* dwarf2loc.c (invalid_synthetic_pointer): Move earlier.
[platform/upstream/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72
73 #include <fcntl.h>
74 #include "gdb_string.h"
75 #include "gdb_assert.h"
76 #include <sys/types.h>
77
78 typedef struct symbol *symbolp;
79 DEF_VEC_P (symbolp);
80
81 /* When non-zero, print basic high level tracing messages.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 struct dwarf2_section_info
104 {
105   asection *asection;
106   const gdb_byte *buffer;
107   bfd_size_type size;
108   /* True if we have tried to read this section.  */
109   int readin;
110 };
111
112 typedef struct dwarf2_section_info dwarf2_section_info_def;
113 DEF_VEC_O (dwarf2_section_info_def);
114
115 /* All offsets in the index are of this type.  It must be
116    architecture-independent.  */
117 typedef uint32_t offset_type;
118
119 DEF_VEC_I (offset_type);
120
121 /* Ensure only legit values are used.  */
122 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
123   do { \
124     gdb_assert ((unsigned int) (value) <= 1); \
125     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
126   } while (0)
127
128 /* Ensure only legit values are used.  */
129 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
130   do { \
131     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
132                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
133     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
134   } while (0)
135
136 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
137 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
138   do { \
139     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
140     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
141   } while (0)
142
143 /* A description of the mapped index.  The file format is described in
144    a comment by the code that writes the index.  */
145 struct mapped_index
146 {
147   /* Index data format version.  */
148   int version;
149
150   /* The total length of the buffer.  */
151   off_t total_size;
152
153   /* A pointer to the address table data.  */
154   const gdb_byte *address_table;
155
156   /* Size of the address table data in bytes.  */
157   offset_type address_table_size;
158
159   /* The symbol table, implemented as a hash table.  */
160   const offset_type *symbol_table;
161
162   /* Size in slots, each slot is 2 offset_types.  */
163   offset_type symbol_table_slots;
164
165   /* A pointer to the constant pool.  */
166   const char *constant_pool;
167 };
168
169 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
170 DEF_VEC_P (dwarf2_per_cu_ptr);
171
172 /* Collection of data recorded per objfile.
173    This hangs off of dwarf2_objfile_data_key.  */
174
175 struct dwarf2_per_objfile
176 {
177   struct dwarf2_section_info info;
178   struct dwarf2_section_info abbrev;
179   struct dwarf2_section_info line;
180   struct dwarf2_section_info loc;
181   struct dwarf2_section_info macinfo;
182   struct dwarf2_section_info macro;
183   struct dwarf2_section_info str;
184   struct dwarf2_section_info ranges;
185   struct dwarf2_section_info addr;
186   struct dwarf2_section_info frame;
187   struct dwarf2_section_info eh_frame;
188   struct dwarf2_section_info gdb_index;
189
190   VEC (dwarf2_section_info_def) *types;
191
192   /* Back link.  */
193   struct objfile *objfile;
194
195   /* Table of all the compilation units.  This is used to locate
196      the target compilation unit of a particular reference.  */
197   struct dwarf2_per_cu_data **all_comp_units;
198
199   /* The number of compilation units in ALL_COMP_UNITS.  */
200   int n_comp_units;
201
202   /* The number of .debug_types-related CUs.  */
203   int n_type_units;
204
205   /* The .debug_types-related CUs (TUs).  */
206   struct signatured_type **all_type_units;
207
208   /* The number of entries in all_type_unit_groups.  */
209   int n_type_unit_groups;
210
211   /* Table of type unit groups.
212      This exists to make it easy to iterate over all CUs and TU groups.  */
213   struct type_unit_group **all_type_unit_groups;
214
215   /* Table of struct type_unit_group objects.
216      The hash key is the DW_AT_stmt_list value.  */
217   htab_t type_unit_groups;
218
219   /* A table mapping .debug_types signatures to its signatured_type entry.
220      This is NULL if the .debug_types section hasn't been read in yet.  */
221   htab_t signatured_types;
222
223   /* Type unit statistics, to see how well the scaling improvements
224      are doing.  */
225   struct tu_stats
226   {
227     int nr_uniq_abbrev_tables;
228     int nr_symtabs;
229     int nr_symtab_sharers;
230     int nr_stmt_less_type_units;
231   } tu_stats;
232
233   /* A chain of compilation units that are currently read in, so that
234      they can be freed later.  */
235   struct dwarf2_per_cu_data *read_in_chain;
236
237   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
238      This is NULL if the table hasn't been allocated yet.  */
239   htab_t dwo_files;
240
241   /* Non-zero if we've check for whether there is a DWP file.  */
242   int dwp_checked;
243
244   /* The DWP file if there is one, or NULL.  */
245   struct dwp_file *dwp_file;
246
247   /* The shared '.dwz' file, if one exists.  This is used when the
248      original data was compressed using 'dwz -m'.  */
249   struct dwz_file *dwz_file;
250
251   /* A flag indicating wether this objfile has a section loaded at a
252      VMA of 0.  */
253   int has_section_at_zero;
254
255   /* True if we are using the mapped index,
256      or we are faking it for OBJF_READNOW's sake.  */
257   unsigned char using_index;
258
259   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
260   struct mapped_index *index_table;
261
262   /* When using index_table, this keeps track of all quick_file_names entries.
263      TUs typically share line table entries with a CU, so we maintain a
264      separate table of all line table entries to support the sharing.
265      Note that while there can be way more TUs than CUs, we've already
266      sorted all the TUs into "type unit groups", grouped by their
267      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
268      CU and its associated TU group if there is one.  */
269   htab_t quick_file_names_table;
270
271   /* Set during partial symbol reading, to prevent queueing of full
272      symbols.  */
273   int reading_partial_symbols;
274
275   /* Table mapping type DIEs to their struct type *.
276      This is NULL if not allocated yet.
277      The mapping is done via (CU/TU + DIE offset) -> type.  */
278   htab_t die_type_hash;
279
280   /* The CUs we recently read.  */
281   VEC (dwarf2_per_cu_ptr) *just_read_cus;
282 };
283
284 static struct dwarf2_per_objfile *dwarf2_per_objfile;
285
286 /* Default names of the debugging sections.  */
287
288 /* Note that if the debugging section has been compressed, it might
289    have a name like .zdebug_info.  */
290
291 static const struct dwarf2_debug_sections dwarf2_elf_names =
292 {
293   { ".debug_info", ".zdebug_info" },
294   { ".debug_abbrev", ".zdebug_abbrev" },
295   { ".debug_line", ".zdebug_line" },
296   { ".debug_loc", ".zdebug_loc" },
297   { ".debug_macinfo", ".zdebug_macinfo" },
298   { ".debug_macro", ".zdebug_macro" },
299   { ".debug_str", ".zdebug_str" },
300   { ".debug_ranges", ".zdebug_ranges" },
301   { ".debug_types", ".zdebug_types" },
302   { ".debug_addr", ".zdebug_addr" },
303   { ".debug_frame", ".zdebug_frame" },
304   { ".eh_frame", NULL },
305   { ".gdb_index", ".zgdb_index" },
306   23
307 };
308
309 /* List of DWO/DWP sections.  */
310
311 static const struct dwop_section_names
312 {
313   struct dwarf2_section_names abbrev_dwo;
314   struct dwarf2_section_names info_dwo;
315   struct dwarf2_section_names line_dwo;
316   struct dwarf2_section_names loc_dwo;
317   struct dwarf2_section_names macinfo_dwo;
318   struct dwarf2_section_names macro_dwo;
319   struct dwarf2_section_names str_dwo;
320   struct dwarf2_section_names str_offsets_dwo;
321   struct dwarf2_section_names types_dwo;
322   struct dwarf2_section_names cu_index;
323   struct dwarf2_section_names tu_index;
324 }
325 dwop_section_names =
326 {
327   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
328   { ".debug_info.dwo", ".zdebug_info.dwo" },
329   { ".debug_line.dwo", ".zdebug_line.dwo" },
330   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
331   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
332   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
333   { ".debug_str.dwo", ".zdebug_str.dwo" },
334   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
335   { ".debug_types.dwo", ".zdebug_types.dwo" },
336   { ".debug_cu_index", ".zdebug_cu_index" },
337   { ".debug_tu_index", ".zdebug_tu_index" },
338 };
339
340 /* local data types */
341
342 /* The data in a compilation unit header, after target2host
343    translation, looks like this.  */
344 struct comp_unit_head
345 {
346   unsigned int length;
347   short version;
348   unsigned char addr_size;
349   unsigned char signed_addr_p;
350   sect_offset abbrev_offset;
351
352   /* Size of file offsets; either 4 or 8.  */
353   unsigned int offset_size;
354
355   /* Size of the length field; either 4 or 12.  */
356   unsigned int initial_length_size;
357
358   /* Offset to the first byte of this compilation unit header in the
359      .debug_info section, for resolving relative reference dies.  */
360   sect_offset offset;
361
362   /* Offset to first die in this cu from the start of the cu.
363      This will be the first byte following the compilation unit header.  */
364   cu_offset first_die_offset;
365 };
366
367 /* Type used for delaying computation of method physnames.
368    See comments for compute_delayed_physnames.  */
369 struct delayed_method_info
370 {
371   /* The type to which the method is attached, i.e., its parent class.  */
372   struct type *type;
373
374   /* The index of the method in the type's function fieldlists.  */
375   int fnfield_index;
376
377   /* The index of the method in the fieldlist.  */
378   int index;
379
380   /* The name of the DIE.  */
381   const char *name;
382
383   /*  The DIE associated with this method.  */
384   struct die_info *die;
385 };
386
387 typedef struct delayed_method_info delayed_method_info;
388 DEF_VEC_O (delayed_method_info);
389
390 /* Internal state when decoding a particular compilation unit.  */
391 struct dwarf2_cu
392 {
393   /* The objfile containing this compilation unit.  */
394   struct objfile *objfile;
395
396   /* The header of the compilation unit.  */
397   struct comp_unit_head header;
398
399   /* Base address of this compilation unit.  */
400   CORE_ADDR base_address;
401
402   /* Non-zero if base_address has been set.  */
403   int base_known;
404
405   /* The language we are debugging.  */
406   enum language language;
407   const struct language_defn *language_defn;
408
409   const char *producer;
410
411   /* The generic symbol table building routines have separate lists for
412      file scope symbols and all all other scopes (local scopes).  So
413      we need to select the right one to pass to add_symbol_to_list().
414      We do it by keeping a pointer to the correct list in list_in_scope.
415
416      FIXME: The original dwarf code just treated the file scope as the
417      first local scope, and all other local scopes as nested local
418      scopes, and worked fine.  Check to see if we really need to
419      distinguish these in buildsym.c.  */
420   struct pending **list_in_scope;
421
422   /* The abbrev table for this CU.
423      Normally this points to the abbrev table in the objfile.
424      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
425   struct abbrev_table *abbrev_table;
426
427   /* Hash table holding all the loaded partial DIEs
428      with partial_die->offset.SECT_OFF as hash.  */
429   htab_t partial_dies;
430
431   /* Storage for things with the same lifetime as this read-in compilation
432      unit, including partial DIEs.  */
433   struct obstack comp_unit_obstack;
434
435   /* When multiple dwarf2_cu structures are living in memory, this field
436      chains them all together, so that they can be released efficiently.
437      We will probably also want a generation counter so that most-recently-used
438      compilation units are cached...  */
439   struct dwarf2_per_cu_data *read_in_chain;
440
441   /* Backchain to our per_cu entry if the tree has been built.  */
442   struct dwarf2_per_cu_data *per_cu;
443
444   /* How many compilation units ago was this CU last referenced?  */
445   int last_used;
446
447   /* A hash table of DIE cu_offset for following references with
448      die_info->offset.sect_off as hash.  */
449   htab_t die_hash;
450
451   /* Full DIEs if read in.  */
452   struct die_info *dies;
453
454   /* A set of pointers to dwarf2_per_cu_data objects for compilation
455      units referenced by this one.  Only set during full symbol processing;
456      partial symbol tables do not have dependencies.  */
457   htab_t dependencies;
458
459   /* Header data from the line table, during full symbol processing.  */
460   struct line_header *line_header;
461
462   /* A list of methods which need to have physnames computed
463      after all type information has been read.  */
464   VEC (delayed_method_info) *method_list;
465
466   /* To be copied to symtab->call_site_htab.  */
467   htab_t call_site_htab;
468
469   /* Non-NULL if this CU came from a DWO file.
470      There is an invariant here that is important to remember:
471      Except for attributes copied from the top level DIE in the "main"
472      (or "stub") file in preparation for reading the DWO file
473      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
474      Either there isn't a DWO file (in which case this is NULL and the point
475      is moot), or there is and either we're not going to read it (in which
476      case this is NULL) or there is and we are reading it (in which case this
477      is non-NULL).  */
478   struct dwo_unit *dwo_unit;
479
480   /* The DW_AT_addr_base attribute if present, zero otherwise
481      (zero is a valid value though).
482      Note this value comes from the stub CU/TU's DIE.  */
483   ULONGEST addr_base;
484
485   /* The DW_AT_ranges_base attribute if present, zero otherwise
486      (zero is a valid value though).
487      Note this value comes from the stub CU/TU's DIE.
488      Also note that the value is zero in the non-DWO case so this value can
489      be used without needing to know whether DWO files are in use or not.
490      N.B. This does not apply to DW_AT_ranges appearing in
491      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
492      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
493      DW_AT_ranges_base *would* have to be applied, and we'd have to care
494      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
495   ULONGEST ranges_base;
496
497   /* Mark used when releasing cached dies.  */
498   unsigned int mark : 1;
499
500   /* This CU references .debug_loc.  See the symtab->locations_valid field.
501      This test is imperfect as there may exist optimized debug code not using
502      any location list and still facing inlining issues if handled as
503      unoptimized code.  For a future better test see GCC PR other/32998.  */
504   unsigned int has_loclist : 1;
505
506   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
507      if all the producer_is_* fields are valid.  This information is cached
508      because profiling CU expansion showed excessive time spent in
509      producer_is_gxx_lt_4_6.  */
510   unsigned int checked_producer : 1;
511   unsigned int producer_is_gxx_lt_4_6 : 1;
512   unsigned int producer_is_gcc_lt_4_3 : 1;
513   unsigned int producer_is_icc : 1;
514
515   /* When set, the file that we're processing is known to have
516      debugging info for C++ namespaces.  GCC 3.3.x did not produce
517      this information, but later versions do.  */
518
519   unsigned int processing_has_namespace_info : 1;
520 };
521
522 /* Persistent data held for a compilation unit, even when not
523    processing it.  We put a pointer to this structure in the
524    read_symtab_private field of the psymtab.  */
525
526 struct dwarf2_per_cu_data
527 {
528   /* The start offset and length of this compilation unit.
529      NOTE: Unlike comp_unit_head.length, this length includes
530      initial_length_size.
531      If the DIE refers to a DWO file, this is always of the original die,
532      not the DWO file.  */
533   sect_offset offset;
534   unsigned int length;
535
536   /* Flag indicating this compilation unit will be read in before
537      any of the current compilation units are processed.  */
538   unsigned int queued : 1;
539
540   /* This flag will be set when reading partial DIEs if we need to load
541      absolutely all DIEs for this compilation unit, instead of just the ones
542      we think are interesting.  It gets set if we look for a DIE in the
543      hash table and don't find it.  */
544   unsigned int load_all_dies : 1;
545
546   /* Non-zero if this CU is from .debug_types.
547      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
548      this is non-zero.  */
549   unsigned int is_debug_types : 1;
550
551   /* Non-zero if this CU is from the .dwz file.  */
552   unsigned int is_dwz : 1;
553
554   /* The section this CU/TU lives in.
555      If the DIE refers to a DWO file, this is always the original die,
556      not the DWO file.  */
557   struct dwarf2_section_info *section;
558
559   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
560      of the CU cache it gets reset to NULL again.  */
561   struct dwarf2_cu *cu;
562
563   /* The corresponding objfile.
564      Normally we can get the objfile from dwarf2_per_objfile.
565      However we can enter this file with just a "per_cu" handle.  */
566   struct objfile *objfile;
567
568   /* When using partial symbol tables, the 'psymtab' field is active.
569      Otherwise the 'quick' field is active.  */
570   union
571   {
572     /* The partial symbol table associated with this compilation unit,
573        or NULL for unread partial units.  */
574     struct partial_symtab *psymtab;
575
576     /* Data needed by the "quick" functions.  */
577     struct dwarf2_per_cu_quick_data *quick;
578   } v;
579
580   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
581      while reading psymtabs, used to compute the psymtab dependencies,
582      and then cleared.  Then it is filled in again while reading full
583      symbols, and only deleted when the objfile is destroyed.
584
585      This is also used to work around a difference between the way gold
586      generates .gdb_index version <=7 and the way gdb does.  Arguably this
587      is a gold bug.  For symbols coming from TUs, gold records in the index
588      the CU that includes the TU instead of the TU itself.  This breaks
589      dw2_lookup_symbol: It assumes that if the index says symbol X lives
590      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
591      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
592      we need to look in TU Z to find X.  Fortunately, this is akin to
593      DW_TAG_imported_unit, so we just use the same mechanism: For
594      .gdb_index version <=7 this also records the TUs that the CU referred
595      to.  Concurrently with this change gdb was modified to emit version 8
596      indices so we only pay a price for gold generated indices.  */
597   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
598 };
599
600 /* Entry in the signatured_types hash table.  */
601
602 struct signatured_type
603 {
604   /* The "per_cu" object of this type.
605      This struct is used iff per_cu.is_debug_types.
606      N.B.: This is the first member so that it's easy to convert pointers
607      between them.  */
608   struct dwarf2_per_cu_data per_cu;
609
610   /* The type's signature.  */
611   ULONGEST signature;
612
613   /* Offset in the TU of the type's DIE, as read from the TU header.
614      If this TU is a DWO stub and the definition lives in a DWO file
615      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
616   cu_offset type_offset_in_tu;
617
618   /* Offset in the section of the type's DIE.
619      If the definition lives in a DWO file, this is the offset in the
620      .debug_types.dwo section.
621      The value is zero until the actual value is known.
622      Zero is otherwise not a valid section offset.  */
623   sect_offset type_offset_in_section;
624
625   /* Type units are grouped by their DW_AT_stmt_list entry so that they
626      can share them.  This points to the containing symtab.  */
627   struct type_unit_group *type_unit_group;
628
629   /* The type.
630      The first time we encounter this type we fully read it in and install it
631      in the symbol tables.  Subsequent times we only need the type.  */
632   struct type *type;
633 };
634
635 typedef struct signatured_type *sig_type_ptr;
636 DEF_VEC_P (sig_type_ptr);
637
638 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
639    This includes type_unit_group and quick_file_names.  */
640
641 struct stmt_list_hash
642 {
643   /* The DWO unit this table is from or NULL if there is none.  */
644   struct dwo_unit *dwo_unit;
645
646   /* Offset in .debug_line or .debug_line.dwo.  */
647   sect_offset line_offset;
648 };
649
650 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
651    an object of this type.  */
652
653 struct type_unit_group
654 {
655   /* dwarf2read.c's main "handle" on a TU symtab.
656      To simplify things we create an artificial CU that "includes" all the
657      type units using this stmt_list so that the rest of the code still has
658      a "per_cu" handle on the symtab.
659      This PER_CU is recognized by having no section.  */
660 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
661   struct dwarf2_per_cu_data per_cu;
662
663   /* The TUs that share this DW_AT_stmt_list entry.
664      This is added to while parsing type units to build partial symtabs,
665      and is deleted afterwards and not used again.  */
666   VEC (sig_type_ptr) *tus;
667
668   /* The primary symtab.
669      Type units in a group needn't all be defined in the same source file,
670      so we create an essentially anonymous symtab as the primary symtab.  */
671   struct symtab *primary_symtab;
672
673   /* The data used to construct the hash key.  */
674   struct stmt_list_hash hash;
675
676   /* The number of symtabs from the line header.
677      The value here must match line_header.num_file_names.  */
678   unsigned int num_symtabs;
679
680   /* The symbol tables for this TU (obtained from the files listed in
681      DW_AT_stmt_list).
682      WARNING: The order of entries here must match the order of entries
683      in the line header.  After the first TU using this type_unit_group, the
684      line header for the subsequent TUs is recreated from this.  This is done
685      because we need to use the same symtabs for each TU using the same
686      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
687      there's no guarantee the line header doesn't have duplicate entries.  */
688   struct symtab **symtabs;
689 };
690
691 /* These sections are what may appear in a DWO file.  */
692
693 struct dwo_sections
694 {
695   struct dwarf2_section_info abbrev;
696   struct dwarf2_section_info line;
697   struct dwarf2_section_info loc;
698   struct dwarf2_section_info macinfo;
699   struct dwarf2_section_info macro;
700   struct dwarf2_section_info str;
701   struct dwarf2_section_info str_offsets;
702   /* In the case of a virtual DWO file, these two are unused.  */
703   struct dwarf2_section_info info;
704   VEC (dwarf2_section_info_def) *types;
705 };
706
707 /* CUs/TUs in DWP/DWO files.  */
708
709 struct dwo_unit
710 {
711   /* Backlink to the containing struct dwo_file.  */
712   struct dwo_file *dwo_file;
713
714   /* The "id" that distinguishes this CU/TU.
715      .debug_info calls this "dwo_id", .debug_types calls this "signature".
716      Since signatures came first, we stick with it for consistency.  */
717   ULONGEST signature;
718
719   /* The section this CU/TU lives in, in the DWO file.  */
720   struct dwarf2_section_info *section;
721
722   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
723   sect_offset offset;
724   unsigned int length;
725
726   /* For types, offset in the type's DIE of the type defined by this TU.  */
727   cu_offset type_offset_in_tu;
728 };
729
730 /* Data for one DWO file.
731    This includes virtual DWO files that have been packaged into a
732    DWP file.  */
733
734 struct dwo_file
735 {
736   /* The DW_AT_GNU_dwo_name attribute.
737      For virtual DWO files the name is constructed from the section offsets
738      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
739      from related CU+TUs.  */
740   const char *dwo_name;
741
742   /* The DW_AT_comp_dir attribute.  */
743   const char *comp_dir;
744
745   /* The bfd, when the file is open.  Otherwise this is NULL.
746      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
747   bfd *dbfd;
748
749   /* Section info for this file.  */
750   struct dwo_sections sections;
751
752   /* The CU in the file.
753      We only support one because having more than one requires hacking the
754      dwo_name of each to match, which is highly unlikely to happen.
755      Doing this means all TUs can share comp_dir: We also assume that
756      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
757   struct dwo_unit *cu;
758
759   /* Table of TUs in the file.
760      Each element is a struct dwo_unit.  */
761   htab_t tus;
762 };
763
764 /* These sections are what may appear in a DWP file.  */
765
766 struct dwp_sections
767 {
768   struct dwarf2_section_info str;
769   struct dwarf2_section_info cu_index;
770   struct dwarf2_section_info tu_index;
771   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
772      by section number.  We don't need to record them here.  */
773 };
774
775 /* These sections are what may appear in a virtual DWO file.  */
776
777 struct virtual_dwo_sections
778 {
779   struct dwarf2_section_info abbrev;
780   struct dwarf2_section_info line;
781   struct dwarf2_section_info loc;
782   struct dwarf2_section_info macinfo;
783   struct dwarf2_section_info macro;
784   struct dwarf2_section_info str_offsets;
785   /* Each DWP hash table entry records one CU or one TU.
786      That is recorded here, and copied to dwo_unit.section.  */
787   struct dwarf2_section_info info_or_types;
788 };
789
790 /* Contents of DWP hash tables.  */
791
792 struct dwp_hash_table
793 {
794   uint32_t nr_units, nr_slots;
795   const gdb_byte *hash_table, *unit_table, *section_pool;
796 };
797
798 /* Data for one DWP file.  */
799
800 struct dwp_file
801 {
802   /* Name of the file.  */
803   const char *name;
804
805   /* The bfd, when the file is open.  Otherwise this is NULL.  */
806   bfd *dbfd;
807
808   /* Section info for this file.  */
809   struct dwp_sections sections;
810
811   /* Table of CUs in the file. */
812   const struct dwp_hash_table *cus;
813
814   /* Table of TUs in the file.  */
815   const struct dwp_hash_table *tus;
816
817   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
818   htab_t loaded_cutus;
819
820   /* Table to map ELF section numbers to their sections.  */
821   unsigned int num_sections;
822   asection **elf_sections;
823 };
824
825 /* This represents a '.dwz' file.  */
826
827 struct dwz_file
828 {
829   /* A dwz file can only contain a few sections.  */
830   struct dwarf2_section_info abbrev;
831   struct dwarf2_section_info info;
832   struct dwarf2_section_info str;
833   struct dwarf2_section_info line;
834   struct dwarf2_section_info macro;
835   struct dwarf2_section_info gdb_index;
836
837   /* The dwz's BFD.  */
838   bfd *dwz_bfd;
839 };
840
841 /* Struct used to pass misc. parameters to read_die_and_children, et
842    al.  which are used for both .debug_info and .debug_types dies.
843    All parameters here are unchanging for the life of the call.  This
844    struct exists to abstract away the constant parameters of die reading.  */
845
846 struct die_reader_specs
847 {
848   /* die_section->asection->owner.  */
849   bfd* abfd;
850
851   /* The CU of the DIE we are parsing.  */
852   struct dwarf2_cu *cu;
853
854   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
855   struct dwo_file *dwo_file;
856
857   /* The section the die comes from.
858      This is either .debug_info or .debug_types, or the .dwo variants.  */
859   struct dwarf2_section_info *die_section;
860
861   /* die_section->buffer.  */
862   const gdb_byte *buffer;
863
864   /* The end of the buffer.  */
865   const gdb_byte *buffer_end;
866 };
867
868 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
869 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
870                                       const gdb_byte *info_ptr,
871                                       struct die_info *comp_unit_die,
872                                       int has_children,
873                                       void *data);
874
875 /* The line number information for a compilation unit (found in the
876    .debug_line section) begins with a "statement program header",
877    which contains the following information.  */
878 struct line_header
879 {
880   unsigned int total_length;
881   unsigned short version;
882   unsigned int header_length;
883   unsigned char minimum_instruction_length;
884   unsigned char maximum_ops_per_instruction;
885   unsigned char default_is_stmt;
886   int line_base;
887   unsigned char line_range;
888   unsigned char opcode_base;
889
890   /* standard_opcode_lengths[i] is the number of operands for the
891      standard opcode whose value is i.  This means that
892      standard_opcode_lengths[0] is unused, and the last meaningful
893      element is standard_opcode_lengths[opcode_base - 1].  */
894   unsigned char *standard_opcode_lengths;
895
896   /* The include_directories table.  NOTE!  These strings are not
897      allocated with xmalloc; instead, they are pointers into
898      debug_line_buffer.  If you try to free them, `free' will get
899      indigestion.  */
900   unsigned int num_include_dirs, include_dirs_size;
901   const char **include_dirs;
902
903   /* The file_names table.  NOTE!  These strings are not allocated
904      with xmalloc; instead, they are pointers into debug_line_buffer.
905      Don't try to free them directly.  */
906   unsigned int num_file_names, file_names_size;
907   struct file_entry
908   {
909     const char *name;
910     unsigned int dir_index;
911     unsigned int mod_time;
912     unsigned int length;
913     int included_p; /* Non-zero if referenced by the Line Number Program.  */
914     struct symtab *symtab; /* The associated symbol table, if any.  */
915   } *file_names;
916
917   /* The start and end of the statement program following this
918      header.  These point into dwarf2_per_objfile->line_buffer.  */
919   const gdb_byte *statement_program_start, *statement_program_end;
920 };
921
922 /* When we construct a partial symbol table entry we only
923    need this much information.  */
924 struct partial_die_info
925   {
926     /* Offset of this DIE.  */
927     sect_offset offset;
928
929     /* DWARF-2 tag for this DIE.  */
930     ENUM_BITFIELD(dwarf_tag) tag : 16;
931
932     /* Assorted flags describing the data found in this DIE.  */
933     unsigned int has_children : 1;
934     unsigned int is_external : 1;
935     unsigned int is_declaration : 1;
936     unsigned int has_type : 1;
937     unsigned int has_specification : 1;
938     unsigned int has_pc_info : 1;
939     unsigned int may_be_inlined : 1;
940
941     /* Flag set if the SCOPE field of this structure has been
942        computed.  */
943     unsigned int scope_set : 1;
944
945     /* Flag set if the DIE has a byte_size attribute.  */
946     unsigned int has_byte_size : 1;
947
948     /* Flag set if any of the DIE's children are template arguments.  */
949     unsigned int has_template_arguments : 1;
950
951     /* Flag set if fixup_partial_die has been called on this die.  */
952     unsigned int fixup_called : 1;
953
954     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
955     unsigned int is_dwz : 1;
956
957     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
958     unsigned int spec_is_dwz : 1;
959
960     /* The name of this DIE.  Normally the value of DW_AT_name, but
961        sometimes a default name for unnamed DIEs.  */
962     const char *name;
963
964     /* The linkage name, if present.  */
965     const char *linkage_name;
966
967     /* The scope to prepend to our children.  This is generally
968        allocated on the comp_unit_obstack, so will disappear
969        when this compilation unit leaves the cache.  */
970     const char *scope;
971
972     /* Some data associated with the partial DIE.  The tag determines
973        which field is live.  */
974     union
975     {
976       /* The location description associated with this DIE, if any.  */
977       struct dwarf_block *locdesc;
978       /* The offset of an import, for DW_TAG_imported_unit.  */
979       sect_offset offset;
980     } d;
981
982     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
983     CORE_ADDR lowpc;
984     CORE_ADDR highpc;
985
986     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
987        DW_AT_sibling, if any.  */
988     /* NOTE: This member isn't strictly necessary, read_partial_die could
989        return DW_AT_sibling values to its caller load_partial_dies.  */
990     const gdb_byte *sibling;
991
992     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
993        DW_AT_specification (or DW_AT_abstract_origin or
994        DW_AT_extension).  */
995     sect_offset spec_offset;
996
997     /* Pointers to this DIE's parent, first child, and next sibling,
998        if any.  */
999     struct partial_die_info *die_parent, *die_child, *die_sibling;
1000   };
1001
1002 /* This data structure holds the information of an abbrev.  */
1003 struct abbrev_info
1004   {
1005     unsigned int number;        /* number identifying abbrev */
1006     enum dwarf_tag tag;         /* dwarf tag */
1007     unsigned short has_children;                /* boolean */
1008     unsigned short num_attrs;   /* number of attributes */
1009     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1010     struct abbrev_info *next;   /* next in chain */
1011   };
1012
1013 struct attr_abbrev
1014   {
1015     ENUM_BITFIELD(dwarf_attribute) name : 16;
1016     ENUM_BITFIELD(dwarf_form) form : 16;
1017   };
1018
1019 /* Size of abbrev_table.abbrev_hash_table.  */
1020 #define ABBREV_HASH_SIZE 121
1021
1022 /* Top level data structure to contain an abbreviation table.  */
1023
1024 struct abbrev_table
1025 {
1026   /* Where the abbrev table came from.
1027      This is used as a sanity check when the table is used.  */
1028   sect_offset offset;
1029
1030   /* Storage for the abbrev table.  */
1031   struct obstack abbrev_obstack;
1032
1033   /* Hash table of abbrevs.
1034      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1035      It could be statically allocated, but the previous code didn't so we
1036      don't either.  */
1037   struct abbrev_info **abbrevs;
1038 };
1039
1040 /* Attributes have a name and a value.  */
1041 struct attribute
1042   {
1043     ENUM_BITFIELD(dwarf_attribute) name : 16;
1044     ENUM_BITFIELD(dwarf_form) form : 15;
1045
1046     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1047        field should be in u.str (existing only for DW_STRING) but it is kept
1048        here for better struct attribute alignment.  */
1049     unsigned int string_is_canonical : 1;
1050
1051     union
1052       {
1053         const char *str;
1054         struct dwarf_block *blk;
1055         ULONGEST unsnd;
1056         LONGEST snd;
1057         CORE_ADDR addr;
1058         ULONGEST signature;
1059       }
1060     u;
1061   };
1062
1063 /* This data structure holds a complete die structure.  */
1064 struct die_info
1065   {
1066     /* DWARF-2 tag for this DIE.  */
1067     ENUM_BITFIELD(dwarf_tag) tag : 16;
1068
1069     /* Number of attributes */
1070     unsigned char num_attrs;
1071
1072     /* True if we're presently building the full type name for the
1073        type derived from this DIE.  */
1074     unsigned char building_fullname : 1;
1075
1076     /* Abbrev number */
1077     unsigned int abbrev;
1078
1079     /* Offset in .debug_info or .debug_types section.  */
1080     sect_offset offset;
1081
1082     /* The dies in a compilation unit form an n-ary tree.  PARENT
1083        points to this die's parent; CHILD points to the first child of
1084        this node; and all the children of a given node are chained
1085        together via their SIBLING fields.  */
1086     struct die_info *child;     /* Its first child, if any.  */
1087     struct die_info *sibling;   /* Its next sibling, if any.  */
1088     struct die_info *parent;    /* Its parent, if any.  */
1089
1090     /* An array of attributes, with NUM_ATTRS elements.  There may be
1091        zero, but it's not common and zero-sized arrays are not
1092        sufficiently portable C.  */
1093     struct attribute attrs[1];
1094   };
1095
1096 /* Get at parts of an attribute structure.  */
1097
1098 #define DW_STRING(attr)    ((attr)->u.str)
1099 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1100 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1101 #define DW_BLOCK(attr)     ((attr)->u.blk)
1102 #define DW_SND(attr)       ((attr)->u.snd)
1103 #define DW_ADDR(attr)      ((attr)->u.addr)
1104 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1105
1106 /* Blocks are a bunch of untyped bytes.  */
1107 struct dwarf_block
1108   {
1109     size_t size;
1110
1111     /* Valid only if SIZE is not zero.  */
1112     const gdb_byte *data;
1113   };
1114
1115 #ifndef ATTR_ALLOC_CHUNK
1116 #define ATTR_ALLOC_CHUNK 4
1117 #endif
1118
1119 /* Allocate fields for structs, unions and enums in this size.  */
1120 #ifndef DW_FIELD_ALLOC_CHUNK
1121 #define DW_FIELD_ALLOC_CHUNK 4
1122 #endif
1123
1124 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1125    but this would require a corresponding change in unpack_field_as_long
1126    and friends.  */
1127 static int bits_per_byte = 8;
1128
1129 /* The routines that read and process dies for a C struct or C++ class
1130    pass lists of data member fields and lists of member function fields
1131    in an instance of a field_info structure, as defined below.  */
1132 struct field_info
1133   {
1134     /* List of data member and baseclasses fields.  */
1135     struct nextfield
1136       {
1137         struct nextfield *next;
1138         int accessibility;
1139         int virtuality;
1140         struct field field;
1141       }
1142      *fields, *baseclasses;
1143
1144     /* Number of fields (including baseclasses).  */
1145     int nfields;
1146
1147     /* Number of baseclasses.  */
1148     int nbaseclasses;
1149
1150     /* Set if the accesibility of one of the fields is not public.  */
1151     int non_public_fields;
1152
1153     /* Member function fields array, entries are allocated in the order they
1154        are encountered in the object file.  */
1155     struct nextfnfield
1156       {
1157         struct nextfnfield *next;
1158         struct fn_field fnfield;
1159       }
1160      *fnfields;
1161
1162     /* Member function fieldlist array, contains name of possibly overloaded
1163        member function, number of overloaded member functions and a pointer
1164        to the head of the member function field chain.  */
1165     struct fnfieldlist
1166       {
1167         const char *name;
1168         int length;
1169         struct nextfnfield *head;
1170       }
1171      *fnfieldlists;
1172
1173     /* Number of entries in the fnfieldlists array.  */
1174     int nfnfields;
1175
1176     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1177        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1178     struct typedef_field_list
1179       {
1180         struct typedef_field field;
1181         struct typedef_field_list *next;
1182       }
1183     *typedef_field_list;
1184     unsigned typedef_field_list_count;
1185   };
1186
1187 /* One item on the queue of compilation units to read in full symbols
1188    for.  */
1189 struct dwarf2_queue_item
1190 {
1191   struct dwarf2_per_cu_data *per_cu;
1192   enum language pretend_language;
1193   struct dwarf2_queue_item *next;
1194 };
1195
1196 /* The current queue.  */
1197 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1198
1199 /* Loaded secondary compilation units are kept in memory until they
1200    have not been referenced for the processing of this many
1201    compilation units.  Set this to zero to disable caching.  Cache
1202    sizes of up to at least twenty will improve startup time for
1203    typical inter-CU-reference binaries, at an obvious memory cost.  */
1204 static int dwarf2_max_cache_age = 5;
1205 static void
1206 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1207                            struct cmd_list_element *c, const char *value)
1208 {
1209   fprintf_filtered (file, _("The upper bound on the age of cached "
1210                             "dwarf2 compilation units is %s.\n"),
1211                     value);
1212 }
1213
1214
1215 /* Various complaints about symbol reading that don't abort the process.  */
1216
1217 static void
1218 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1219 {
1220   complaint (&symfile_complaints,
1221              _("statement list doesn't fit in .debug_line section"));
1222 }
1223
1224 static void
1225 dwarf2_debug_line_missing_file_complaint (void)
1226 {
1227   complaint (&symfile_complaints,
1228              _(".debug_line section has line data without a file"));
1229 }
1230
1231 static void
1232 dwarf2_debug_line_missing_end_sequence_complaint (void)
1233 {
1234   complaint (&symfile_complaints,
1235              _(".debug_line section has line "
1236                "program sequence without an end"));
1237 }
1238
1239 static void
1240 dwarf2_complex_location_expr_complaint (void)
1241 {
1242   complaint (&symfile_complaints, _("location expression too complex"));
1243 }
1244
1245 static void
1246 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1247                                               int arg3)
1248 {
1249   complaint (&symfile_complaints,
1250              _("const value length mismatch for '%s', got %d, expected %d"),
1251              arg1, arg2, arg3);
1252 }
1253
1254 static void
1255 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1256 {
1257   complaint (&symfile_complaints,
1258              _("debug info runs off end of %s section"
1259                " [in module %s]"),
1260              section->asection->name,
1261              bfd_get_filename (section->asection->owner));
1262 }
1263
1264 static void
1265 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1266 {
1267   complaint (&symfile_complaints,
1268              _("macro debug info contains a "
1269                "malformed macro definition:\n`%s'"),
1270              arg1);
1271 }
1272
1273 static void
1274 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1275 {
1276   complaint (&symfile_complaints,
1277              _("invalid attribute class or form for '%s' in '%s'"),
1278              arg1, arg2);
1279 }
1280
1281 /* local function prototypes */
1282
1283 static void dwarf2_locate_sections (bfd *, asection *, void *);
1284
1285 static void dwarf2_find_base_address (struct die_info *die,
1286                                       struct dwarf2_cu *cu);
1287
1288 static struct partial_symtab *create_partial_symtab
1289   (struct dwarf2_per_cu_data *per_cu, const char *name);
1290
1291 static void dwarf2_build_psymtabs_hard (struct objfile *);
1292
1293 static void scan_partial_symbols (struct partial_die_info *,
1294                                   CORE_ADDR *, CORE_ADDR *,
1295                                   int, struct dwarf2_cu *);
1296
1297 static void add_partial_symbol (struct partial_die_info *,
1298                                 struct dwarf2_cu *);
1299
1300 static void add_partial_namespace (struct partial_die_info *pdi,
1301                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1302                                    int need_pc, struct dwarf2_cu *cu);
1303
1304 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1305                                 CORE_ADDR *highpc, int need_pc,
1306                                 struct dwarf2_cu *cu);
1307
1308 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1309                                      struct dwarf2_cu *cu);
1310
1311 static void add_partial_subprogram (struct partial_die_info *pdi,
1312                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1313                                     int need_pc, struct dwarf2_cu *cu);
1314
1315 static void dwarf2_read_symtab (struct partial_symtab *,
1316                                 struct objfile *);
1317
1318 static void psymtab_to_symtab_1 (struct partial_symtab *);
1319
1320 static struct abbrev_info *abbrev_table_lookup_abbrev
1321   (const struct abbrev_table *, unsigned int);
1322
1323 static struct abbrev_table *abbrev_table_read_table
1324   (struct dwarf2_section_info *, sect_offset);
1325
1326 static void abbrev_table_free (struct abbrev_table *);
1327
1328 static void abbrev_table_free_cleanup (void *);
1329
1330 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1331                                  struct dwarf2_section_info *);
1332
1333 static void dwarf2_free_abbrev_table (void *);
1334
1335 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1336
1337 static struct partial_die_info *load_partial_dies
1338   (const struct die_reader_specs *, const gdb_byte *, int);
1339
1340 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1341                                          struct partial_die_info *,
1342                                          struct abbrev_info *,
1343                                          unsigned int,
1344                                          const gdb_byte *);
1345
1346 static struct partial_die_info *find_partial_die (sect_offset, int,
1347                                                   struct dwarf2_cu *);
1348
1349 static void fixup_partial_die (struct partial_die_info *,
1350                                struct dwarf2_cu *);
1351
1352 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1353                                        struct attribute *, struct attr_abbrev *,
1354                                        const gdb_byte *);
1355
1356 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1357
1358 static int read_1_signed_byte (bfd *, const gdb_byte *);
1359
1360 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1361
1362 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1363
1364 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1365
1366 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1367                                unsigned int *);
1368
1369 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1370
1371 static LONGEST read_checked_initial_length_and_offset
1372   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1373    unsigned int *, unsigned int *);
1374
1375 static LONGEST read_offset (bfd *, const gdb_byte *,
1376                             const struct comp_unit_head *,
1377                             unsigned int *);
1378
1379 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1380
1381 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1382                                        sect_offset);
1383
1384 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1385
1386 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1387
1388 static const char *read_indirect_string (bfd *, const gdb_byte *,
1389                                          const struct comp_unit_head *,
1390                                          unsigned int *);
1391
1392 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1393
1394 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1395
1396 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1397
1398 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1399                                               const gdb_byte *,
1400                                               unsigned int *);
1401
1402 static const char *read_str_index (const struct die_reader_specs *reader,
1403                                    struct dwarf2_cu *cu, ULONGEST str_index);
1404
1405 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1406
1407 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1408                                       struct dwarf2_cu *);
1409
1410 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1411                                                 unsigned int);
1412
1413 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1414                                struct dwarf2_cu *cu);
1415
1416 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1417
1418 static struct die_info *die_specification (struct die_info *die,
1419                                            struct dwarf2_cu **);
1420
1421 static void free_line_header (struct line_header *lh);
1422
1423 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1424                                                      struct dwarf2_cu *cu);
1425
1426 static void dwarf_decode_lines (struct line_header *, const char *,
1427                                 struct dwarf2_cu *, struct partial_symtab *,
1428                                 int);
1429
1430 static void dwarf2_start_subfile (const char *, const char *, const char *);
1431
1432 static void dwarf2_start_symtab (struct dwarf2_cu *,
1433                                  const char *, const char *, CORE_ADDR);
1434
1435 static struct symbol *new_symbol (struct die_info *, struct type *,
1436                                   struct dwarf2_cu *);
1437
1438 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1439                                        struct dwarf2_cu *, struct symbol *);
1440
1441 static void dwarf2_const_value (struct attribute *, struct symbol *,
1442                                 struct dwarf2_cu *);
1443
1444 static void dwarf2_const_value_attr (struct attribute *attr,
1445                                      struct type *type,
1446                                      const char *name,
1447                                      struct obstack *obstack,
1448                                      struct dwarf2_cu *cu, LONGEST *value,
1449                                      const gdb_byte **bytes,
1450                                      struct dwarf2_locexpr_baton **baton);
1451
1452 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1453
1454 static int need_gnat_info (struct dwarf2_cu *);
1455
1456 static struct type *die_descriptive_type (struct die_info *,
1457                                           struct dwarf2_cu *);
1458
1459 static void set_descriptive_type (struct type *, struct die_info *,
1460                                   struct dwarf2_cu *);
1461
1462 static struct type *die_containing_type (struct die_info *,
1463                                          struct dwarf2_cu *);
1464
1465 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1466                                      struct dwarf2_cu *);
1467
1468 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1469
1470 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1471
1472 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1473
1474 static char *typename_concat (struct obstack *obs, const char *prefix,
1475                               const char *suffix, int physname,
1476                               struct dwarf2_cu *cu);
1477
1478 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1479
1480 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1481
1482 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1483
1484 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1485
1486 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1487
1488 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1489                                struct dwarf2_cu *, struct partial_symtab *);
1490
1491 static int dwarf2_get_pc_bounds (struct die_info *,
1492                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1493                                  struct partial_symtab *);
1494
1495 static void get_scope_pc_bounds (struct die_info *,
1496                                  CORE_ADDR *, CORE_ADDR *,
1497                                  struct dwarf2_cu *);
1498
1499 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1500                                         CORE_ADDR, struct dwarf2_cu *);
1501
1502 static void dwarf2_add_field (struct field_info *, struct die_info *,
1503                               struct dwarf2_cu *);
1504
1505 static void dwarf2_attach_fields_to_type (struct field_info *,
1506                                           struct type *, struct dwarf2_cu *);
1507
1508 static void dwarf2_add_member_fn (struct field_info *,
1509                                   struct die_info *, struct type *,
1510                                   struct dwarf2_cu *);
1511
1512 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1513                                              struct type *,
1514                                              struct dwarf2_cu *);
1515
1516 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1517
1518 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1519
1520 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1521
1522 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1523
1524 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1525
1526 static struct type *read_module_type (struct die_info *die,
1527                                       struct dwarf2_cu *cu);
1528
1529 static const char *namespace_name (struct die_info *die,
1530                                    int *is_anonymous, struct dwarf2_cu *);
1531
1532 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1533
1534 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1535
1536 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1537                                                        struct dwarf2_cu *);
1538
1539 static struct die_info *read_die_and_siblings_1
1540   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1541    struct die_info *);
1542
1543 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1544                                                const gdb_byte *info_ptr,
1545                                                const gdb_byte **new_info_ptr,
1546                                                struct die_info *parent);
1547
1548 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1549                                         struct die_info **, const gdb_byte *,
1550                                         int *, int);
1551
1552 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1553                                       struct die_info **, const gdb_byte *,
1554                                       int *);
1555
1556 static void process_die (struct die_info *, struct dwarf2_cu *);
1557
1558 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1559                                              struct obstack *);
1560
1561 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1562
1563 static const char *dwarf2_full_name (const char *name,
1564                                      struct die_info *die,
1565                                      struct dwarf2_cu *cu);
1566
1567 static const char *dwarf2_physname (const char *name, struct die_info *die,
1568                                     struct dwarf2_cu *cu);
1569
1570 static struct die_info *dwarf2_extension (struct die_info *die,
1571                                           struct dwarf2_cu **);
1572
1573 static const char *dwarf_tag_name (unsigned int);
1574
1575 static const char *dwarf_attr_name (unsigned int);
1576
1577 static const char *dwarf_form_name (unsigned int);
1578
1579 static char *dwarf_bool_name (unsigned int);
1580
1581 static const char *dwarf_type_encoding_name (unsigned int);
1582
1583 static struct die_info *sibling_die (struct die_info *);
1584
1585 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1586
1587 static void dump_die_for_error (struct die_info *);
1588
1589 static void dump_die_1 (struct ui_file *, int level, int max_level,
1590                         struct die_info *);
1591
1592 /*static*/ void dump_die (struct die_info *, int max_level);
1593
1594 static void store_in_ref_table (struct die_info *,
1595                                 struct dwarf2_cu *);
1596
1597 static int is_ref_attr (struct attribute *);
1598
1599 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1600
1601 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1602
1603 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1604                                                struct attribute *,
1605                                                struct dwarf2_cu **);
1606
1607 static struct die_info *follow_die_ref (struct die_info *,
1608                                         struct attribute *,
1609                                         struct dwarf2_cu **);
1610
1611 static struct die_info *follow_die_sig (struct die_info *,
1612                                         struct attribute *,
1613                                         struct dwarf2_cu **);
1614
1615 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1616                                          struct dwarf2_cu *);
1617
1618 static struct type *get_DW_AT_signature_type (struct die_info *,
1619                                               struct attribute *,
1620                                               struct dwarf2_cu *);
1621
1622 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1623
1624 static void read_signatured_type (struct signatured_type *);
1625
1626 static struct type_unit_group *get_type_unit_group
1627     (struct dwarf2_cu *, struct attribute *);
1628
1629 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1630
1631 /* memory allocation interface */
1632
1633 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1634
1635 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1636
1637 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1638                                  const char *, int);
1639
1640 static int attr_form_is_block (struct attribute *);
1641
1642 static int attr_form_is_section_offset (struct attribute *);
1643
1644 static int attr_form_is_constant (struct attribute *);
1645
1646 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1647                                    struct dwarf2_loclist_baton *baton,
1648                                    struct attribute *attr);
1649
1650 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1651                                          struct symbol *sym,
1652                                          struct dwarf2_cu *cu,
1653                                          int is_block);
1654
1655 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1656                                      const gdb_byte *info_ptr,
1657                                      struct abbrev_info *abbrev);
1658
1659 static void free_stack_comp_unit (void *);
1660
1661 static hashval_t partial_die_hash (const void *item);
1662
1663 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1664
1665 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1666   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1667
1668 static void init_one_comp_unit (struct dwarf2_cu *cu,
1669                                 struct dwarf2_per_cu_data *per_cu);
1670
1671 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1672                                    struct die_info *comp_unit_die,
1673                                    enum language pretend_language);
1674
1675 static void free_heap_comp_unit (void *);
1676
1677 static void free_cached_comp_units (void *);
1678
1679 static void age_cached_comp_units (void);
1680
1681 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1682
1683 static struct type *set_die_type (struct die_info *, struct type *,
1684                                   struct dwarf2_cu *);
1685
1686 static void create_all_comp_units (struct objfile *);
1687
1688 static int create_all_type_units (struct objfile *);
1689
1690 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1691                                  enum language);
1692
1693 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1694                                     enum language);
1695
1696 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1697                                     enum language);
1698
1699 static void dwarf2_add_dependence (struct dwarf2_cu *,
1700                                    struct dwarf2_per_cu_data *);
1701
1702 static void dwarf2_mark (struct dwarf2_cu *);
1703
1704 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1705
1706 static struct type *get_die_type_at_offset (sect_offset,
1707                                             struct dwarf2_per_cu_data *);
1708
1709 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1710
1711 static void dwarf2_release_queue (void *dummy);
1712
1713 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1714                              enum language pretend_language);
1715
1716 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1717                                   struct dwarf2_per_cu_data *per_cu,
1718                                   enum language pretend_language);
1719
1720 static void process_queue (void);
1721
1722 static void find_file_and_directory (struct die_info *die,
1723                                      struct dwarf2_cu *cu,
1724                                      const char **name, const char **comp_dir);
1725
1726 static char *file_full_name (int file, struct line_header *lh,
1727                              const char *comp_dir);
1728
1729 static const gdb_byte *read_and_check_comp_unit_head
1730   (struct comp_unit_head *header,
1731    struct dwarf2_section_info *section,
1732    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1733    int is_debug_types_section);
1734
1735 static void init_cutu_and_read_dies
1736   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1737    int use_existing_cu, int keep,
1738    die_reader_func_ftype *die_reader_func, void *data);
1739
1740 static void init_cutu_and_read_dies_simple
1741   (struct dwarf2_per_cu_data *this_cu,
1742    die_reader_func_ftype *die_reader_func, void *data);
1743
1744 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1745
1746 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1747
1748 static struct dwo_unit *lookup_dwo_comp_unit
1749   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1750
1751 static struct dwo_unit *lookup_dwo_type_unit
1752   (struct signatured_type *, const char *, const char *);
1753
1754 static void free_dwo_file_cleanup (void *);
1755
1756 static void process_cu_includes (void);
1757
1758 static void check_producer (struct dwarf2_cu *cu);
1759
1760 #if WORDS_BIGENDIAN
1761
1762 /* Convert VALUE between big- and little-endian.  */
1763 static offset_type
1764 byte_swap (offset_type value)
1765 {
1766   offset_type result;
1767
1768   result = (value & 0xff) << 24;
1769   result |= (value & 0xff00) << 8;
1770   result |= (value & 0xff0000) >> 8;
1771   result |= (value & 0xff000000) >> 24;
1772   return result;
1773 }
1774
1775 #define MAYBE_SWAP(V)  byte_swap (V)
1776
1777 #else
1778 #define MAYBE_SWAP(V) (V)
1779 #endif /* WORDS_BIGENDIAN */
1780
1781 /* The suffix for an index file.  */
1782 #define INDEX_SUFFIX ".gdb-index"
1783
1784 /* Try to locate the sections we need for DWARF 2 debugging
1785    information and return true if we have enough to do something.
1786    NAMES points to the dwarf2 section names, or is NULL if the standard
1787    ELF names are used.  */
1788
1789 int
1790 dwarf2_has_info (struct objfile *objfile,
1791                  const struct dwarf2_debug_sections *names)
1792 {
1793   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1794   if (!dwarf2_per_objfile)
1795     {
1796       /* Initialize per-objfile state.  */
1797       struct dwarf2_per_objfile *data
1798         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1799
1800       memset (data, 0, sizeof (*data));
1801       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1802       dwarf2_per_objfile = data;
1803
1804       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1805                              (void *) names);
1806       dwarf2_per_objfile->objfile = objfile;
1807     }
1808   return (dwarf2_per_objfile->info.asection != NULL
1809           && dwarf2_per_objfile->abbrev.asection != NULL);
1810 }
1811
1812 /* When loading sections, we look either for uncompressed section or for
1813    compressed section names.  */
1814
1815 static int
1816 section_is_p (const char *section_name,
1817               const struct dwarf2_section_names *names)
1818 {
1819   if (names->normal != NULL
1820       && strcmp (section_name, names->normal) == 0)
1821     return 1;
1822   if (names->compressed != NULL
1823       && strcmp (section_name, names->compressed) == 0)
1824     return 1;
1825   return 0;
1826 }
1827
1828 /* This function is mapped across the sections and remembers the
1829    offset and size of each of the debugging sections we are interested
1830    in.  */
1831
1832 static void
1833 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1834 {
1835   const struct dwarf2_debug_sections *names;
1836   flagword aflag = bfd_get_section_flags (abfd, sectp);
1837
1838   if (vnames == NULL)
1839     names = &dwarf2_elf_names;
1840   else
1841     names = (const struct dwarf2_debug_sections *) vnames;
1842
1843   if ((aflag & SEC_HAS_CONTENTS) == 0)
1844     {
1845     }
1846   else if (section_is_p (sectp->name, &names->info))
1847     {
1848       dwarf2_per_objfile->info.asection = sectp;
1849       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1850     }
1851   else if (section_is_p (sectp->name, &names->abbrev))
1852     {
1853       dwarf2_per_objfile->abbrev.asection = sectp;
1854       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1855     }
1856   else if (section_is_p (sectp->name, &names->line))
1857     {
1858       dwarf2_per_objfile->line.asection = sectp;
1859       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1860     }
1861   else if (section_is_p (sectp->name, &names->loc))
1862     {
1863       dwarf2_per_objfile->loc.asection = sectp;
1864       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1865     }
1866   else if (section_is_p (sectp->name, &names->macinfo))
1867     {
1868       dwarf2_per_objfile->macinfo.asection = sectp;
1869       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1870     }
1871   else if (section_is_p (sectp->name, &names->macro))
1872     {
1873       dwarf2_per_objfile->macro.asection = sectp;
1874       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1875     }
1876   else if (section_is_p (sectp->name, &names->str))
1877     {
1878       dwarf2_per_objfile->str.asection = sectp;
1879       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1880     }
1881   else if (section_is_p (sectp->name, &names->addr))
1882     {
1883       dwarf2_per_objfile->addr.asection = sectp;
1884       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1885     }
1886   else if (section_is_p (sectp->name, &names->frame))
1887     {
1888       dwarf2_per_objfile->frame.asection = sectp;
1889       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1890     }
1891   else if (section_is_p (sectp->name, &names->eh_frame))
1892     {
1893       dwarf2_per_objfile->eh_frame.asection = sectp;
1894       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1895     }
1896   else if (section_is_p (sectp->name, &names->ranges))
1897     {
1898       dwarf2_per_objfile->ranges.asection = sectp;
1899       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1900     }
1901   else if (section_is_p (sectp->name, &names->types))
1902     {
1903       struct dwarf2_section_info type_section;
1904
1905       memset (&type_section, 0, sizeof (type_section));
1906       type_section.asection = sectp;
1907       type_section.size = bfd_get_section_size (sectp);
1908
1909       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1910                      &type_section);
1911     }
1912   else if (section_is_p (sectp->name, &names->gdb_index))
1913     {
1914       dwarf2_per_objfile->gdb_index.asection = sectp;
1915       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1916     }
1917
1918   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1919       && bfd_section_vma (abfd, sectp) == 0)
1920     dwarf2_per_objfile->has_section_at_zero = 1;
1921 }
1922
1923 /* A helper function that decides whether a section is empty,
1924    or not present.  */
1925
1926 static int
1927 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1928 {
1929   return info->asection == NULL || info->size == 0;
1930 }
1931
1932 /* Read the contents of the section INFO.
1933    OBJFILE is the main object file, but not necessarily the file where
1934    the section comes from.  E.g., for DWO files INFO->asection->owner
1935    is the bfd of the DWO file.
1936    If the section is compressed, uncompress it before returning.  */
1937
1938 static void
1939 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1940 {
1941   asection *sectp = info->asection;
1942   bfd *abfd;
1943   gdb_byte *buf, *retbuf;
1944   unsigned char header[4];
1945
1946   if (info->readin)
1947     return;
1948   info->buffer = NULL;
1949   info->readin = 1;
1950
1951   if (dwarf2_section_empty_p (info))
1952     return;
1953
1954   abfd = sectp->owner;
1955
1956   /* If the section has relocations, we must read it ourselves.
1957      Otherwise we attach it to the BFD.  */
1958   if ((sectp->flags & SEC_RELOC) == 0)
1959     {
1960       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1961       return;
1962     }
1963
1964   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1965   info->buffer = buf;
1966
1967   /* When debugging .o files, we may need to apply relocations; see
1968      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1969      We never compress sections in .o files, so we only need to
1970      try this when the section is not compressed.  */
1971   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1972   if (retbuf != NULL)
1973     {
1974       info->buffer = retbuf;
1975       return;
1976     }
1977
1978   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1979       || bfd_bread (buf, info->size, abfd) != info->size)
1980     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1981            bfd_get_filename (abfd));
1982 }
1983
1984 /* A helper function that returns the size of a section in a safe way.
1985    If you are positive that the section has been read before using the
1986    size, then it is safe to refer to the dwarf2_section_info object's
1987    "size" field directly.  In other cases, you must call this
1988    function, because for compressed sections the size field is not set
1989    correctly until the section has been read.  */
1990
1991 static bfd_size_type
1992 dwarf2_section_size (struct objfile *objfile,
1993                      struct dwarf2_section_info *info)
1994 {
1995   if (!info->readin)
1996     dwarf2_read_section (objfile, info);
1997   return info->size;
1998 }
1999
2000 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2001    SECTION_NAME.  */
2002
2003 void
2004 dwarf2_get_section_info (struct objfile *objfile,
2005                          enum dwarf2_section_enum sect,
2006                          asection **sectp, const gdb_byte **bufp,
2007                          bfd_size_type *sizep)
2008 {
2009   struct dwarf2_per_objfile *data
2010     = objfile_data (objfile, dwarf2_objfile_data_key);
2011   struct dwarf2_section_info *info;
2012
2013   /* We may see an objfile without any DWARF, in which case we just
2014      return nothing.  */
2015   if (data == NULL)
2016     {
2017       *sectp = NULL;
2018       *bufp = NULL;
2019       *sizep = 0;
2020       return;
2021     }
2022   switch (sect)
2023     {
2024     case DWARF2_DEBUG_FRAME:
2025       info = &data->frame;
2026       break;
2027     case DWARF2_EH_FRAME:
2028       info = &data->eh_frame;
2029       break;
2030     default:
2031       gdb_assert_not_reached ("unexpected section");
2032     }
2033
2034   dwarf2_read_section (objfile, info);
2035
2036   *sectp = info->asection;
2037   *bufp = info->buffer;
2038   *sizep = info->size;
2039 }
2040
2041 /* A helper function to find the sections for a .dwz file.  */
2042
2043 static void
2044 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2045 {
2046   struct dwz_file *dwz_file = arg;
2047
2048   /* Note that we only support the standard ELF names, because .dwz
2049      is ELF-only (at the time of writing).  */
2050   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2051     {
2052       dwz_file->abbrev.asection = sectp;
2053       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2054     }
2055   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2056     {
2057       dwz_file->info.asection = sectp;
2058       dwz_file->info.size = bfd_get_section_size (sectp);
2059     }
2060   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2061     {
2062       dwz_file->str.asection = sectp;
2063       dwz_file->str.size = bfd_get_section_size (sectp);
2064     }
2065   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2066     {
2067       dwz_file->line.asection = sectp;
2068       dwz_file->line.size = bfd_get_section_size (sectp);
2069     }
2070   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2071     {
2072       dwz_file->macro.asection = sectp;
2073       dwz_file->macro.size = bfd_get_section_size (sectp);
2074     }
2075   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2076     {
2077       dwz_file->gdb_index.asection = sectp;
2078       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2079     }
2080 }
2081
2082 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2083    cannot be found.  */
2084
2085 static struct dwz_file *
2086 dwarf2_get_dwz_file (void)
2087 {
2088   bfd *abfd, *dwz_bfd;
2089   asection *section;
2090   gdb_byte *data;
2091   struct cleanup *cleanup;
2092   const char *filename;
2093   struct dwz_file *result;
2094
2095   if (dwarf2_per_objfile->dwz_file != NULL)
2096     return dwarf2_per_objfile->dwz_file;
2097
2098   abfd = dwarf2_per_objfile->objfile->obfd;
2099   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2100   if (section == NULL)
2101     error (_("could not find '.gnu_debugaltlink' section"));
2102   if (!bfd_malloc_and_get_section (abfd, section, &data))
2103     error (_("could not read '.gnu_debugaltlink' section: %s"),
2104            bfd_errmsg (bfd_get_error ()));
2105   cleanup = make_cleanup (xfree, data);
2106
2107   filename = (const char *) data;
2108   if (!IS_ABSOLUTE_PATH (filename))
2109     {
2110       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2111       char *rel;
2112
2113       make_cleanup (xfree, abs);
2114       abs = ldirname (abs);
2115       make_cleanup (xfree, abs);
2116
2117       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2118       make_cleanup (xfree, rel);
2119       filename = rel;
2120     }
2121
2122   /* The format is just a NUL-terminated file name, followed by the
2123      build-id.  For now, though, we ignore the build-id.  */
2124   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2125   if (dwz_bfd == NULL)
2126     error (_("could not read '%s': %s"), filename,
2127            bfd_errmsg (bfd_get_error ()));
2128
2129   if (!bfd_check_format (dwz_bfd, bfd_object))
2130     {
2131       gdb_bfd_unref (dwz_bfd);
2132       error (_("file '%s' was not usable: %s"), filename,
2133              bfd_errmsg (bfd_get_error ()));
2134     }
2135
2136   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2137                            struct dwz_file);
2138   result->dwz_bfd = dwz_bfd;
2139
2140   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2141
2142   do_cleanups (cleanup);
2143
2144   dwarf2_per_objfile->dwz_file = result;
2145   return result;
2146 }
2147 \f
2148 /* DWARF quick_symbols_functions support.  */
2149
2150 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2151    unique line tables, so we maintain a separate table of all .debug_line
2152    derived entries to support the sharing.
2153    All the quick functions need is the list of file names.  We discard the
2154    line_header when we're done and don't need to record it here.  */
2155 struct quick_file_names
2156 {
2157   /* The data used to construct the hash key.  */
2158   struct stmt_list_hash hash;
2159
2160   /* The number of entries in file_names, real_names.  */
2161   unsigned int num_file_names;
2162
2163   /* The file names from the line table, after being run through
2164      file_full_name.  */
2165   const char **file_names;
2166
2167   /* The file names from the line table after being run through
2168      gdb_realpath.  These are computed lazily.  */
2169   const char **real_names;
2170 };
2171
2172 /* When using the index (and thus not using psymtabs), each CU has an
2173    object of this type.  This is used to hold information needed by
2174    the various "quick" methods.  */
2175 struct dwarf2_per_cu_quick_data
2176 {
2177   /* The file table.  This can be NULL if there was no file table
2178      or it's currently not read in.
2179      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2180   struct quick_file_names *file_names;
2181
2182   /* The corresponding symbol table.  This is NULL if symbols for this
2183      CU have not yet been read.  */
2184   struct symtab *symtab;
2185
2186   /* A temporary mark bit used when iterating over all CUs in
2187      expand_symtabs_matching.  */
2188   unsigned int mark : 1;
2189
2190   /* True if we've tried to read the file table and found there isn't one.
2191      There will be no point in trying to read it again next time.  */
2192   unsigned int no_file_data : 1;
2193 };
2194
2195 /* Utility hash function for a stmt_list_hash.  */
2196
2197 static hashval_t
2198 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2199 {
2200   hashval_t v = 0;
2201
2202   if (stmt_list_hash->dwo_unit != NULL)
2203     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2204   v += stmt_list_hash->line_offset.sect_off;
2205   return v;
2206 }
2207
2208 /* Utility equality function for a stmt_list_hash.  */
2209
2210 static int
2211 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2212                     const struct stmt_list_hash *rhs)
2213 {
2214   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2215     return 0;
2216   if (lhs->dwo_unit != NULL
2217       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2218     return 0;
2219
2220   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2221 }
2222
2223 /* Hash function for a quick_file_names.  */
2224
2225 static hashval_t
2226 hash_file_name_entry (const void *e)
2227 {
2228   const struct quick_file_names *file_data = e;
2229
2230   return hash_stmt_list_entry (&file_data->hash);
2231 }
2232
2233 /* Equality function for a quick_file_names.  */
2234
2235 static int
2236 eq_file_name_entry (const void *a, const void *b)
2237 {
2238   const struct quick_file_names *ea = a;
2239   const struct quick_file_names *eb = b;
2240
2241   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2242 }
2243
2244 /* Delete function for a quick_file_names.  */
2245
2246 static void
2247 delete_file_name_entry (void *e)
2248 {
2249   struct quick_file_names *file_data = e;
2250   int i;
2251
2252   for (i = 0; i < file_data->num_file_names; ++i)
2253     {
2254       xfree ((void*) file_data->file_names[i]);
2255       if (file_data->real_names)
2256         xfree ((void*) file_data->real_names[i]);
2257     }
2258
2259   /* The space for the struct itself lives on objfile_obstack,
2260      so we don't free it here.  */
2261 }
2262
2263 /* Create a quick_file_names hash table.  */
2264
2265 static htab_t
2266 create_quick_file_names_table (unsigned int nr_initial_entries)
2267 {
2268   return htab_create_alloc (nr_initial_entries,
2269                             hash_file_name_entry, eq_file_name_entry,
2270                             delete_file_name_entry, xcalloc, xfree);
2271 }
2272
2273 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2274    have to be created afterwards.  You should call age_cached_comp_units after
2275    processing PER_CU->CU.  dw2_setup must have been already called.  */
2276
2277 static void
2278 load_cu (struct dwarf2_per_cu_data *per_cu)
2279 {
2280   if (per_cu->is_debug_types)
2281     load_full_type_unit (per_cu);
2282   else
2283     load_full_comp_unit (per_cu, language_minimal);
2284
2285   gdb_assert (per_cu->cu != NULL);
2286
2287   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2288 }
2289
2290 /* Read in the symbols for PER_CU.  */
2291
2292 static void
2293 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2294 {
2295   struct cleanup *back_to;
2296
2297   /* Skip type_unit_groups, reading the type units they contain
2298      is handled elsewhere.  */
2299   if (IS_TYPE_UNIT_GROUP (per_cu))
2300     return;
2301
2302   back_to = make_cleanup (dwarf2_release_queue, NULL);
2303
2304   if (dwarf2_per_objfile->using_index
2305       ? per_cu->v.quick->symtab == NULL
2306       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2307     {
2308       queue_comp_unit (per_cu, language_minimal);
2309       load_cu (per_cu);
2310     }
2311
2312   process_queue ();
2313
2314   /* Age the cache, releasing compilation units that have not
2315      been used recently.  */
2316   age_cached_comp_units ();
2317
2318   do_cleanups (back_to);
2319 }
2320
2321 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2322    the objfile from which this CU came.  Returns the resulting symbol
2323    table.  */
2324
2325 static struct symtab *
2326 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2327 {
2328   gdb_assert (dwarf2_per_objfile->using_index);
2329   if (!per_cu->v.quick->symtab)
2330     {
2331       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2332       increment_reading_symtab ();
2333       dw2_do_instantiate_symtab (per_cu);
2334       process_cu_includes ();
2335       do_cleanups (back_to);
2336     }
2337   return per_cu->v.quick->symtab;
2338 }
2339
2340 /* Return the CU given its index.
2341
2342    This is intended for loops like:
2343
2344    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2345                     + dwarf2_per_objfile->n_type_units); ++i)
2346      {
2347        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2348
2349        ...;
2350      }
2351 */
2352
2353 static struct dwarf2_per_cu_data *
2354 dw2_get_cu (int index)
2355 {
2356   if (index >= dwarf2_per_objfile->n_comp_units)
2357     {
2358       index -= dwarf2_per_objfile->n_comp_units;
2359       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2360       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2361     }
2362
2363   return dwarf2_per_objfile->all_comp_units[index];
2364 }
2365
2366 /* Return the primary CU given its index.
2367    The difference between this function and dw2_get_cu is in the handling
2368    of type units (TUs).  Here we return the type_unit_group object.
2369
2370    This is intended for loops like:
2371
2372    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2373                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2374      {
2375        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2376
2377        ...;
2378      }
2379 */
2380
2381 static struct dwarf2_per_cu_data *
2382 dw2_get_primary_cu (int index)
2383 {
2384   if (index >= dwarf2_per_objfile->n_comp_units)
2385     {
2386       index -= dwarf2_per_objfile->n_comp_units;
2387       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2388       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2389     }
2390
2391   return dwarf2_per_objfile->all_comp_units[index];
2392 }
2393
2394 /* A helper for create_cus_from_index that handles a given list of
2395    CUs.  */
2396
2397 static void
2398 create_cus_from_index_list (struct objfile *objfile,
2399                             const gdb_byte *cu_list, offset_type n_elements,
2400                             struct dwarf2_section_info *section,
2401                             int is_dwz,
2402                             int base_offset)
2403 {
2404   offset_type i;
2405
2406   for (i = 0; i < n_elements; i += 2)
2407     {
2408       struct dwarf2_per_cu_data *the_cu;
2409       ULONGEST offset, length;
2410
2411       gdb_static_assert (sizeof (ULONGEST) >= 8);
2412       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2413       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2414       cu_list += 2 * 8;
2415
2416       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2417                                struct dwarf2_per_cu_data);
2418       the_cu->offset.sect_off = offset;
2419       the_cu->length = length;
2420       the_cu->objfile = objfile;
2421       the_cu->section = section;
2422       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2423                                         struct dwarf2_per_cu_quick_data);
2424       the_cu->is_dwz = is_dwz;
2425       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2426     }
2427 }
2428
2429 /* Read the CU list from the mapped index, and use it to create all
2430    the CU objects for this objfile.  */
2431
2432 static void
2433 create_cus_from_index (struct objfile *objfile,
2434                        const gdb_byte *cu_list, offset_type cu_list_elements,
2435                        const gdb_byte *dwz_list, offset_type dwz_elements)
2436 {
2437   struct dwz_file *dwz;
2438
2439   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2440   dwarf2_per_objfile->all_comp_units
2441     = obstack_alloc (&objfile->objfile_obstack,
2442                      dwarf2_per_objfile->n_comp_units
2443                      * sizeof (struct dwarf2_per_cu_data *));
2444
2445   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2446                               &dwarf2_per_objfile->info, 0, 0);
2447
2448   if (dwz_elements == 0)
2449     return;
2450
2451   dwz = dwarf2_get_dwz_file ();
2452   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2453                               cu_list_elements / 2);
2454 }
2455
2456 /* Create the signatured type hash table from the index.  */
2457
2458 static void
2459 create_signatured_type_table_from_index (struct objfile *objfile,
2460                                          struct dwarf2_section_info *section,
2461                                          const gdb_byte *bytes,
2462                                          offset_type elements)
2463 {
2464   offset_type i;
2465   htab_t sig_types_hash;
2466
2467   dwarf2_per_objfile->n_type_units = elements / 3;
2468   dwarf2_per_objfile->all_type_units
2469     = obstack_alloc (&objfile->objfile_obstack,
2470                      dwarf2_per_objfile->n_type_units
2471                      * sizeof (struct signatured_type *));
2472
2473   sig_types_hash = allocate_signatured_type_table (objfile);
2474
2475   for (i = 0; i < elements; i += 3)
2476     {
2477       struct signatured_type *sig_type;
2478       ULONGEST offset, type_offset_in_tu, signature;
2479       void **slot;
2480
2481       gdb_static_assert (sizeof (ULONGEST) >= 8);
2482       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2483       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2484                                                     BFD_ENDIAN_LITTLE);
2485       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2486       bytes += 3 * 8;
2487
2488       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2489                                  struct signatured_type);
2490       sig_type->signature = signature;
2491       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2492       sig_type->per_cu.is_debug_types = 1;
2493       sig_type->per_cu.section = section;
2494       sig_type->per_cu.offset.sect_off = offset;
2495       sig_type->per_cu.objfile = objfile;
2496       sig_type->per_cu.v.quick
2497         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2498                           struct dwarf2_per_cu_quick_data);
2499
2500       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2501       *slot = sig_type;
2502
2503       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2504     }
2505
2506   dwarf2_per_objfile->signatured_types = sig_types_hash;
2507 }
2508
2509 /* Read the address map data from the mapped index, and use it to
2510    populate the objfile's psymtabs_addrmap.  */
2511
2512 static void
2513 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2514 {
2515   const gdb_byte *iter, *end;
2516   struct obstack temp_obstack;
2517   struct addrmap *mutable_map;
2518   struct cleanup *cleanup;
2519   CORE_ADDR baseaddr;
2520
2521   obstack_init (&temp_obstack);
2522   cleanup = make_cleanup_obstack_free (&temp_obstack);
2523   mutable_map = addrmap_create_mutable (&temp_obstack);
2524
2525   iter = index->address_table;
2526   end = iter + index->address_table_size;
2527
2528   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2529
2530   while (iter < end)
2531     {
2532       ULONGEST hi, lo, cu_index;
2533       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2534       iter += 8;
2535       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2536       iter += 8;
2537       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2538       iter += 4;
2539
2540       if (cu_index < dwarf2_per_objfile->n_comp_units)
2541         {
2542           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2543                              dw2_get_cu (cu_index));
2544         }
2545       else
2546         {
2547           complaint (&symfile_complaints,
2548                      _(".gdb_index address table has invalid CU number %u"),
2549                      (unsigned) cu_index);
2550         }
2551     }
2552
2553   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2554                                                     &objfile->objfile_obstack);
2555   do_cleanups (cleanup);
2556 }
2557
2558 /* The hash function for strings in the mapped index.  This is the same as
2559    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2560    implementation.  This is necessary because the hash function is tied to the
2561    format of the mapped index file.  The hash values do not have to match with
2562    SYMBOL_HASH_NEXT.
2563    
2564    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2565
2566 static hashval_t
2567 mapped_index_string_hash (int index_version, const void *p)
2568 {
2569   const unsigned char *str = (const unsigned char *) p;
2570   hashval_t r = 0;
2571   unsigned char c;
2572
2573   while ((c = *str++) != 0)
2574     {
2575       if (index_version >= 5)
2576         c = tolower (c);
2577       r = r * 67 + c - 113;
2578     }
2579
2580   return r;
2581 }
2582
2583 /* Find a slot in the mapped index INDEX for the object named NAME.
2584    If NAME is found, set *VEC_OUT to point to the CU vector in the
2585    constant pool and return 1.  If NAME cannot be found, return 0.  */
2586
2587 static int
2588 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2589                           offset_type **vec_out)
2590 {
2591   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2592   offset_type hash;
2593   offset_type slot, step;
2594   int (*cmp) (const char *, const char *);
2595
2596   if (current_language->la_language == language_cplus
2597       || current_language->la_language == language_java
2598       || current_language->la_language == language_fortran)
2599     {
2600       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2601          not contain any.  */
2602       const char *paren = strchr (name, '(');
2603
2604       if (paren)
2605         {
2606           char *dup;
2607
2608           dup = xmalloc (paren - name + 1);
2609           memcpy (dup, name, paren - name);
2610           dup[paren - name] = 0;
2611
2612           make_cleanup (xfree, dup);
2613           name = dup;
2614         }
2615     }
2616
2617   /* Index version 4 did not support case insensitive searches.  But the
2618      indices for case insensitive languages are built in lowercase, therefore
2619      simulate our NAME being searched is also lowercased.  */
2620   hash = mapped_index_string_hash ((index->version == 4
2621                                     && case_sensitivity == case_sensitive_off
2622                                     ? 5 : index->version),
2623                                    name);
2624
2625   slot = hash & (index->symbol_table_slots - 1);
2626   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2627   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2628
2629   for (;;)
2630     {
2631       /* Convert a slot number to an offset into the table.  */
2632       offset_type i = 2 * slot;
2633       const char *str;
2634       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2635         {
2636           do_cleanups (back_to);
2637           return 0;
2638         }
2639
2640       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2641       if (!cmp (name, str))
2642         {
2643           *vec_out = (offset_type *) (index->constant_pool
2644                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2645           do_cleanups (back_to);
2646           return 1;
2647         }
2648
2649       slot = (slot + step) & (index->symbol_table_slots - 1);
2650     }
2651 }
2652
2653 /* A helper function that reads the .gdb_index from SECTION and fills
2654    in MAP.  FILENAME is the name of the file containing the section;
2655    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2656    ok to use deprecated sections.
2657
2658    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2659    out parameters that are filled in with information about the CU and
2660    TU lists in the section.
2661
2662    Returns 1 if all went well, 0 otherwise.  */
2663
2664 static int
2665 read_index_from_section (struct objfile *objfile,
2666                          const char *filename,
2667                          int deprecated_ok,
2668                          struct dwarf2_section_info *section,
2669                          struct mapped_index *map,
2670                          const gdb_byte **cu_list,
2671                          offset_type *cu_list_elements,
2672                          const gdb_byte **types_list,
2673                          offset_type *types_list_elements)
2674 {
2675   const gdb_byte *addr;
2676   offset_type version;
2677   offset_type *metadata;
2678   int i;
2679
2680   if (dwarf2_section_empty_p (section))
2681     return 0;
2682
2683   /* Older elfutils strip versions could keep the section in the main
2684      executable while splitting it for the separate debug info file.  */
2685   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2686     return 0;
2687
2688   dwarf2_read_section (objfile, section);
2689
2690   addr = section->buffer;
2691   /* Version check.  */
2692   version = MAYBE_SWAP (*(offset_type *) addr);
2693   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2694      causes the index to behave very poorly for certain requests.  Version 3
2695      contained incomplete addrmap.  So, it seems better to just ignore such
2696      indices.  */
2697   if (version < 4)
2698     {
2699       static int warning_printed = 0;
2700       if (!warning_printed)
2701         {
2702           warning (_("Skipping obsolete .gdb_index section in %s."),
2703                    filename);
2704           warning_printed = 1;
2705         }
2706       return 0;
2707     }
2708   /* Index version 4 uses a different hash function than index version
2709      5 and later.
2710
2711      Versions earlier than 6 did not emit psymbols for inlined
2712      functions.  Using these files will cause GDB not to be able to
2713      set breakpoints on inlined functions by name, so we ignore these
2714      indices unless the user has done
2715      "set use-deprecated-index-sections on".  */
2716   if (version < 6 && !deprecated_ok)
2717     {
2718       static int warning_printed = 0;
2719       if (!warning_printed)
2720         {
2721           warning (_("\
2722 Skipping deprecated .gdb_index section in %s.\n\
2723 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2724 to use the section anyway."),
2725                    filename);
2726           warning_printed = 1;
2727         }
2728       return 0;
2729     }
2730   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2731      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2732      we can't distinguish gdb-generated indices from gold-generated ones, so
2733      nothing to do here.  */
2734
2735   /* Indexes with higher version than the one supported by GDB may be no
2736      longer backward compatible.  */
2737   if (version > 8)
2738     return 0;
2739
2740   map->version = version;
2741   map->total_size = section->size;
2742
2743   metadata = (offset_type *) (addr + sizeof (offset_type));
2744
2745   i = 0;
2746   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2747   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2748                        / 8);
2749   ++i;
2750
2751   *types_list = addr + MAYBE_SWAP (metadata[i]);
2752   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2753                            - MAYBE_SWAP (metadata[i]))
2754                           / 8);
2755   ++i;
2756
2757   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2758   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2759                              - MAYBE_SWAP (metadata[i]));
2760   ++i;
2761
2762   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2763   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2764                               - MAYBE_SWAP (metadata[i]))
2765                              / (2 * sizeof (offset_type)));
2766   ++i;
2767
2768   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2769
2770   return 1;
2771 }
2772
2773
2774 /* Read the index file.  If everything went ok, initialize the "quick"
2775    elements of all the CUs and return 1.  Otherwise, return 0.  */
2776
2777 static int
2778 dwarf2_read_index (struct objfile *objfile)
2779 {
2780   struct mapped_index local_map, *map;
2781   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2782   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2783
2784   if (!read_index_from_section (objfile, objfile->name,
2785                                 use_deprecated_index_sections,
2786                                 &dwarf2_per_objfile->gdb_index, &local_map,
2787                                 &cu_list, &cu_list_elements,
2788                                 &types_list, &types_list_elements))
2789     return 0;
2790
2791   /* Don't use the index if it's empty.  */
2792   if (local_map.symbol_table_slots == 0)
2793     return 0;
2794
2795   /* If there is a .dwz file, read it so we can get its CU list as
2796      well.  */
2797   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2798     {
2799       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2800       struct mapped_index dwz_map;
2801       const gdb_byte *dwz_types_ignore;
2802       offset_type dwz_types_elements_ignore;
2803
2804       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2805                                     1,
2806                                     &dwz->gdb_index, &dwz_map,
2807                                     &dwz_list, &dwz_list_elements,
2808                                     &dwz_types_ignore,
2809                                     &dwz_types_elements_ignore))
2810         {
2811           warning (_("could not read '.gdb_index' section from %s; skipping"),
2812                    bfd_get_filename (dwz->dwz_bfd));
2813           return 0;
2814         }
2815     }
2816
2817   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2818                          dwz_list_elements);
2819
2820   if (types_list_elements)
2821     {
2822       struct dwarf2_section_info *section;
2823
2824       /* We can only handle a single .debug_types when we have an
2825          index.  */
2826       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2827         return 0;
2828
2829       section = VEC_index (dwarf2_section_info_def,
2830                            dwarf2_per_objfile->types, 0);
2831
2832       create_signatured_type_table_from_index (objfile, section, types_list,
2833                                                types_list_elements);
2834     }
2835
2836   create_addrmap_from_index (objfile, &local_map);
2837
2838   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2839   *map = local_map;
2840
2841   dwarf2_per_objfile->index_table = map;
2842   dwarf2_per_objfile->using_index = 1;
2843   dwarf2_per_objfile->quick_file_names_table =
2844     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2845
2846   return 1;
2847 }
2848
2849 /* A helper for the "quick" functions which sets the global
2850    dwarf2_per_objfile according to OBJFILE.  */
2851
2852 static void
2853 dw2_setup (struct objfile *objfile)
2854 {
2855   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2856   gdb_assert (dwarf2_per_objfile);
2857 }
2858
2859 /* die_reader_func for dw2_get_file_names.  */
2860
2861 static void
2862 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2863                            const gdb_byte *info_ptr,
2864                            struct die_info *comp_unit_die,
2865                            int has_children,
2866                            void *data)
2867 {
2868   struct dwarf2_cu *cu = reader->cu;
2869   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2870   struct objfile *objfile = dwarf2_per_objfile->objfile;
2871   struct dwarf2_per_cu_data *lh_cu;
2872   struct line_header *lh;
2873   struct attribute *attr;
2874   int i;
2875   const char *name, *comp_dir;
2876   void **slot;
2877   struct quick_file_names *qfn;
2878   unsigned int line_offset;
2879
2880   gdb_assert (! this_cu->is_debug_types);
2881
2882   /* Our callers never want to match partial units -- instead they
2883      will match the enclosing full CU.  */
2884   if (comp_unit_die->tag == DW_TAG_partial_unit)
2885     {
2886       this_cu->v.quick->no_file_data = 1;
2887       return;
2888     }
2889
2890   lh_cu = this_cu;
2891   lh = NULL;
2892   slot = NULL;
2893   line_offset = 0;
2894
2895   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2896   if (attr)
2897     {
2898       struct quick_file_names find_entry;
2899
2900       line_offset = DW_UNSND (attr);
2901
2902       /* We may have already read in this line header (TU line header sharing).
2903          If we have we're done.  */
2904       find_entry.hash.dwo_unit = cu->dwo_unit;
2905       find_entry.hash.line_offset.sect_off = line_offset;
2906       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2907                              &find_entry, INSERT);
2908       if (*slot != NULL)
2909         {
2910           lh_cu->v.quick->file_names = *slot;
2911           return;
2912         }
2913
2914       lh = dwarf_decode_line_header (line_offset, cu);
2915     }
2916   if (lh == NULL)
2917     {
2918       lh_cu->v.quick->no_file_data = 1;
2919       return;
2920     }
2921
2922   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2923   qfn->hash.dwo_unit = cu->dwo_unit;
2924   qfn->hash.line_offset.sect_off = line_offset;
2925   gdb_assert (slot != NULL);
2926   *slot = qfn;
2927
2928   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2929
2930   qfn->num_file_names = lh->num_file_names;
2931   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2932                                    lh->num_file_names * sizeof (char *));
2933   for (i = 0; i < lh->num_file_names; ++i)
2934     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2935   qfn->real_names = NULL;
2936
2937   free_line_header (lh);
2938
2939   lh_cu->v.quick->file_names = qfn;
2940 }
2941
2942 /* A helper for the "quick" functions which attempts to read the line
2943    table for THIS_CU.  */
2944
2945 static struct quick_file_names *
2946 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2947 {
2948   /* This should never be called for TUs.  */
2949   gdb_assert (! this_cu->is_debug_types);
2950   /* Nor type unit groups.  */
2951   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
2952
2953   if (this_cu->v.quick->file_names != NULL)
2954     return this_cu->v.quick->file_names;
2955   /* If we know there is no line data, no point in looking again.  */
2956   if (this_cu->v.quick->no_file_data)
2957     return NULL;
2958
2959   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2960
2961   if (this_cu->v.quick->no_file_data)
2962     return NULL;
2963   return this_cu->v.quick->file_names;
2964 }
2965
2966 /* A helper for the "quick" functions which computes and caches the
2967    real path for a given file name from the line table.  */
2968
2969 static const char *
2970 dw2_get_real_path (struct objfile *objfile,
2971                    struct quick_file_names *qfn, int index)
2972 {
2973   if (qfn->real_names == NULL)
2974     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2975                                       qfn->num_file_names, sizeof (char *));
2976
2977   if (qfn->real_names[index] == NULL)
2978     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2979
2980   return qfn->real_names[index];
2981 }
2982
2983 static struct symtab *
2984 dw2_find_last_source_symtab (struct objfile *objfile)
2985 {
2986   int index;
2987
2988   dw2_setup (objfile);
2989   index = dwarf2_per_objfile->n_comp_units - 1;
2990   return dw2_instantiate_symtab (dw2_get_cu (index));
2991 }
2992
2993 /* Traversal function for dw2_forget_cached_source_info.  */
2994
2995 static int
2996 dw2_free_cached_file_names (void **slot, void *info)
2997 {
2998   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2999
3000   if (file_data->real_names)
3001     {
3002       int i;
3003
3004       for (i = 0; i < file_data->num_file_names; ++i)
3005         {
3006           xfree ((void*) file_data->real_names[i]);
3007           file_data->real_names[i] = NULL;
3008         }
3009     }
3010
3011   return 1;
3012 }
3013
3014 static void
3015 dw2_forget_cached_source_info (struct objfile *objfile)
3016 {
3017   dw2_setup (objfile);
3018
3019   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3020                           dw2_free_cached_file_names, NULL);
3021 }
3022
3023 /* Helper function for dw2_map_symtabs_matching_filename that expands
3024    the symtabs and calls the iterator.  */
3025
3026 static int
3027 dw2_map_expand_apply (struct objfile *objfile,
3028                       struct dwarf2_per_cu_data *per_cu,
3029                       const char *name, const char *real_path,
3030                       int (*callback) (struct symtab *, void *),
3031                       void *data)
3032 {
3033   struct symtab *last_made = objfile->symtabs;
3034
3035   /* Don't visit already-expanded CUs.  */
3036   if (per_cu->v.quick->symtab)
3037     return 0;
3038
3039   /* This may expand more than one symtab, and we want to iterate over
3040      all of them.  */
3041   dw2_instantiate_symtab (per_cu);
3042
3043   return iterate_over_some_symtabs (name, real_path, callback, data,
3044                                     objfile->symtabs, last_made);
3045 }
3046
3047 /* Implementation of the map_symtabs_matching_filename method.  */
3048
3049 static int
3050 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3051                                    const char *real_path,
3052                                    int (*callback) (struct symtab *, void *),
3053                                    void *data)
3054 {
3055   int i;
3056   const char *name_basename = lbasename (name);
3057
3058   dw2_setup (objfile);
3059
3060   /* The rule is CUs specify all the files, including those used by
3061      any TU, so there's no need to scan TUs here.  */
3062
3063   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3064     {
3065       int j;
3066       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3067       struct quick_file_names *file_data;
3068
3069       /* We only need to look at symtabs not already expanded.  */
3070       if (per_cu->v.quick->symtab)
3071         continue;
3072
3073       file_data = dw2_get_file_names (per_cu);
3074       if (file_data == NULL)
3075         continue;
3076
3077       for (j = 0; j < file_data->num_file_names; ++j)
3078         {
3079           const char *this_name = file_data->file_names[j];
3080           const char *this_real_name;
3081
3082           if (compare_filenames_for_search (this_name, name))
3083             {
3084               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3085                                         callback, data))
3086                 return 1;
3087               continue;
3088             }
3089
3090           /* Before we invoke realpath, which can get expensive when many
3091              files are involved, do a quick comparison of the basenames.  */
3092           if (! basenames_may_differ
3093               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3094             continue;
3095
3096           this_real_name = dw2_get_real_path (objfile, file_data, j);
3097           if (compare_filenames_for_search (this_real_name, name))
3098             {
3099               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3100                                         callback, data))
3101                 return 1;
3102               continue;
3103             }
3104
3105           if (real_path != NULL)
3106             {
3107               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3108               gdb_assert (IS_ABSOLUTE_PATH (name));
3109               if (this_real_name != NULL
3110                   && FILENAME_CMP (real_path, this_real_name) == 0)
3111                 {
3112                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3113                                             callback, data))
3114                     return 1;
3115                   continue;
3116                 }
3117             }
3118         }
3119     }
3120
3121   return 0;
3122 }
3123
3124 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3125
3126 struct dw2_symtab_iterator
3127 {
3128   /* The internalized form of .gdb_index.  */
3129   struct mapped_index *index;
3130   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3131   int want_specific_block;
3132   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3133      Unused if !WANT_SPECIFIC_BLOCK.  */
3134   int block_index;
3135   /* The kind of symbol we're looking for.  */
3136   domain_enum domain;
3137   /* The list of CUs from the index entry of the symbol,
3138      or NULL if not found.  */
3139   offset_type *vec;
3140   /* The next element in VEC to look at.  */
3141   int next;
3142   /* The number of elements in VEC, or zero if there is no match.  */
3143   int length;
3144 };
3145
3146 /* Initialize the index symtab iterator ITER.
3147    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3148    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3149
3150 static void
3151 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3152                       struct mapped_index *index,
3153                       int want_specific_block,
3154                       int block_index,
3155                       domain_enum domain,
3156                       const char *name)
3157 {
3158   iter->index = index;
3159   iter->want_specific_block = want_specific_block;
3160   iter->block_index = block_index;
3161   iter->domain = domain;
3162   iter->next = 0;
3163
3164   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3165     iter->length = MAYBE_SWAP (*iter->vec);
3166   else
3167     {
3168       iter->vec = NULL;
3169       iter->length = 0;
3170     }
3171 }
3172
3173 /* Return the next matching CU or NULL if there are no more.  */
3174
3175 static struct dwarf2_per_cu_data *
3176 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3177 {
3178   for ( ; iter->next < iter->length; ++iter->next)
3179     {
3180       offset_type cu_index_and_attrs =
3181         MAYBE_SWAP (iter->vec[iter->next + 1]);
3182       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3183       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3184       int want_static = iter->block_index != GLOBAL_BLOCK;
3185       /* This value is only valid for index versions >= 7.  */
3186       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3187       gdb_index_symbol_kind symbol_kind =
3188         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3189       /* Only check the symbol attributes if they're present.
3190          Indices prior to version 7 don't record them,
3191          and indices >= 7 may elide them for certain symbols
3192          (gold does this).  */
3193       int attrs_valid =
3194         (iter->index->version >= 7
3195          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3196
3197       /* Skip if already read in.  */
3198       if (per_cu->v.quick->symtab)
3199         continue;
3200
3201       if (attrs_valid
3202           && iter->want_specific_block
3203           && want_static != is_static)
3204         continue;
3205
3206       /* Only check the symbol's kind if it has one.  */
3207       if (attrs_valid)
3208         {
3209           switch (iter->domain)
3210             {
3211             case VAR_DOMAIN:
3212               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3213                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3214                   /* Some types are also in VAR_DOMAIN.  */
3215                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3216                 continue;
3217               break;
3218             case STRUCT_DOMAIN:
3219               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3220                 continue;
3221               break;
3222             case LABEL_DOMAIN:
3223               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3224                 continue;
3225               break;
3226             default:
3227               break;
3228             }
3229         }
3230
3231       ++iter->next;
3232       return per_cu;
3233     }
3234
3235   return NULL;
3236 }
3237
3238 static struct symtab *
3239 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3240                    const char *name, domain_enum domain)
3241 {
3242   struct symtab *stab_best = NULL;
3243   struct mapped_index *index;
3244
3245   dw2_setup (objfile);
3246
3247   index = dwarf2_per_objfile->index_table;
3248
3249   /* index is NULL if OBJF_READNOW.  */
3250   if (index)
3251     {
3252       struct dw2_symtab_iterator iter;
3253       struct dwarf2_per_cu_data *per_cu;
3254
3255       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3256
3257       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3258         {
3259           struct symbol *sym = NULL;
3260           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3261
3262           /* Some caution must be observed with overloaded functions
3263              and methods, since the index will not contain any overload
3264              information (but NAME might contain it).  */
3265           if (stab->primary)
3266             {
3267               struct blockvector *bv = BLOCKVECTOR (stab);
3268               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3269
3270               sym = lookup_block_symbol (block, name, domain);
3271             }
3272
3273           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3274             {
3275               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3276                 return stab;
3277
3278               stab_best = stab;
3279             }
3280
3281           /* Keep looking through other CUs.  */
3282         }
3283     }
3284
3285   return stab_best;
3286 }
3287
3288 static void
3289 dw2_print_stats (struct objfile *objfile)
3290 {
3291   int i, total, count;
3292
3293   dw2_setup (objfile);
3294   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3295   count = 0;
3296   for (i = 0; i < total; ++i)
3297     {
3298       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3299
3300       if (!per_cu->v.quick->symtab)
3301         ++count;
3302     }
3303   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3304   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3305 }
3306
3307 static void
3308 dw2_dump (struct objfile *objfile)
3309 {
3310   /* Nothing worth printing.  */
3311 }
3312
3313 static void
3314 dw2_relocate (struct objfile *objfile,
3315               const struct section_offsets *new_offsets,
3316               const struct section_offsets *delta)
3317 {
3318   /* There's nothing to relocate here.  */
3319 }
3320
3321 static void
3322 dw2_expand_symtabs_for_function (struct objfile *objfile,
3323                                  const char *func_name)
3324 {
3325   struct mapped_index *index;
3326
3327   dw2_setup (objfile);
3328
3329   index = dwarf2_per_objfile->index_table;
3330
3331   /* index is NULL if OBJF_READNOW.  */
3332   if (index)
3333     {
3334       struct dw2_symtab_iterator iter;
3335       struct dwarf2_per_cu_data *per_cu;
3336
3337       /* Note: It doesn't matter what we pass for block_index here.  */
3338       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3339                             func_name);
3340
3341       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3342         dw2_instantiate_symtab (per_cu);
3343     }
3344 }
3345
3346 static void
3347 dw2_expand_all_symtabs (struct objfile *objfile)
3348 {
3349   int i;
3350
3351   dw2_setup (objfile);
3352
3353   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3354                    + dwarf2_per_objfile->n_type_units); ++i)
3355     {
3356       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3357
3358       dw2_instantiate_symtab (per_cu);
3359     }
3360 }
3361
3362 static void
3363 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3364                                   const char *fullname)
3365 {
3366   int i;
3367
3368   dw2_setup (objfile);
3369
3370   /* We don't need to consider type units here.
3371      This is only called for examining code, e.g. expand_line_sal.
3372      There can be an order of magnitude (or more) more type units
3373      than comp units, and we avoid them if we can.  */
3374
3375   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3376     {
3377       int j;
3378       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3379       struct quick_file_names *file_data;
3380
3381       /* We only need to look at symtabs not already expanded.  */
3382       if (per_cu->v.quick->symtab)
3383         continue;
3384
3385       file_data = dw2_get_file_names (per_cu);
3386       if (file_data == NULL)
3387         continue;
3388
3389       for (j = 0; j < file_data->num_file_names; ++j)
3390         {
3391           const char *this_fullname = file_data->file_names[j];
3392
3393           if (filename_cmp (this_fullname, fullname) == 0)
3394             {
3395               dw2_instantiate_symtab (per_cu);
3396               break;
3397             }
3398         }
3399     }
3400 }
3401
3402 /* A helper function for dw2_find_symbol_file that finds the primary
3403    file name for a given CU.  This is a die_reader_func.  */
3404
3405 static void
3406 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3407                                  const gdb_byte *info_ptr,
3408                                  struct die_info *comp_unit_die,
3409                                  int has_children,
3410                                  void *data)
3411 {
3412   const char **result_ptr = data;
3413   struct dwarf2_cu *cu = reader->cu;
3414   struct attribute *attr;
3415
3416   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3417   if (attr == NULL)
3418     *result_ptr = NULL;
3419   else
3420     *result_ptr = DW_STRING (attr);
3421 }
3422
3423 static const char *
3424 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3425 {
3426   struct dwarf2_per_cu_data *per_cu;
3427   offset_type *vec;
3428   const char *filename;
3429
3430   dw2_setup (objfile);
3431
3432   /* index_table is NULL if OBJF_READNOW.  */
3433   if (!dwarf2_per_objfile->index_table)
3434     {
3435       struct symtab *s;
3436
3437       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3438         {
3439           struct blockvector *bv = BLOCKVECTOR (s);
3440           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3441           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3442
3443           if (sym)
3444             {
3445               /* Only file extension of returned filename is recognized.  */
3446               return SYMBOL_SYMTAB (sym)->filename;
3447             }
3448         }
3449       return NULL;
3450     }
3451
3452   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3453                                  name, &vec))
3454     return NULL;
3455
3456   /* Note that this just looks at the very first one named NAME -- but
3457      actually we are looking for a function.  find_main_filename
3458      should be rewritten so that it doesn't require a custom hook.  It
3459      could just use the ordinary symbol tables.  */
3460   /* vec[0] is the length, which must always be >0.  */
3461   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3462
3463   if (per_cu->v.quick->symtab != NULL)
3464     {
3465       /* Only file extension of returned filename is recognized.  */
3466       return per_cu->v.quick->symtab->filename;
3467     }
3468
3469   /* Initialize filename in case there's a problem reading the DWARF,
3470      dw2_get_primary_filename_reader may not get called.  */
3471   filename = NULL;
3472   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3473                            dw2_get_primary_filename_reader, &filename);
3474
3475   /* Only file extension of returned filename is recognized.  */
3476   return filename;
3477 }
3478
3479 static void
3480 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3481                           struct objfile *objfile, int global,
3482                           int (*callback) (struct block *,
3483                                            struct symbol *, void *),
3484                           void *data, symbol_compare_ftype *match,
3485                           symbol_compare_ftype *ordered_compare)
3486 {
3487   /* Currently unimplemented; used for Ada.  The function can be called if the
3488      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3489      does not look for non-Ada symbols this function should just return.  */
3490 }
3491
3492 static void
3493 dw2_expand_symtabs_matching
3494   (struct objfile *objfile,
3495    int (*file_matcher) (const char *, void *, int basenames),
3496    int (*name_matcher) (const char *, void *),
3497    enum search_domain kind,
3498    void *data)
3499 {
3500   int i;
3501   offset_type iter;
3502   struct mapped_index *index;
3503
3504   dw2_setup (objfile);
3505
3506   /* index_table is NULL if OBJF_READNOW.  */
3507   if (!dwarf2_per_objfile->index_table)
3508     return;
3509   index = dwarf2_per_objfile->index_table;
3510
3511   if (file_matcher != NULL)
3512     {
3513       struct cleanup *cleanup;
3514       htab_t visited_found, visited_not_found;
3515
3516       visited_found = htab_create_alloc (10,
3517                                          htab_hash_pointer, htab_eq_pointer,
3518                                          NULL, xcalloc, xfree);
3519       cleanup = make_cleanup_htab_delete (visited_found);
3520       visited_not_found = htab_create_alloc (10,
3521                                              htab_hash_pointer, htab_eq_pointer,
3522                                              NULL, xcalloc, xfree);
3523       make_cleanup_htab_delete (visited_not_found);
3524
3525       /* The rule is CUs specify all the files, including those used by
3526          any TU, so there's no need to scan TUs here.  */
3527
3528       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3529         {
3530           int j;
3531           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3532           struct quick_file_names *file_data;
3533           void **slot;
3534
3535           per_cu->v.quick->mark = 0;
3536
3537           /* We only need to look at symtabs not already expanded.  */
3538           if (per_cu->v.quick->symtab)
3539             continue;
3540
3541           file_data = dw2_get_file_names (per_cu);
3542           if (file_data == NULL)
3543             continue;
3544
3545           if (htab_find (visited_not_found, file_data) != NULL)
3546             continue;
3547           else if (htab_find (visited_found, file_data) != NULL)
3548             {
3549               per_cu->v.quick->mark = 1;
3550               continue;
3551             }
3552
3553           for (j = 0; j < file_data->num_file_names; ++j)
3554             {
3555               const char *this_real_name;
3556
3557               if (file_matcher (file_data->file_names[j], data, 0))
3558                 {
3559                   per_cu->v.quick->mark = 1;
3560                   break;
3561                 }
3562
3563               /* Before we invoke realpath, which can get expensive when many
3564                  files are involved, do a quick comparison of the basenames.  */
3565               if (!basenames_may_differ
3566                   && !file_matcher (lbasename (file_data->file_names[j]),
3567                                     data, 1))
3568                 continue;
3569
3570               this_real_name = dw2_get_real_path (objfile, file_data, j);
3571               if (file_matcher (this_real_name, data, 0))
3572                 {
3573                   per_cu->v.quick->mark = 1;
3574                   break;
3575                 }
3576             }
3577
3578           slot = htab_find_slot (per_cu->v.quick->mark
3579                                  ? visited_found
3580                                  : visited_not_found,
3581                                  file_data, INSERT);
3582           *slot = file_data;
3583         }
3584
3585       do_cleanups (cleanup);
3586     }
3587
3588   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3589     {
3590       offset_type idx = 2 * iter;
3591       const char *name;
3592       offset_type *vec, vec_len, vec_idx;
3593
3594       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3595         continue;
3596
3597       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3598
3599       if (! (*name_matcher) (name, data))
3600         continue;
3601
3602       /* The name was matched, now expand corresponding CUs that were
3603          marked.  */
3604       vec = (offset_type *) (index->constant_pool
3605                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3606       vec_len = MAYBE_SWAP (vec[0]);
3607       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3608         {
3609           struct dwarf2_per_cu_data *per_cu;
3610           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3611           gdb_index_symbol_kind symbol_kind =
3612             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3613           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3614
3615           /* Don't crash on bad data.  */
3616           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3617                            + dwarf2_per_objfile->n_type_units))
3618             continue;
3619
3620           /* Only check the symbol's kind if it has one.
3621              Indices prior to version 7 don't record it.  */
3622           if (index->version >= 7)
3623             {
3624               switch (kind)
3625                 {
3626                 case VARIABLES_DOMAIN:
3627                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3628                     continue;
3629                   break;
3630                 case FUNCTIONS_DOMAIN:
3631                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3632                     continue;
3633                   break;
3634                 case TYPES_DOMAIN:
3635                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3636                     continue;
3637                   break;
3638                 default:
3639                   break;
3640                 }
3641             }
3642
3643           per_cu = dw2_get_cu (cu_index);
3644           if (file_matcher == NULL || per_cu->v.quick->mark)
3645             dw2_instantiate_symtab (per_cu);
3646         }
3647     }
3648 }
3649
3650 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3651    symtab.  */
3652
3653 static struct symtab *
3654 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3655 {
3656   int i;
3657
3658   if (BLOCKVECTOR (symtab) != NULL
3659       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3660     return symtab;
3661
3662   if (symtab->includes == NULL)
3663     return NULL;
3664
3665   for (i = 0; symtab->includes[i]; ++i)
3666     {
3667       struct symtab *s = symtab->includes[i];
3668
3669       s = recursively_find_pc_sect_symtab (s, pc);
3670       if (s != NULL)
3671         return s;
3672     }
3673
3674   return NULL;
3675 }
3676
3677 static struct symtab *
3678 dw2_find_pc_sect_symtab (struct objfile *objfile,
3679                          struct minimal_symbol *msymbol,
3680                          CORE_ADDR pc,
3681                          struct obj_section *section,
3682                          int warn_if_readin)
3683 {
3684   struct dwarf2_per_cu_data *data;
3685   struct symtab *result;
3686
3687   dw2_setup (objfile);
3688
3689   if (!objfile->psymtabs_addrmap)
3690     return NULL;
3691
3692   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3693   if (!data)
3694     return NULL;
3695
3696   if (warn_if_readin && data->v.quick->symtab)
3697     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3698              paddress (get_objfile_arch (objfile), pc));
3699
3700   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3701   gdb_assert (result != NULL);
3702   return result;
3703 }
3704
3705 static void
3706 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3707                           void *data, int need_fullname)
3708 {
3709   int i;
3710   struct cleanup *cleanup;
3711   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3712                                       NULL, xcalloc, xfree);
3713
3714   cleanup = make_cleanup_htab_delete (visited);
3715   dw2_setup (objfile);
3716
3717   /* The rule is CUs specify all the files, including those used by
3718      any TU, so there's no need to scan TUs here.
3719      We can ignore file names coming from already-expanded CUs.  */
3720
3721   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3722     {
3723       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3724
3725       if (per_cu->v.quick->symtab)
3726         {
3727           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3728                                         INSERT);
3729
3730           *slot = per_cu->v.quick->file_names;
3731         }
3732     }
3733
3734   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3735     {
3736       int j;
3737       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3738       struct quick_file_names *file_data;
3739       void **slot;
3740
3741       /* We only need to look at symtabs not already expanded.  */
3742       if (per_cu->v.quick->symtab)
3743         continue;
3744
3745       file_data = dw2_get_file_names (per_cu);
3746       if (file_data == NULL)
3747         continue;
3748
3749       slot = htab_find_slot (visited, file_data, INSERT);
3750       if (*slot)
3751         {
3752           /* Already visited.  */
3753           continue;
3754         }
3755       *slot = file_data;
3756
3757       for (j = 0; j < file_data->num_file_names; ++j)
3758         {
3759           const char *this_real_name;
3760
3761           if (need_fullname)
3762             this_real_name = dw2_get_real_path (objfile, file_data, j);
3763           else
3764             this_real_name = NULL;
3765           (*fun) (file_data->file_names[j], this_real_name, data);
3766         }
3767     }
3768
3769   do_cleanups (cleanup);
3770 }
3771
3772 static int
3773 dw2_has_symbols (struct objfile *objfile)
3774 {
3775   return 1;
3776 }
3777
3778 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3779 {
3780   dw2_has_symbols,
3781   dw2_find_last_source_symtab,
3782   dw2_forget_cached_source_info,
3783   dw2_map_symtabs_matching_filename,
3784   dw2_lookup_symbol,
3785   dw2_print_stats,
3786   dw2_dump,
3787   dw2_relocate,
3788   dw2_expand_symtabs_for_function,
3789   dw2_expand_all_symtabs,
3790   dw2_expand_symtabs_with_fullname,
3791   dw2_find_symbol_file,
3792   dw2_map_matching_symbols,
3793   dw2_expand_symtabs_matching,
3794   dw2_find_pc_sect_symtab,
3795   dw2_map_symbol_filenames
3796 };
3797
3798 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3799    file will use psymtabs, or 1 if using the GNU index.  */
3800
3801 int
3802 dwarf2_initialize_objfile (struct objfile *objfile)
3803 {
3804   /* If we're about to read full symbols, don't bother with the
3805      indices.  In this case we also don't care if some other debug
3806      format is making psymtabs, because they are all about to be
3807      expanded anyway.  */
3808   if ((objfile->flags & OBJF_READNOW))
3809     {
3810       int i;
3811
3812       dwarf2_per_objfile->using_index = 1;
3813       create_all_comp_units (objfile);
3814       create_all_type_units (objfile);
3815       dwarf2_per_objfile->quick_file_names_table =
3816         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3817
3818       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3819                        + dwarf2_per_objfile->n_type_units); ++i)
3820         {
3821           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3822
3823           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3824                                             struct dwarf2_per_cu_quick_data);
3825         }
3826
3827       /* Return 1 so that gdb sees the "quick" functions.  However,
3828          these functions will be no-ops because we will have expanded
3829          all symtabs.  */
3830       return 1;
3831     }
3832
3833   if (dwarf2_read_index (objfile))
3834     return 1;
3835
3836   return 0;
3837 }
3838
3839 \f
3840
3841 /* Build a partial symbol table.  */
3842
3843 void
3844 dwarf2_build_psymtabs (struct objfile *objfile)
3845 {
3846   volatile struct gdb_exception except;
3847
3848   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3849     {
3850       init_psymbol_list (objfile, 1024);
3851     }
3852
3853   TRY_CATCH (except, RETURN_MASK_ERROR)
3854     {
3855       /* This isn't really ideal: all the data we allocate on the
3856          objfile's obstack is still uselessly kept around.  However,
3857          freeing it seems unsafe.  */
3858       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3859
3860       dwarf2_build_psymtabs_hard (objfile);
3861       discard_cleanups (cleanups);
3862     }
3863   if (except.reason < 0)
3864     exception_print (gdb_stderr, except);
3865 }
3866
3867 /* Return the total length of the CU described by HEADER.  */
3868
3869 static unsigned int
3870 get_cu_length (const struct comp_unit_head *header)
3871 {
3872   return header->initial_length_size + header->length;
3873 }
3874
3875 /* Return TRUE if OFFSET is within CU_HEADER.  */
3876
3877 static inline int
3878 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3879 {
3880   sect_offset bottom = { cu_header->offset.sect_off };
3881   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3882
3883   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3884 }
3885
3886 /* Find the base address of the compilation unit for range lists and
3887    location lists.  It will normally be specified by DW_AT_low_pc.
3888    In DWARF-3 draft 4, the base address could be overridden by
3889    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3890    compilation units with discontinuous ranges.  */
3891
3892 static void
3893 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3894 {
3895   struct attribute *attr;
3896
3897   cu->base_known = 0;
3898   cu->base_address = 0;
3899
3900   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3901   if (attr)
3902     {
3903       cu->base_address = DW_ADDR (attr);
3904       cu->base_known = 1;
3905     }
3906   else
3907     {
3908       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3909       if (attr)
3910         {
3911           cu->base_address = DW_ADDR (attr);
3912           cu->base_known = 1;
3913         }
3914     }
3915 }
3916
3917 /* Read in the comp unit header information from the debug_info at info_ptr.
3918    NOTE: This leaves members offset, first_die_offset to be filled in
3919    by the caller.  */
3920
3921 static const gdb_byte *
3922 read_comp_unit_head (struct comp_unit_head *cu_header,
3923                      const gdb_byte *info_ptr, bfd *abfd)
3924 {
3925   int signed_addr;
3926   unsigned int bytes_read;
3927
3928   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3929   cu_header->initial_length_size = bytes_read;
3930   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3931   info_ptr += bytes_read;
3932   cu_header->version = read_2_bytes (abfd, info_ptr);
3933   info_ptr += 2;
3934   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3935                                              &bytes_read);
3936   info_ptr += bytes_read;
3937   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3938   info_ptr += 1;
3939   signed_addr = bfd_get_sign_extend_vma (abfd);
3940   if (signed_addr < 0)
3941     internal_error (__FILE__, __LINE__,
3942                     _("read_comp_unit_head: dwarf from non elf file"));
3943   cu_header->signed_addr_p = signed_addr;
3944
3945   return info_ptr;
3946 }
3947
3948 /* Helper function that returns the proper abbrev section for
3949    THIS_CU.  */
3950
3951 static struct dwarf2_section_info *
3952 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3953 {
3954   struct dwarf2_section_info *abbrev;
3955
3956   if (this_cu->is_dwz)
3957     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3958   else
3959     abbrev = &dwarf2_per_objfile->abbrev;
3960
3961   return abbrev;
3962 }
3963
3964 /* Subroutine of read_and_check_comp_unit_head and
3965    read_and_check_type_unit_head to simplify them.
3966    Perform various error checking on the header.  */
3967
3968 static void
3969 error_check_comp_unit_head (struct comp_unit_head *header,
3970                             struct dwarf2_section_info *section,
3971                             struct dwarf2_section_info *abbrev_section)
3972 {
3973   bfd *abfd = section->asection->owner;
3974   const char *filename = bfd_get_filename (abfd);
3975
3976   if (header->version != 2 && header->version != 3 && header->version != 4)
3977     error (_("Dwarf Error: wrong version in compilation unit header "
3978            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3979            filename);
3980
3981   if (header->abbrev_offset.sect_off
3982       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3983     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3984            "(offset 0x%lx + 6) [in module %s]"),
3985            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3986            filename);
3987
3988   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3989      avoid potential 32-bit overflow.  */
3990   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3991       > section->size)
3992     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3993            "(offset 0x%lx + 0) [in module %s]"),
3994            (long) header->length, (long) header->offset.sect_off,
3995            filename);
3996 }
3997
3998 /* Read in a CU/TU header and perform some basic error checking.
3999    The contents of the header are stored in HEADER.
4000    The result is a pointer to the start of the first DIE.  */
4001
4002 static const gdb_byte *
4003 read_and_check_comp_unit_head (struct comp_unit_head *header,
4004                                struct dwarf2_section_info *section,
4005                                struct dwarf2_section_info *abbrev_section,
4006                                const gdb_byte *info_ptr,
4007                                int is_debug_types_section)
4008 {
4009   const gdb_byte *beg_of_comp_unit = info_ptr;
4010   bfd *abfd = section->asection->owner;
4011
4012   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4013
4014   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4015
4016   /* If we're reading a type unit, skip over the signature and
4017      type_offset fields.  */
4018   if (is_debug_types_section)
4019     info_ptr += 8 /*signature*/ + header->offset_size;
4020
4021   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4022
4023   error_check_comp_unit_head (header, section, abbrev_section);
4024
4025   return info_ptr;
4026 }
4027
4028 /* Read in the types comp unit header information from .debug_types entry at
4029    types_ptr.  The result is a pointer to one past the end of the header.  */
4030
4031 static const gdb_byte *
4032 read_and_check_type_unit_head (struct comp_unit_head *header,
4033                                struct dwarf2_section_info *section,
4034                                struct dwarf2_section_info *abbrev_section,
4035                                const gdb_byte *info_ptr,
4036                                ULONGEST *signature,
4037                                cu_offset *type_offset_in_tu)
4038 {
4039   const gdb_byte *beg_of_comp_unit = info_ptr;
4040   bfd *abfd = section->asection->owner;
4041
4042   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4043
4044   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4045
4046   /* If we're reading a type unit, skip over the signature and
4047      type_offset fields.  */
4048   if (signature != NULL)
4049     *signature = read_8_bytes (abfd, info_ptr);
4050   info_ptr += 8;
4051   if (type_offset_in_tu != NULL)
4052     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4053                                                header->offset_size);
4054   info_ptr += header->offset_size;
4055
4056   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4057
4058   error_check_comp_unit_head (header, section, abbrev_section);
4059
4060   return info_ptr;
4061 }
4062
4063 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4064
4065 static sect_offset
4066 read_abbrev_offset (struct dwarf2_section_info *section,
4067                     sect_offset offset)
4068 {
4069   bfd *abfd = section->asection->owner;
4070   const gdb_byte *info_ptr;
4071   unsigned int length, initial_length_size, offset_size;
4072   sect_offset abbrev_offset;
4073
4074   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4075   info_ptr = section->buffer + offset.sect_off;
4076   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4077   offset_size = initial_length_size == 4 ? 4 : 8;
4078   info_ptr += initial_length_size + 2 /*version*/;
4079   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4080   return abbrev_offset;
4081 }
4082
4083 /* Allocate a new partial symtab for file named NAME and mark this new
4084    partial symtab as being an include of PST.  */
4085
4086 static void
4087 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4088                                struct objfile *objfile)
4089 {
4090   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4091
4092   if (!IS_ABSOLUTE_PATH (subpst->filename))
4093     {
4094       /* It shares objfile->objfile_obstack.  */
4095       subpst->dirname = pst->dirname;
4096     }
4097
4098   subpst->section_offsets = pst->section_offsets;
4099   subpst->textlow = 0;
4100   subpst->texthigh = 0;
4101
4102   subpst->dependencies = (struct partial_symtab **)
4103     obstack_alloc (&objfile->objfile_obstack,
4104                    sizeof (struct partial_symtab *));
4105   subpst->dependencies[0] = pst;
4106   subpst->number_of_dependencies = 1;
4107
4108   subpst->globals_offset = 0;
4109   subpst->n_global_syms = 0;
4110   subpst->statics_offset = 0;
4111   subpst->n_static_syms = 0;
4112   subpst->symtab = NULL;
4113   subpst->read_symtab = pst->read_symtab;
4114   subpst->readin = 0;
4115
4116   /* No private part is necessary for include psymtabs.  This property
4117      can be used to differentiate between such include psymtabs and
4118      the regular ones.  */
4119   subpst->read_symtab_private = NULL;
4120 }
4121
4122 /* Read the Line Number Program data and extract the list of files
4123    included by the source file represented by PST.  Build an include
4124    partial symtab for each of these included files.  */
4125
4126 static void
4127 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4128                                struct die_info *die,
4129                                struct partial_symtab *pst)
4130 {
4131   struct line_header *lh = NULL;
4132   struct attribute *attr;
4133
4134   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4135   if (attr)
4136     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4137   if (lh == NULL)
4138     return;  /* No linetable, so no includes.  */
4139
4140   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4141   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4142
4143   free_line_header (lh);
4144 }
4145
4146 static hashval_t
4147 hash_signatured_type (const void *item)
4148 {
4149   const struct signatured_type *sig_type = item;
4150
4151   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4152   return sig_type->signature;
4153 }
4154
4155 static int
4156 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4157 {
4158   const struct signatured_type *lhs = item_lhs;
4159   const struct signatured_type *rhs = item_rhs;
4160
4161   return lhs->signature == rhs->signature;
4162 }
4163
4164 /* Allocate a hash table for signatured types.  */
4165
4166 static htab_t
4167 allocate_signatured_type_table (struct objfile *objfile)
4168 {
4169   return htab_create_alloc_ex (41,
4170                                hash_signatured_type,
4171                                eq_signatured_type,
4172                                NULL,
4173                                &objfile->objfile_obstack,
4174                                hashtab_obstack_allocate,
4175                                dummy_obstack_deallocate);
4176 }
4177
4178 /* A helper function to add a signatured type CU to a table.  */
4179
4180 static int
4181 add_signatured_type_cu_to_table (void **slot, void *datum)
4182 {
4183   struct signatured_type *sigt = *slot;
4184   struct signatured_type ***datap = datum;
4185
4186   **datap = sigt;
4187   ++*datap;
4188
4189   return 1;
4190 }
4191
4192 /* Create the hash table of all entries in the .debug_types
4193    (or .debug_types.dwo) section(s).
4194    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4195    otherwise it is NULL.
4196
4197    The result is a pointer to the hash table or NULL if there are no types.
4198
4199    Note: This function processes DWO files only, not DWP files.  */
4200
4201 static htab_t
4202 create_debug_types_hash_table (struct dwo_file *dwo_file,
4203                                VEC (dwarf2_section_info_def) *types)
4204 {
4205   struct objfile *objfile = dwarf2_per_objfile->objfile;
4206   htab_t types_htab = NULL;
4207   int ix;
4208   struct dwarf2_section_info *section;
4209   struct dwarf2_section_info *abbrev_section;
4210
4211   if (VEC_empty (dwarf2_section_info_def, types))
4212     return NULL;
4213
4214   abbrev_section = (dwo_file != NULL
4215                     ? &dwo_file->sections.abbrev
4216                     : &dwarf2_per_objfile->abbrev);
4217
4218   if (dwarf2_read_debug)
4219     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4220                         dwo_file ? ".dwo" : "",
4221                         bfd_get_filename (abbrev_section->asection->owner));
4222
4223   for (ix = 0;
4224        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4225        ++ix)
4226     {
4227       bfd *abfd;
4228       const gdb_byte *info_ptr, *end_ptr;
4229       struct dwarf2_section_info *abbrev_section;
4230
4231       dwarf2_read_section (objfile, section);
4232       info_ptr = section->buffer;
4233
4234       if (info_ptr == NULL)
4235         continue;
4236
4237       /* We can't set abfd until now because the section may be empty or
4238          not present, in which case section->asection will be NULL.  */
4239       abfd = section->asection->owner;
4240
4241       if (dwo_file)
4242         abbrev_section = &dwo_file->sections.abbrev;
4243       else
4244         abbrev_section = &dwarf2_per_objfile->abbrev;
4245
4246       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4247          because we don't need to read any dies: the signature is in the
4248          header.  */
4249
4250       end_ptr = info_ptr + section->size;
4251       while (info_ptr < end_ptr)
4252         {
4253           sect_offset offset;
4254           cu_offset type_offset_in_tu;
4255           ULONGEST signature;
4256           struct signatured_type *sig_type;
4257           struct dwo_unit *dwo_tu;
4258           void **slot;
4259           const gdb_byte *ptr = info_ptr;
4260           struct comp_unit_head header;
4261           unsigned int length;
4262
4263           offset.sect_off = ptr - section->buffer;
4264
4265           /* We need to read the type's signature in order to build the hash
4266              table, but we don't need anything else just yet.  */
4267
4268           ptr = read_and_check_type_unit_head (&header, section,
4269                                                abbrev_section, ptr,
4270                                                &signature, &type_offset_in_tu);
4271
4272           length = get_cu_length (&header);
4273
4274           /* Skip dummy type units.  */
4275           if (ptr >= info_ptr + length
4276               || peek_abbrev_code (abfd, ptr) == 0)
4277             {
4278               info_ptr += length;
4279               continue;
4280             }
4281
4282           if (types_htab == NULL)
4283             {
4284               if (dwo_file)
4285                 types_htab = allocate_dwo_unit_table (objfile);
4286               else
4287                 types_htab = allocate_signatured_type_table (objfile);
4288             }
4289
4290           if (dwo_file)
4291             {
4292               sig_type = NULL;
4293               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4294                                        struct dwo_unit);
4295               dwo_tu->dwo_file = dwo_file;
4296               dwo_tu->signature = signature;
4297               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4298               dwo_tu->section = section;
4299               dwo_tu->offset = offset;
4300               dwo_tu->length = length;
4301             }
4302           else
4303             {
4304               /* N.B.: type_offset is not usable if this type uses a DWO file.
4305                  The real type_offset is in the DWO file.  */
4306               dwo_tu = NULL;
4307               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4308                                          struct signatured_type);
4309               sig_type->signature = signature;
4310               sig_type->type_offset_in_tu = type_offset_in_tu;
4311               sig_type->per_cu.objfile = objfile;
4312               sig_type->per_cu.is_debug_types = 1;
4313               sig_type->per_cu.section = section;
4314               sig_type->per_cu.offset = offset;
4315               sig_type->per_cu.length = length;
4316             }
4317
4318           slot = htab_find_slot (types_htab,
4319                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4320                                  INSERT);
4321           gdb_assert (slot != NULL);
4322           if (*slot != NULL)
4323             {
4324               sect_offset dup_offset;
4325
4326               if (dwo_file)
4327                 {
4328                   const struct dwo_unit *dup_tu = *slot;
4329
4330                   dup_offset = dup_tu->offset;
4331                 }
4332               else
4333                 {
4334                   const struct signatured_type *dup_tu = *slot;
4335
4336                   dup_offset = dup_tu->per_cu.offset;
4337                 }
4338
4339               complaint (&symfile_complaints,
4340                          _("debug type entry at offset 0x%x is duplicate to"
4341                            " the entry at offset 0x%x, signature %s"),
4342                          offset.sect_off, dup_offset.sect_off,
4343                          hex_string (signature));
4344             }
4345           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4346
4347           if (dwarf2_read_debug)
4348             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4349                                 offset.sect_off,
4350                                 hex_string (signature));
4351
4352           info_ptr += length;
4353         }
4354     }
4355
4356   return types_htab;
4357 }
4358
4359 /* Create the hash table of all entries in the .debug_types section,
4360    and initialize all_type_units.
4361    The result is zero if there is an error (e.g. missing .debug_types section),
4362    otherwise non-zero.  */
4363
4364 static int
4365 create_all_type_units (struct objfile *objfile)
4366 {
4367   htab_t types_htab;
4368   struct signatured_type **iter;
4369
4370   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4371   if (types_htab == NULL)
4372     {
4373       dwarf2_per_objfile->signatured_types = NULL;
4374       return 0;
4375     }
4376
4377   dwarf2_per_objfile->signatured_types = types_htab;
4378
4379   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4380   dwarf2_per_objfile->all_type_units
4381     = obstack_alloc (&objfile->objfile_obstack,
4382                      dwarf2_per_objfile->n_type_units
4383                      * sizeof (struct signatured_type *));
4384   iter = &dwarf2_per_objfile->all_type_units[0];
4385   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4386   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4387               == dwarf2_per_objfile->n_type_units);
4388
4389   return 1;
4390 }
4391
4392 /* Lookup a signature based type for DW_FORM_ref_sig8.
4393    Returns NULL if signature SIG is not present in the table.
4394    It is up to the caller to complain about this.  */
4395
4396 static struct signatured_type *
4397 lookup_signatured_type (ULONGEST sig)
4398 {
4399   struct signatured_type find_entry, *entry;
4400
4401   if (dwarf2_per_objfile->signatured_types == NULL)
4402     return NULL;
4403   find_entry.signature = sig;
4404   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4405   return entry;
4406 }
4407 \f
4408 /* Low level DIE reading support.  */
4409
4410 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4411
4412 static void
4413 init_cu_die_reader (struct die_reader_specs *reader,
4414                     struct dwarf2_cu *cu,
4415                     struct dwarf2_section_info *section,
4416                     struct dwo_file *dwo_file)
4417 {
4418   gdb_assert (section->readin && section->buffer != NULL);
4419   reader->abfd = section->asection->owner;
4420   reader->cu = cu;
4421   reader->dwo_file = dwo_file;
4422   reader->die_section = section;
4423   reader->buffer = section->buffer;
4424   reader->buffer_end = section->buffer + section->size;
4425 }
4426
4427 /* Subroutine of init_cutu_and_read_dies to simplify it.
4428    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4429    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4430    already.
4431
4432    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4433    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4434    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4435    are filled in with the info of the DIE from the DWO file.
4436    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4437    provided an abbrev table to use.
4438    The result is non-zero if a valid (non-dummy) DIE was found.  */
4439
4440 static int
4441 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4442                         struct dwo_unit *dwo_unit,
4443                         int abbrev_table_provided,
4444                         struct die_info *stub_comp_unit_die,
4445                         struct die_reader_specs *result_reader,
4446                         const gdb_byte **result_info_ptr,
4447                         struct die_info **result_comp_unit_die,
4448                         int *result_has_children)
4449 {
4450   struct objfile *objfile = dwarf2_per_objfile->objfile;
4451   struct dwarf2_cu *cu = this_cu->cu;
4452   struct dwarf2_section_info *section;
4453   bfd *abfd;
4454   const gdb_byte *begin_info_ptr, *info_ptr;
4455   const char *comp_dir_string;
4456   ULONGEST signature; /* Or dwo_id.  */
4457   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4458   int i,num_extra_attrs;
4459   struct dwarf2_section_info *dwo_abbrev_section;
4460   struct attribute *attr;
4461   struct die_info *comp_unit_die;
4462
4463   /* These attributes aren't processed until later:
4464      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4465      However, the attribute is found in the stub which we won't have later.
4466      In order to not impose this complication on the rest of the code,
4467      we read them here and copy them to the DWO CU/TU die.  */
4468
4469   stmt_list = NULL;
4470   low_pc = NULL;
4471   high_pc = NULL;
4472   ranges = NULL;
4473   comp_dir = NULL;
4474
4475   if (stub_comp_unit_die != NULL)
4476     {
4477       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4478          DWO file.  */
4479       if (! this_cu->is_debug_types)
4480         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4481       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4482       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4483       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4484       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4485
4486       /* There should be a DW_AT_addr_base attribute here (if needed).
4487          We need the value before we can process DW_FORM_GNU_addr_index.  */
4488       cu->addr_base = 0;
4489       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4490       if (attr)
4491         cu->addr_base = DW_UNSND (attr);
4492
4493       /* There should be a DW_AT_ranges_base attribute here (if needed).
4494          We need the value before we can process DW_AT_ranges.  */
4495       cu->ranges_base = 0;
4496       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4497       if (attr)
4498         cu->ranges_base = DW_UNSND (attr);
4499     }
4500
4501   /* Set up for reading the DWO CU/TU.  */
4502   cu->dwo_unit = dwo_unit;
4503   section = dwo_unit->section;
4504   dwarf2_read_section (objfile, section);
4505   abfd = section->asection->owner;
4506   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4507   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4508   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4509
4510   if (this_cu->is_debug_types)
4511     {
4512       ULONGEST header_signature;
4513       cu_offset type_offset_in_tu;
4514       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4515
4516       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4517                                                 dwo_abbrev_section,
4518                                                 info_ptr,
4519                                                 &header_signature,
4520                                                 &type_offset_in_tu);
4521       gdb_assert (sig_type->signature == header_signature);
4522       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4523       /* For DWOs coming from DWP files, we don't know the CU length
4524          nor the type's offset in the TU until now.  */
4525       dwo_unit->length = get_cu_length (&cu->header);
4526       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4527
4528       /* Establish the type offset that can be used to lookup the type.
4529          For DWO files, we don't know it until now.  */
4530       sig_type->type_offset_in_section.sect_off =
4531         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4532     }
4533   else
4534     {
4535       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4536                                                 dwo_abbrev_section,
4537                                                 info_ptr, 0);
4538       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4539       /* For DWOs coming from DWP files, we don't know the CU length
4540          until now.  */
4541       dwo_unit->length = get_cu_length (&cu->header);
4542     }
4543
4544   /* Replace the CU's original abbrev table with the DWO's.
4545      Reminder: We can't read the abbrev table until we've read the header.  */
4546   if (abbrev_table_provided)
4547     {
4548       /* Don't free the provided abbrev table, the caller of
4549          init_cutu_and_read_dies owns it.  */
4550       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4551       /* Ensure the DWO abbrev table gets freed.  */
4552       make_cleanup (dwarf2_free_abbrev_table, cu);
4553     }
4554   else
4555     {
4556       dwarf2_free_abbrev_table (cu);
4557       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4558       /* Leave any existing abbrev table cleanup as is.  */
4559     }
4560
4561   /* Read in the die, but leave space to copy over the attributes
4562      from the stub.  This has the benefit of simplifying the rest of
4563      the code - all the work to maintain the illusion of a single
4564      DW_TAG_{compile,type}_unit DIE is done here.  */
4565   num_extra_attrs = ((stmt_list != NULL)
4566                      + (low_pc != NULL)
4567                      + (high_pc != NULL)
4568                      + (ranges != NULL)
4569                      + (comp_dir != NULL));
4570   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4571                               result_has_children, num_extra_attrs);
4572
4573   /* Copy over the attributes from the stub to the DIE we just read in.  */
4574   comp_unit_die = *result_comp_unit_die;
4575   i = comp_unit_die->num_attrs;
4576   if (stmt_list != NULL)
4577     comp_unit_die->attrs[i++] = *stmt_list;
4578   if (low_pc != NULL)
4579     comp_unit_die->attrs[i++] = *low_pc;
4580   if (high_pc != NULL)
4581     comp_unit_die->attrs[i++] = *high_pc;
4582   if (ranges != NULL)
4583     comp_unit_die->attrs[i++] = *ranges;
4584   if (comp_dir != NULL)
4585     comp_unit_die->attrs[i++] = *comp_dir;
4586   comp_unit_die->num_attrs += num_extra_attrs;
4587
4588   if (dwarf2_die_debug)
4589     {
4590       fprintf_unfiltered (gdb_stdlog,
4591                           "Read die from %s@0x%x of %s:\n",
4592                           bfd_section_name (abfd, section->asection),
4593                           (unsigned) (begin_info_ptr - section->buffer),
4594                           bfd_get_filename (abfd));
4595       dump_die (comp_unit_die, dwarf2_die_debug);
4596     }
4597
4598   /* Skip dummy compilation units.  */
4599   if (info_ptr >= begin_info_ptr + dwo_unit->length
4600       || peek_abbrev_code (abfd, info_ptr) == 0)
4601     return 0;
4602
4603   *result_info_ptr = info_ptr;
4604   return 1;
4605 }
4606
4607 /* Subroutine of init_cutu_and_read_dies to simplify it.
4608    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4609    Returns NULL if the specified DWO unit cannot be found.  */
4610
4611 static struct dwo_unit *
4612 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4613                  struct die_info *comp_unit_die)
4614 {
4615   struct dwarf2_cu *cu = this_cu->cu;
4616   struct attribute *attr;
4617   ULONGEST signature;
4618   struct dwo_unit *dwo_unit;
4619   const char *comp_dir, *dwo_name;
4620
4621   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4622   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4623   gdb_assert (attr != NULL);
4624   dwo_name = DW_STRING (attr);
4625   comp_dir = NULL;
4626   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4627   if (attr)
4628     comp_dir = DW_STRING (attr);
4629
4630   if (this_cu->is_debug_types)
4631     {
4632       struct signatured_type *sig_type;
4633
4634       /* Since this_cu is the first member of struct signatured_type,
4635          we can go from a pointer to one to a pointer to the other.  */
4636       sig_type = (struct signatured_type *) this_cu;
4637       signature = sig_type->signature;
4638       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4639     }
4640   else
4641     {
4642       struct attribute *attr;
4643
4644       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4645       if (! attr)
4646         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4647                  " [in module %s]"),
4648                dwo_name, this_cu->objfile->name);
4649       signature = DW_UNSND (attr);
4650       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4651                                        signature);
4652     }
4653
4654   return dwo_unit;
4655 }
4656
4657 /* Initialize a CU (or TU) and read its DIEs.
4658    If the CU defers to a DWO file, read the DWO file as well.
4659
4660    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4661    Otherwise the table specified in the comp unit header is read in and used.
4662    This is an optimization for when we already have the abbrev table.
4663
4664    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4665    Otherwise, a new CU is allocated with xmalloc.
4666
4667    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4668    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4669
4670    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4671    linker) then DIE_READER_FUNC will not get called.  */
4672
4673 static void
4674 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4675                          struct abbrev_table *abbrev_table,
4676                          int use_existing_cu, int keep,
4677                          die_reader_func_ftype *die_reader_func,
4678                          void *data)
4679 {
4680   struct objfile *objfile = dwarf2_per_objfile->objfile;
4681   struct dwarf2_section_info *section = this_cu->section;
4682   bfd *abfd = section->asection->owner;
4683   struct dwarf2_cu *cu;
4684   const gdb_byte *begin_info_ptr, *info_ptr;
4685   struct die_reader_specs reader;
4686   struct die_info *comp_unit_die;
4687   int has_children;
4688   struct attribute *attr;
4689   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4690   struct signatured_type *sig_type = NULL;
4691   struct dwarf2_section_info *abbrev_section;
4692   /* Non-zero if CU currently points to a DWO file and we need to
4693      reread it.  When this happens we need to reread the skeleton die
4694      before we can reread the DWO file.  */
4695   int rereading_dwo_cu = 0;
4696
4697   if (dwarf2_die_debug)
4698     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4699                         this_cu->is_debug_types ? "type" : "comp",
4700                         this_cu->offset.sect_off);
4701
4702   if (use_existing_cu)
4703     gdb_assert (keep);
4704
4705   cleanups = make_cleanup (null_cleanup, NULL);
4706
4707   /* This is cheap if the section is already read in.  */
4708   dwarf2_read_section (objfile, section);
4709
4710   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4711
4712   abbrev_section = get_abbrev_section_for_cu (this_cu);
4713
4714   if (use_existing_cu && this_cu->cu != NULL)
4715     {
4716       cu = this_cu->cu;
4717
4718       /* If this CU is from a DWO file we need to start over, we need to
4719          refetch the attributes from the skeleton CU.
4720          This could be optimized by retrieving those attributes from when we
4721          were here the first time: the previous comp_unit_die was stored in
4722          comp_unit_obstack.  But there's no data yet that we need this
4723          optimization.  */
4724       if (cu->dwo_unit != NULL)
4725         rereading_dwo_cu = 1;
4726     }
4727   else
4728     {
4729       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4730       gdb_assert (this_cu->cu == NULL);
4731
4732       cu = xmalloc (sizeof (*cu));
4733       init_one_comp_unit (cu, this_cu);
4734
4735       /* If an error occurs while loading, release our storage.  */
4736       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4737     }
4738
4739   /* Get the header.  */
4740   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4741     {
4742       /* We already have the header, there's no need to read it in again.  */
4743       info_ptr += cu->header.first_die_offset.cu_off;
4744     }
4745   else
4746     {
4747       if (this_cu->is_debug_types)
4748         {
4749           ULONGEST signature;
4750           cu_offset type_offset_in_tu;
4751
4752           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4753                                                     abbrev_section, info_ptr,
4754                                                     &signature,
4755                                                     &type_offset_in_tu);
4756
4757           /* Since per_cu is the first member of struct signatured_type,
4758              we can go from a pointer to one to a pointer to the other.  */
4759           sig_type = (struct signatured_type *) this_cu;
4760           gdb_assert (sig_type->signature == signature);
4761           gdb_assert (sig_type->type_offset_in_tu.cu_off
4762                       == type_offset_in_tu.cu_off);
4763           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4764
4765           /* LENGTH has not been set yet for type units if we're
4766              using .gdb_index.  */
4767           this_cu->length = get_cu_length (&cu->header);
4768
4769           /* Establish the type offset that can be used to lookup the type.  */
4770           sig_type->type_offset_in_section.sect_off =
4771             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4772         }
4773       else
4774         {
4775           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4776                                                     abbrev_section,
4777                                                     info_ptr, 0);
4778
4779           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4780           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4781         }
4782     }
4783
4784   /* Skip dummy compilation units.  */
4785   if (info_ptr >= begin_info_ptr + this_cu->length
4786       || peek_abbrev_code (abfd, info_ptr) == 0)
4787     {
4788       do_cleanups (cleanups);
4789       return;
4790     }
4791
4792   /* If we don't have them yet, read the abbrevs for this compilation unit.
4793      And if we need to read them now, make sure they're freed when we're
4794      done.  Note that it's important that if the CU had an abbrev table
4795      on entry we don't free it when we're done: Somewhere up the call stack
4796      it may be in use.  */
4797   if (abbrev_table != NULL)
4798     {
4799       gdb_assert (cu->abbrev_table == NULL);
4800       gdb_assert (cu->header.abbrev_offset.sect_off
4801                   == abbrev_table->offset.sect_off);
4802       cu->abbrev_table = abbrev_table;
4803     }
4804   else if (cu->abbrev_table == NULL)
4805     {
4806       dwarf2_read_abbrevs (cu, abbrev_section);
4807       make_cleanup (dwarf2_free_abbrev_table, cu);
4808     }
4809   else if (rereading_dwo_cu)
4810     {
4811       dwarf2_free_abbrev_table (cu);
4812       dwarf2_read_abbrevs (cu, abbrev_section);
4813     }
4814
4815   /* Read the top level CU/TU die.  */
4816   init_cu_die_reader (&reader, cu, section, NULL);
4817   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4818
4819   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
4820      from the DWO file.
4821      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
4822      DWO CU, that this test will fail (the attribute will not be present).  */
4823   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4824   if (attr)
4825     {
4826       struct dwo_unit *dwo_unit;
4827       struct die_info *dwo_comp_unit_die;
4828
4829       if (has_children)
4830         {
4831           complaint (&symfile_complaints,
4832                      _("compilation unit with DW_AT_GNU_dwo_name"
4833                        " has children (offset 0x%x) [in module %s]"),
4834                      this_cu->offset.sect_off, bfd_get_filename (abfd));
4835         }
4836       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
4837       if (dwo_unit != NULL)
4838         {
4839           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
4840                                       abbrev_table != NULL,
4841                                       comp_unit_die,
4842                                       &reader, &info_ptr,
4843                                       &dwo_comp_unit_die, &has_children) == 0)
4844             {
4845               /* Dummy die.  */
4846               do_cleanups (cleanups);
4847               return;
4848             }
4849           comp_unit_die = dwo_comp_unit_die;
4850         }
4851       else
4852         {
4853           /* Yikes, we couldn't find the rest of the DIE, we only have
4854              the stub.  A complaint has already been logged.  There's
4855              not much more we can do except pass on the stub DIE to
4856              die_reader_func.  We don't want to throw an error on bad
4857              debug info.  */
4858         }
4859     }
4860
4861   /* All of the above is setup for this call.  Yikes.  */
4862   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4863
4864   /* Done, clean up.  */
4865   if (free_cu_cleanup != NULL)
4866     {
4867       if (keep)
4868         {
4869           /* We've successfully allocated this compilation unit.  Let our
4870              caller clean it up when finished with it.  */
4871           discard_cleanups (free_cu_cleanup);
4872
4873           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4874              So we have to manually free the abbrev table.  */
4875           dwarf2_free_abbrev_table (cu);
4876
4877           /* Link this CU into read_in_chain.  */
4878           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4879           dwarf2_per_objfile->read_in_chain = this_cu;
4880         }
4881       else
4882         do_cleanups (free_cu_cleanup);
4883     }
4884
4885   do_cleanups (cleanups);
4886 }
4887
4888 /* Read CU/TU THIS_CU in section SECTION,
4889    but do not follow DW_AT_GNU_dwo_name if present.
4890    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4891    to have already done the lookup to find the DWO/DWP file).
4892
4893    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4894    THIS_CU->is_debug_types, but nothing else.
4895
4896    We fill in THIS_CU->length.
4897
4898    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4899    linker) then DIE_READER_FUNC will not get called.
4900
4901    THIS_CU->cu is always freed when done.
4902    This is done in order to not leave THIS_CU->cu in a state where we have
4903    to care whether it refers to the "main" CU or the DWO CU.  */
4904
4905 static void
4906 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4907                                    struct dwarf2_section_info *abbrev_section,
4908                                    struct dwo_file *dwo_file,
4909                                    die_reader_func_ftype *die_reader_func,
4910                                    void *data)
4911 {
4912   struct objfile *objfile = dwarf2_per_objfile->objfile;
4913   struct dwarf2_section_info *section = this_cu->section;
4914   bfd *abfd = section->asection->owner;
4915   struct dwarf2_cu cu;
4916   const gdb_byte *begin_info_ptr, *info_ptr;
4917   struct die_reader_specs reader;
4918   struct cleanup *cleanups;
4919   struct die_info *comp_unit_die;
4920   int has_children;
4921
4922   if (dwarf2_die_debug)
4923     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4924                         this_cu->is_debug_types ? "type" : "comp",
4925                         this_cu->offset.sect_off);
4926
4927   gdb_assert (this_cu->cu == NULL);
4928
4929   /* This is cheap if the section is already read in.  */
4930   dwarf2_read_section (objfile, section);
4931
4932   init_one_comp_unit (&cu, this_cu);
4933
4934   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4935
4936   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4937   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4938                                             abbrev_section, info_ptr,
4939                                             this_cu->is_debug_types);
4940
4941   this_cu->length = get_cu_length (&cu.header);
4942
4943   /* Skip dummy compilation units.  */
4944   if (info_ptr >= begin_info_ptr + this_cu->length
4945       || peek_abbrev_code (abfd, info_ptr) == 0)
4946     {
4947       do_cleanups (cleanups);
4948       return;
4949     }
4950
4951   dwarf2_read_abbrevs (&cu, abbrev_section);
4952   make_cleanup (dwarf2_free_abbrev_table, &cu);
4953
4954   init_cu_die_reader (&reader, &cu, section, dwo_file);
4955   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4956
4957   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4958
4959   do_cleanups (cleanups);
4960 }
4961
4962 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4963    does not lookup the specified DWO file.
4964    This cannot be used to read DWO files.
4965
4966    THIS_CU->cu is always freed when done.
4967    This is done in order to not leave THIS_CU->cu in a state where we have
4968    to care whether it refers to the "main" CU or the DWO CU.
4969    We can revisit this if the data shows there's a performance issue.  */
4970
4971 static void
4972 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4973                                 die_reader_func_ftype *die_reader_func,
4974                                 void *data)
4975 {
4976   init_cutu_and_read_dies_no_follow (this_cu,
4977                                      get_abbrev_section_for_cu (this_cu),
4978                                      NULL,
4979                                      die_reader_func, data);
4980 }
4981 \f
4982 /* Type Unit Groups.
4983
4984    Type Unit Groups are a way to collapse the set of all TUs (type units) into
4985    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
4986    so that all types coming from the same compilation (.o file) are grouped
4987    together.  A future step could be to put the types in the same symtab as
4988    the CU the types ultimately came from.  */
4989
4990 static hashval_t
4991 hash_type_unit_group (const void *item)
4992 {
4993   const struct type_unit_group *tu_group = item;
4994
4995   return hash_stmt_list_entry (&tu_group->hash);
4996 }
4997
4998 static int
4999 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5000 {
5001   const struct type_unit_group *lhs = item_lhs;
5002   const struct type_unit_group *rhs = item_rhs;
5003
5004   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5005 }
5006
5007 /* Allocate a hash table for type unit groups.  */
5008
5009 static htab_t
5010 allocate_type_unit_groups_table (void)
5011 {
5012   return htab_create_alloc_ex (3,
5013                                hash_type_unit_group,
5014                                eq_type_unit_group,
5015                                NULL,
5016                                &dwarf2_per_objfile->objfile->objfile_obstack,
5017                                hashtab_obstack_allocate,
5018                                dummy_obstack_deallocate);
5019 }
5020
5021 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5022    partial symtabs.  We combine several TUs per psymtab to not let the size
5023    of any one psymtab grow too big.  */
5024 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5025 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5026
5027 /* Helper routine for get_type_unit_group.
5028    Create the type_unit_group object used to hold one or more TUs.  */
5029
5030 static struct type_unit_group *
5031 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5032 {
5033   struct objfile *objfile = dwarf2_per_objfile->objfile;
5034   struct dwarf2_per_cu_data *per_cu;
5035   struct type_unit_group *tu_group;
5036
5037   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5038                              struct type_unit_group);
5039   per_cu = &tu_group->per_cu;
5040   per_cu->objfile = objfile;
5041
5042   if (dwarf2_per_objfile->using_index)
5043     {
5044       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5045                                         struct dwarf2_per_cu_quick_data);
5046     }
5047   else
5048     {
5049       unsigned int line_offset = line_offset_struct.sect_off;
5050       struct partial_symtab *pst;
5051       char *name;
5052
5053       /* Give the symtab a useful name for debug purposes.  */
5054       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5055         name = xstrprintf ("<type_units_%d>",
5056                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5057       else
5058         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5059
5060       pst = create_partial_symtab (per_cu, name);
5061       pst->anonymous = 1;
5062
5063       xfree (name);
5064     }
5065
5066   tu_group->hash.dwo_unit = cu->dwo_unit;
5067   tu_group->hash.line_offset = line_offset_struct;
5068
5069   return tu_group;
5070 }
5071
5072 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5073    STMT_LIST is a DW_AT_stmt_list attribute.  */
5074
5075 static struct type_unit_group *
5076 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5077 {
5078   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5079   struct type_unit_group *tu_group;
5080   void **slot;
5081   unsigned int line_offset;
5082   struct type_unit_group type_unit_group_for_lookup;
5083
5084   if (dwarf2_per_objfile->type_unit_groups == NULL)
5085     {
5086       dwarf2_per_objfile->type_unit_groups =
5087         allocate_type_unit_groups_table ();
5088     }
5089
5090   /* Do we need to create a new group, or can we use an existing one?  */
5091
5092   if (stmt_list)
5093     {
5094       line_offset = DW_UNSND (stmt_list);
5095       ++tu_stats->nr_symtab_sharers;
5096     }
5097   else
5098     {
5099       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5100          We can do various things here like create one group per TU or
5101          spread them over multiple groups to split up the expansion work.
5102          To avoid worst case scenarios (too many groups or too large groups)
5103          we, umm, group them in bunches.  */
5104       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5105                      | (tu_stats->nr_stmt_less_type_units
5106                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5107       ++tu_stats->nr_stmt_less_type_units;
5108     }
5109
5110   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5111   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5112   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5113                          &type_unit_group_for_lookup, INSERT);
5114   if (*slot != NULL)
5115     {
5116       tu_group = *slot;
5117       gdb_assert (tu_group != NULL);
5118     }
5119   else
5120     {
5121       sect_offset line_offset_struct;
5122
5123       line_offset_struct.sect_off = line_offset;
5124       tu_group = create_type_unit_group (cu, line_offset_struct);
5125       *slot = tu_group;
5126       ++tu_stats->nr_symtabs;
5127     }
5128
5129   return tu_group;
5130 }
5131
5132 /* Struct used to sort TUs by their abbreviation table offset.  */
5133
5134 struct tu_abbrev_offset
5135 {
5136   struct signatured_type *sig_type;
5137   sect_offset abbrev_offset;
5138 };
5139
5140 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5141
5142 static int
5143 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5144 {
5145   const struct tu_abbrev_offset * const *a = ap;
5146   const struct tu_abbrev_offset * const *b = bp;
5147   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5148   unsigned int boff = (*b)->abbrev_offset.sect_off;
5149
5150   return (aoff > boff) - (aoff < boff);
5151 }
5152
5153 /* A helper function to add a type_unit_group to a table.  */
5154
5155 static int
5156 add_type_unit_group_to_table (void **slot, void *datum)
5157 {
5158   struct type_unit_group *tu_group = *slot;
5159   struct type_unit_group ***datap = datum;
5160
5161   **datap = tu_group;
5162   ++*datap;
5163
5164   return 1;
5165 }
5166
5167 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5168    each one passing FUNC,DATA.
5169
5170    The efficiency is because we sort TUs by the abbrev table they use and
5171    only read each abbrev table once.  In one program there are 200K TUs
5172    sharing 8K abbrev tables.
5173
5174    The main purpose of this function is to support building the
5175    dwarf2_per_objfile->type_unit_groups table.
5176    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5177    can collapse the search space by grouping them by stmt_list.
5178    The savings can be significant, in the same program from above the 200K TUs
5179    share 8K stmt_list tables.
5180
5181    FUNC is expected to call get_type_unit_group, which will create the
5182    struct type_unit_group if necessary and add it to
5183    dwarf2_per_objfile->type_unit_groups.  */
5184
5185 static void
5186 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5187 {
5188   struct objfile *objfile = dwarf2_per_objfile->objfile;
5189   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5190   struct cleanup *cleanups;
5191   struct abbrev_table *abbrev_table;
5192   sect_offset abbrev_offset;
5193   struct tu_abbrev_offset *sorted_by_abbrev;
5194   struct type_unit_group **iter;
5195   int i;
5196
5197   /* It's up to the caller to not call us multiple times.  */
5198   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5199
5200   if (dwarf2_per_objfile->n_type_units == 0)
5201     return;
5202
5203   /* TUs typically share abbrev tables, and there can be way more TUs than
5204      abbrev tables.  Sort by abbrev table to reduce the number of times we
5205      read each abbrev table in.
5206      Alternatives are to punt or to maintain a cache of abbrev tables.
5207      This is simpler and efficient enough for now.
5208
5209      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5210      symtab to use).  Typically TUs with the same abbrev offset have the same
5211      stmt_list value too so in practice this should work well.
5212
5213      The basic algorithm here is:
5214
5215       sort TUs by abbrev table
5216       for each TU with same abbrev table:
5217         read abbrev table if first user
5218         read TU top level DIE
5219           [IWBN if DWO skeletons had DW_AT_stmt_list]
5220         call FUNC  */
5221
5222   if (dwarf2_read_debug)
5223     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5224
5225   /* Sort in a separate table to maintain the order of all_type_units
5226      for .gdb_index: TU indices directly index all_type_units.  */
5227   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5228                               dwarf2_per_objfile->n_type_units);
5229   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5230     {
5231       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5232
5233       sorted_by_abbrev[i].sig_type = sig_type;
5234       sorted_by_abbrev[i].abbrev_offset =
5235         read_abbrev_offset (sig_type->per_cu.section,
5236                             sig_type->per_cu.offset);
5237     }
5238   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5239   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5240          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5241
5242   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5243      called any number of times, so we don't reset tu_stats here.  */
5244
5245   abbrev_offset.sect_off = ~(unsigned) 0;
5246   abbrev_table = NULL;
5247   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5248
5249   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5250     {
5251       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5252
5253       /* Switch to the next abbrev table if necessary.  */
5254       if (abbrev_table == NULL
5255           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5256         {
5257           if (abbrev_table != NULL)
5258             {
5259               abbrev_table_free (abbrev_table);
5260               /* Reset to NULL in case abbrev_table_read_table throws
5261                  an error: abbrev_table_free_cleanup will get called.  */
5262               abbrev_table = NULL;
5263             }
5264           abbrev_offset = tu->abbrev_offset;
5265           abbrev_table =
5266             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5267                                      abbrev_offset);
5268           ++tu_stats->nr_uniq_abbrev_tables;
5269         }
5270
5271       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5272                                func, data);
5273     }
5274
5275   /* Create a vector of pointers to primary type units to make it easy to
5276      iterate over them and CUs.  See dw2_get_primary_cu.  */
5277   dwarf2_per_objfile->n_type_unit_groups =
5278     htab_elements (dwarf2_per_objfile->type_unit_groups);
5279   dwarf2_per_objfile->all_type_unit_groups =
5280     obstack_alloc (&objfile->objfile_obstack,
5281                    dwarf2_per_objfile->n_type_unit_groups
5282                    * sizeof (struct type_unit_group *));
5283   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5284   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5285                           add_type_unit_group_to_table, &iter);
5286   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5287               == dwarf2_per_objfile->n_type_unit_groups);
5288
5289   do_cleanups (cleanups);
5290
5291   if (dwarf2_read_debug)
5292     {
5293       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5294       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5295                           dwarf2_per_objfile->n_type_units);
5296       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5297                           tu_stats->nr_uniq_abbrev_tables);
5298       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5299                           tu_stats->nr_symtabs);
5300       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5301                           tu_stats->nr_symtab_sharers);
5302       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5303                           tu_stats->nr_stmt_less_type_units);
5304     }
5305 }
5306 \f
5307 /* Partial symbol tables.  */
5308
5309 /* Create a psymtab named NAME and assign it to PER_CU.
5310
5311    The caller must fill in the following details:
5312    dirname, textlow, texthigh.  */
5313
5314 static struct partial_symtab *
5315 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5316 {
5317   struct objfile *objfile = per_cu->objfile;
5318   struct partial_symtab *pst;
5319
5320   pst = start_psymtab_common (objfile, objfile->section_offsets,
5321                               name, 0,
5322                               objfile->global_psymbols.next,
5323                               objfile->static_psymbols.next);
5324
5325   pst->psymtabs_addrmap_supported = 1;
5326
5327   /* This is the glue that links PST into GDB's symbol API.  */
5328   pst->read_symtab_private = per_cu;
5329   pst->read_symtab = dwarf2_read_symtab;
5330   per_cu->v.psymtab = pst;
5331
5332   return pst;
5333 }
5334
5335 /* die_reader_func for process_psymtab_comp_unit.  */
5336
5337 static void
5338 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5339                                   const gdb_byte *info_ptr,
5340                                   struct die_info *comp_unit_die,
5341                                   int has_children,
5342                                   void *data)
5343 {
5344   struct dwarf2_cu *cu = reader->cu;
5345   struct objfile *objfile = cu->objfile;
5346   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5347   struct attribute *attr;
5348   CORE_ADDR baseaddr;
5349   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5350   struct partial_symtab *pst;
5351   int has_pc_info;
5352   const char *filename;
5353   int *want_partial_unit_ptr = data;
5354
5355   if (comp_unit_die->tag == DW_TAG_partial_unit
5356       && (want_partial_unit_ptr == NULL
5357           || !*want_partial_unit_ptr))
5358     return;
5359
5360   gdb_assert (! per_cu->is_debug_types);
5361
5362   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5363
5364   cu->list_in_scope = &file_symbols;
5365
5366   /* Allocate a new partial symbol table structure.  */
5367   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5368   if (attr == NULL || !DW_STRING (attr))
5369     filename = "";
5370   else
5371     filename = DW_STRING (attr);
5372
5373   pst = create_partial_symtab (per_cu, filename);
5374
5375   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5376   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5377   if (attr != NULL)
5378     pst->dirname = DW_STRING (attr);
5379
5380   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5381
5382   dwarf2_find_base_address (comp_unit_die, cu);
5383
5384   /* Possibly set the default values of LOWPC and HIGHPC from
5385      `DW_AT_ranges'.  */
5386   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5387                                       &best_highpc, cu, pst);
5388   if (has_pc_info == 1 && best_lowpc < best_highpc)
5389     /* Store the contiguous range if it is not empty; it can be empty for
5390        CUs with no code.  */
5391     addrmap_set_empty (objfile->psymtabs_addrmap,
5392                        best_lowpc + baseaddr,
5393                        best_highpc + baseaddr - 1, pst);
5394
5395   /* Check if comp unit has_children.
5396      If so, read the rest of the partial symbols from this comp unit.
5397      If not, there's no more debug_info for this comp unit.  */
5398   if (has_children)
5399     {
5400       struct partial_die_info *first_die;
5401       CORE_ADDR lowpc, highpc;
5402
5403       lowpc = ((CORE_ADDR) -1);
5404       highpc = ((CORE_ADDR) 0);
5405
5406       first_die = load_partial_dies (reader, info_ptr, 1);
5407
5408       scan_partial_symbols (first_die, &lowpc, &highpc,
5409                             ! has_pc_info, cu);
5410
5411       /* If we didn't find a lowpc, set it to highpc to avoid
5412          complaints from `maint check'.  */
5413       if (lowpc == ((CORE_ADDR) -1))
5414         lowpc = highpc;
5415
5416       /* If the compilation unit didn't have an explicit address range,
5417          then use the information extracted from its child dies.  */
5418       if (! has_pc_info)
5419         {
5420           best_lowpc = lowpc;
5421           best_highpc = highpc;
5422         }
5423     }
5424   pst->textlow = best_lowpc + baseaddr;
5425   pst->texthigh = best_highpc + baseaddr;
5426
5427   pst->n_global_syms = objfile->global_psymbols.next -
5428     (objfile->global_psymbols.list + pst->globals_offset);
5429   pst->n_static_syms = objfile->static_psymbols.next -
5430     (objfile->static_psymbols.list + pst->statics_offset);
5431   sort_pst_symbols (objfile, pst);
5432
5433   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5434     {
5435       int i;
5436       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5437       struct dwarf2_per_cu_data *iter;
5438
5439       /* Fill in 'dependencies' here; we fill in 'users' in a
5440          post-pass.  */
5441       pst->number_of_dependencies = len;
5442       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5443                                          len * sizeof (struct symtab *));
5444       for (i = 0;
5445            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5446                         i, iter);
5447            ++i)
5448         pst->dependencies[i] = iter->v.psymtab;
5449
5450       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5451     }
5452
5453   /* Get the list of files included in the current compilation unit,
5454      and build a psymtab for each of them.  */
5455   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5456
5457   if (dwarf2_read_debug)
5458     {
5459       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5460
5461       fprintf_unfiltered (gdb_stdlog,
5462                           "Psymtab for %s unit @0x%x: %s - %s"
5463                           ", %d global, %d static syms\n",
5464                           per_cu->is_debug_types ? "type" : "comp",
5465                           per_cu->offset.sect_off,
5466                           paddress (gdbarch, pst->textlow),
5467                           paddress (gdbarch, pst->texthigh),
5468                           pst->n_global_syms, pst->n_static_syms);
5469     }
5470 }
5471
5472 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5473    Process compilation unit THIS_CU for a psymtab.  */
5474
5475 static void
5476 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5477                            int want_partial_unit)
5478 {
5479   /* If this compilation unit was already read in, free the
5480      cached copy in order to read it in again.  This is
5481      necessary because we skipped some symbols when we first
5482      read in the compilation unit (see load_partial_dies).
5483      This problem could be avoided, but the benefit is unclear.  */
5484   if (this_cu->cu != NULL)
5485     free_one_cached_comp_unit (this_cu);
5486
5487   gdb_assert (! this_cu->is_debug_types);
5488   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5489                            process_psymtab_comp_unit_reader,
5490                            &want_partial_unit);
5491
5492   /* Age out any secondary CUs.  */
5493   age_cached_comp_units ();
5494 }
5495
5496 /* Reader function for build_type_psymtabs.  */
5497
5498 static void
5499 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5500                             const gdb_byte *info_ptr,
5501                             struct die_info *type_unit_die,
5502                             int has_children,
5503                             void *data)
5504 {
5505   struct objfile *objfile = dwarf2_per_objfile->objfile;
5506   struct dwarf2_cu *cu = reader->cu;
5507   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5508   struct signatured_type *sig_type;
5509   struct type_unit_group *tu_group;
5510   struct attribute *attr;
5511   struct partial_die_info *first_die;
5512   CORE_ADDR lowpc, highpc;
5513   struct partial_symtab *pst;
5514
5515   gdb_assert (data == NULL);
5516   gdb_assert (per_cu->is_debug_types);
5517   sig_type = (struct signatured_type *) per_cu;
5518
5519   if (! has_children)
5520     return;
5521
5522   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5523   tu_group = get_type_unit_group (cu, attr);
5524
5525   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5526
5527   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5528   cu->list_in_scope = &file_symbols;
5529   pst = create_partial_symtab (per_cu, "");
5530   pst->anonymous = 1;
5531
5532   first_die = load_partial_dies (reader, info_ptr, 1);
5533
5534   lowpc = (CORE_ADDR) -1;
5535   highpc = (CORE_ADDR) 0;
5536   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5537
5538   pst->n_global_syms = objfile->global_psymbols.next -
5539     (objfile->global_psymbols.list + pst->globals_offset);
5540   pst->n_static_syms = objfile->static_psymbols.next -
5541     (objfile->static_psymbols.list + pst->statics_offset);
5542   sort_pst_symbols (objfile, pst);
5543 }
5544
5545 /* Traversal function for build_type_psymtabs.  */
5546
5547 static int
5548 build_type_psymtab_dependencies (void **slot, void *info)
5549 {
5550   struct objfile *objfile = dwarf2_per_objfile->objfile;
5551   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5552   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5553   struct partial_symtab *pst = per_cu->v.psymtab;
5554   int len = VEC_length (sig_type_ptr, tu_group->tus);
5555   struct signatured_type *iter;
5556   int i;
5557
5558   gdb_assert (len > 0);
5559   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5560
5561   pst->number_of_dependencies = len;
5562   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5563                                      len * sizeof (struct psymtab *));
5564   for (i = 0;
5565        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5566        ++i)
5567     {
5568       gdb_assert (iter->per_cu.is_debug_types);
5569       pst->dependencies[i] = iter->per_cu.v.psymtab;
5570       iter->type_unit_group = tu_group;
5571     }
5572
5573   VEC_free (sig_type_ptr, tu_group->tus);
5574
5575   return 1;
5576 }
5577
5578 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5579    Build partial symbol tables for the .debug_types comp-units.  */
5580
5581 static void
5582 build_type_psymtabs (struct objfile *objfile)
5583 {
5584   if (! create_all_type_units (objfile))
5585     return;
5586
5587   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5588
5589   /* Now that all TUs have been processed we can fill in the dependencies.  */
5590   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5591                           build_type_psymtab_dependencies, NULL);
5592 }
5593
5594 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5595
5596 static void
5597 psymtabs_addrmap_cleanup (void *o)
5598 {
5599   struct objfile *objfile = o;
5600
5601   objfile->psymtabs_addrmap = NULL;
5602 }
5603
5604 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5605
5606 static void
5607 set_partial_user (struct objfile *objfile)
5608 {
5609   int i;
5610
5611   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5612     {
5613       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5614       struct partial_symtab *pst = per_cu->v.psymtab;
5615       int j;
5616
5617       if (pst == NULL)
5618         continue;
5619
5620       for (j = 0; j < pst->number_of_dependencies; ++j)
5621         {
5622           /* Set the 'user' field only if it is not already set.  */
5623           if (pst->dependencies[j]->user == NULL)
5624             pst->dependencies[j]->user = pst;
5625         }
5626     }
5627 }
5628
5629 /* Build the partial symbol table by doing a quick pass through the
5630    .debug_info and .debug_abbrev sections.  */
5631
5632 static void
5633 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5634 {
5635   struct cleanup *back_to, *addrmap_cleanup;
5636   struct obstack temp_obstack;
5637   int i;
5638
5639   if (dwarf2_read_debug)
5640     {
5641       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5642                           objfile->name);
5643     }
5644
5645   dwarf2_per_objfile->reading_partial_symbols = 1;
5646
5647   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5648
5649   /* Any cached compilation units will be linked by the per-objfile
5650      read_in_chain.  Make sure to free them when we're done.  */
5651   back_to = make_cleanup (free_cached_comp_units, NULL);
5652
5653   build_type_psymtabs (objfile);
5654
5655   create_all_comp_units (objfile);
5656
5657   /* Create a temporary address map on a temporary obstack.  We later
5658      copy this to the final obstack.  */
5659   obstack_init (&temp_obstack);
5660   make_cleanup_obstack_free (&temp_obstack);
5661   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5662   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5663
5664   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5665     {
5666       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5667
5668       process_psymtab_comp_unit (per_cu, 0);
5669     }
5670
5671   set_partial_user (objfile);
5672
5673   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5674                                                     &objfile->objfile_obstack);
5675   discard_cleanups (addrmap_cleanup);
5676
5677   do_cleanups (back_to);
5678
5679   if (dwarf2_read_debug)
5680     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5681                         objfile->name);
5682 }
5683
5684 /* die_reader_func for load_partial_comp_unit.  */
5685
5686 static void
5687 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5688                                const gdb_byte *info_ptr,
5689                                struct die_info *comp_unit_die,
5690                                int has_children,
5691                                void *data)
5692 {
5693   struct dwarf2_cu *cu = reader->cu;
5694
5695   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5696
5697   /* Check if comp unit has_children.
5698      If so, read the rest of the partial symbols from this comp unit.
5699      If not, there's no more debug_info for this comp unit.  */
5700   if (has_children)
5701     load_partial_dies (reader, info_ptr, 0);
5702 }
5703
5704 /* Load the partial DIEs for a secondary CU into memory.
5705    This is also used when rereading a primary CU with load_all_dies.  */
5706
5707 static void
5708 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5709 {
5710   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5711                            load_partial_comp_unit_reader, NULL);
5712 }
5713
5714 static void
5715 read_comp_units_from_section (struct objfile *objfile,
5716                               struct dwarf2_section_info *section,
5717                               unsigned int is_dwz,
5718                               int *n_allocated,
5719                               int *n_comp_units,
5720                               struct dwarf2_per_cu_data ***all_comp_units)
5721 {
5722   const gdb_byte *info_ptr;
5723   bfd *abfd = section->asection->owner;
5724
5725   if (dwarf2_read_debug)
5726     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
5727                         section->asection->name, bfd_get_filename (abfd));
5728
5729   dwarf2_read_section (objfile, section);
5730
5731   info_ptr = section->buffer;
5732
5733   while (info_ptr < section->buffer + section->size)
5734     {
5735       unsigned int length, initial_length_size;
5736       struct dwarf2_per_cu_data *this_cu;
5737       sect_offset offset;
5738
5739       offset.sect_off = info_ptr - section->buffer;
5740
5741       /* Read just enough information to find out where the next
5742          compilation unit is.  */
5743       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5744
5745       /* Save the compilation unit for later lookup.  */
5746       this_cu = obstack_alloc (&objfile->objfile_obstack,
5747                                sizeof (struct dwarf2_per_cu_data));
5748       memset (this_cu, 0, sizeof (*this_cu));
5749       this_cu->offset = offset;
5750       this_cu->length = length + initial_length_size;
5751       this_cu->is_dwz = is_dwz;
5752       this_cu->objfile = objfile;
5753       this_cu->section = section;
5754
5755       if (*n_comp_units == *n_allocated)
5756         {
5757           *n_allocated *= 2;
5758           *all_comp_units = xrealloc (*all_comp_units,
5759                                       *n_allocated
5760                                       * sizeof (struct dwarf2_per_cu_data *));
5761         }
5762       (*all_comp_units)[*n_comp_units] = this_cu;
5763       ++*n_comp_units;
5764
5765       info_ptr = info_ptr + this_cu->length;
5766     }
5767 }
5768
5769 /* Create a list of all compilation units in OBJFILE.
5770    This is only done for -readnow and building partial symtabs.  */
5771
5772 static void
5773 create_all_comp_units (struct objfile *objfile)
5774 {
5775   int n_allocated;
5776   int n_comp_units;
5777   struct dwarf2_per_cu_data **all_comp_units;
5778
5779   n_comp_units = 0;
5780   n_allocated = 10;
5781   all_comp_units = xmalloc (n_allocated
5782                             * sizeof (struct dwarf2_per_cu_data *));
5783
5784   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5785                                 &n_allocated, &n_comp_units, &all_comp_units);
5786
5787   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5788     {
5789       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5790
5791       read_comp_units_from_section (objfile, &dwz->info, 1,
5792                                     &n_allocated, &n_comp_units,
5793                                     &all_comp_units);
5794     }
5795
5796   dwarf2_per_objfile->all_comp_units
5797     = obstack_alloc (&objfile->objfile_obstack,
5798                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5799   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5800           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5801   xfree (all_comp_units);
5802   dwarf2_per_objfile->n_comp_units = n_comp_units;
5803 }
5804
5805 /* Process all loaded DIEs for compilation unit CU, starting at
5806    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5807    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5808    DW_AT_ranges).  If NEED_PC is set, then this function will set
5809    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5810    and record the covered ranges in the addrmap.  */
5811
5812 static void
5813 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5814                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5815 {
5816   struct partial_die_info *pdi;
5817
5818   /* Now, march along the PDI's, descending into ones which have
5819      interesting children but skipping the children of the other ones,
5820      until we reach the end of the compilation unit.  */
5821
5822   pdi = first_die;
5823
5824   while (pdi != NULL)
5825     {
5826       fixup_partial_die (pdi, cu);
5827
5828       /* Anonymous namespaces or modules have no name but have interesting
5829          children, so we need to look at them.  Ditto for anonymous
5830          enums.  */
5831
5832       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5833           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5834           || pdi->tag == DW_TAG_imported_unit)
5835         {
5836           switch (pdi->tag)
5837             {
5838             case DW_TAG_subprogram:
5839               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5840               break;
5841             case DW_TAG_constant:
5842             case DW_TAG_variable:
5843             case DW_TAG_typedef:
5844             case DW_TAG_union_type:
5845               if (!pdi->is_declaration)
5846                 {
5847                   add_partial_symbol (pdi, cu);
5848                 }
5849               break;
5850             case DW_TAG_class_type:
5851             case DW_TAG_interface_type:
5852             case DW_TAG_structure_type:
5853               if (!pdi->is_declaration)
5854                 {
5855                   add_partial_symbol (pdi, cu);
5856                 }
5857               break;
5858             case DW_TAG_enumeration_type:
5859               if (!pdi->is_declaration)
5860                 add_partial_enumeration (pdi, cu);
5861               break;
5862             case DW_TAG_base_type:
5863             case DW_TAG_subrange_type:
5864               /* File scope base type definitions are added to the partial
5865                  symbol table.  */
5866               add_partial_symbol (pdi, cu);
5867               break;
5868             case DW_TAG_namespace:
5869               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5870               break;
5871             case DW_TAG_module:
5872               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5873               break;
5874             case DW_TAG_imported_unit:
5875               {
5876                 struct dwarf2_per_cu_data *per_cu;
5877
5878                 /* For now we don't handle imported units in type units.  */
5879                 if (cu->per_cu->is_debug_types)
5880                   {
5881                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5882                              " supported in type units [in module %s]"),
5883                            cu->objfile->name);
5884                   }
5885
5886                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5887                                                            pdi->is_dwz,
5888                                                            cu->objfile);
5889
5890                 /* Go read the partial unit, if needed.  */
5891                 if (per_cu->v.psymtab == NULL)
5892                   process_psymtab_comp_unit (per_cu, 1);
5893
5894                 VEC_safe_push (dwarf2_per_cu_ptr,
5895                                cu->per_cu->imported_symtabs, per_cu);
5896               }
5897               break;
5898             default:
5899               break;
5900             }
5901         }
5902
5903       /* If the die has a sibling, skip to the sibling.  */
5904
5905       pdi = pdi->die_sibling;
5906     }
5907 }
5908
5909 /* Functions used to compute the fully scoped name of a partial DIE.
5910
5911    Normally, this is simple.  For C++, the parent DIE's fully scoped
5912    name is concatenated with "::" and the partial DIE's name.  For
5913    Java, the same thing occurs except that "." is used instead of "::".
5914    Enumerators are an exception; they use the scope of their parent
5915    enumeration type, i.e. the name of the enumeration type is not
5916    prepended to the enumerator.
5917
5918    There are two complexities.  One is DW_AT_specification; in this
5919    case "parent" means the parent of the target of the specification,
5920    instead of the direct parent of the DIE.  The other is compilers
5921    which do not emit DW_TAG_namespace; in this case we try to guess
5922    the fully qualified name of structure types from their members'
5923    linkage names.  This must be done using the DIE's children rather
5924    than the children of any DW_AT_specification target.  We only need
5925    to do this for structures at the top level, i.e. if the target of
5926    any DW_AT_specification (if any; otherwise the DIE itself) does not
5927    have a parent.  */
5928
5929 /* Compute the scope prefix associated with PDI's parent, in
5930    compilation unit CU.  The result will be allocated on CU's
5931    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5932    field.  NULL is returned if no prefix is necessary.  */
5933 static const char *
5934 partial_die_parent_scope (struct partial_die_info *pdi,
5935                           struct dwarf2_cu *cu)
5936 {
5937   const char *grandparent_scope;
5938   struct partial_die_info *parent, *real_pdi;
5939
5940   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5941      then this means the parent of the specification DIE.  */
5942
5943   real_pdi = pdi;
5944   while (real_pdi->has_specification)
5945     real_pdi = find_partial_die (real_pdi->spec_offset,
5946                                  real_pdi->spec_is_dwz, cu);
5947
5948   parent = real_pdi->die_parent;
5949   if (parent == NULL)
5950     return NULL;
5951
5952   if (parent->scope_set)
5953     return parent->scope;
5954
5955   fixup_partial_die (parent, cu);
5956
5957   grandparent_scope = partial_die_parent_scope (parent, cu);
5958
5959   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5960      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5961      Work around this problem here.  */
5962   if (cu->language == language_cplus
5963       && parent->tag == DW_TAG_namespace
5964       && strcmp (parent->name, "::") == 0
5965       && grandparent_scope == NULL)
5966     {
5967       parent->scope = NULL;
5968       parent->scope_set = 1;
5969       return NULL;
5970     }
5971
5972   if (pdi->tag == DW_TAG_enumerator)
5973     /* Enumerators should not get the name of the enumeration as a prefix.  */
5974     parent->scope = grandparent_scope;
5975   else if (parent->tag == DW_TAG_namespace
5976       || parent->tag == DW_TAG_module
5977       || parent->tag == DW_TAG_structure_type
5978       || parent->tag == DW_TAG_class_type
5979       || parent->tag == DW_TAG_interface_type
5980       || parent->tag == DW_TAG_union_type
5981       || parent->tag == DW_TAG_enumeration_type)
5982     {
5983       if (grandparent_scope == NULL)
5984         parent->scope = parent->name;
5985       else
5986         parent->scope = typename_concat (&cu->comp_unit_obstack,
5987                                          grandparent_scope,
5988                                          parent->name, 0, cu);
5989     }
5990   else
5991     {
5992       /* FIXME drow/2004-04-01: What should we be doing with
5993          function-local names?  For partial symbols, we should probably be
5994          ignoring them.  */
5995       complaint (&symfile_complaints,
5996                  _("unhandled containing DIE tag %d for DIE at %d"),
5997                  parent->tag, pdi->offset.sect_off);
5998       parent->scope = grandparent_scope;
5999     }
6000
6001   parent->scope_set = 1;
6002   return parent->scope;
6003 }
6004
6005 /* Return the fully scoped name associated with PDI, from compilation unit
6006    CU.  The result will be allocated with malloc.  */
6007
6008 static char *
6009 partial_die_full_name (struct partial_die_info *pdi,
6010                        struct dwarf2_cu *cu)
6011 {
6012   const char *parent_scope;
6013
6014   /* If this is a template instantiation, we can not work out the
6015      template arguments from partial DIEs.  So, unfortunately, we have
6016      to go through the full DIEs.  At least any work we do building
6017      types here will be reused if full symbols are loaded later.  */
6018   if (pdi->has_template_arguments)
6019     {
6020       fixup_partial_die (pdi, cu);
6021
6022       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6023         {
6024           struct die_info *die;
6025           struct attribute attr;
6026           struct dwarf2_cu *ref_cu = cu;
6027
6028           /* DW_FORM_ref_addr is using section offset.  */
6029           attr.name = 0;
6030           attr.form = DW_FORM_ref_addr;
6031           attr.u.unsnd = pdi->offset.sect_off;
6032           die = follow_die_ref (NULL, &attr, &ref_cu);
6033
6034           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6035         }
6036     }
6037
6038   parent_scope = partial_die_parent_scope (pdi, cu);
6039   if (parent_scope == NULL)
6040     return NULL;
6041   else
6042     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6043 }
6044
6045 static void
6046 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6047 {
6048   struct objfile *objfile = cu->objfile;
6049   CORE_ADDR addr = 0;
6050   const char *actual_name = NULL;
6051   CORE_ADDR baseaddr;
6052   char *built_actual_name;
6053
6054   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6055
6056   built_actual_name = partial_die_full_name (pdi, cu);
6057   if (built_actual_name != NULL)
6058     actual_name = built_actual_name;
6059
6060   if (actual_name == NULL)
6061     actual_name = pdi->name;
6062
6063   switch (pdi->tag)
6064     {
6065     case DW_TAG_subprogram:
6066       if (pdi->is_external || cu->language == language_ada)
6067         {
6068           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6069              of the global scope.  But in Ada, we want to be able to access
6070              nested procedures globally.  So all Ada subprograms are stored
6071              in the global scope.  */
6072           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6073              mst_text, objfile); */
6074           add_psymbol_to_list (actual_name, strlen (actual_name),
6075                                built_actual_name != NULL,
6076                                VAR_DOMAIN, LOC_BLOCK,
6077                                &objfile->global_psymbols,
6078                                0, pdi->lowpc + baseaddr,
6079                                cu->language, objfile);
6080         }
6081       else
6082         {
6083           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6084              mst_file_text, objfile); */
6085           add_psymbol_to_list (actual_name, strlen (actual_name),
6086                                built_actual_name != NULL,
6087                                VAR_DOMAIN, LOC_BLOCK,
6088                                &objfile->static_psymbols,
6089                                0, pdi->lowpc + baseaddr,
6090                                cu->language, objfile);
6091         }
6092       break;
6093     case DW_TAG_constant:
6094       {
6095         struct psymbol_allocation_list *list;
6096
6097         if (pdi->is_external)
6098           list = &objfile->global_psymbols;
6099         else
6100           list = &objfile->static_psymbols;
6101         add_psymbol_to_list (actual_name, strlen (actual_name),
6102                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6103                              list, 0, 0, cu->language, objfile);
6104       }
6105       break;
6106     case DW_TAG_variable:
6107       if (pdi->d.locdesc)
6108         addr = decode_locdesc (pdi->d.locdesc, cu);
6109
6110       if (pdi->d.locdesc
6111           && addr == 0
6112           && !dwarf2_per_objfile->has_section_at_zero)
6113         {
6114           /* A global or static variable may also have been stripped
6115              out by the linker if unused, in which case its address
6116              will be nullified; do not add such variables into partial
6117              symbol table then.  */
6118         }
6119       else if (pdi->is_external)
6120         {
6121           /* Global Variable.
6122              Don't enter into the minimal symbol tables as there is
6123              a minimal symbol table entry from the ELF symbols already.
6124              Enter into partial symbol table if it has a location
6125              descriptor or a type.
6126              If the location descriptor is missing, new_symbol will create
6127              a LOC_UNRESOLVED symbol, the address of the variable will then
6128              be determined from the minimal symbol table whenever the variable
6129              is referenced.
6130              The address for the partial symbol table entry is not
6131              used by GDB, but it comes in handy for debugging partial symbol
6132              table building.  */
6133
6134           if (pdi->d.locdesc || pdi->has_type)
6135             add_psymbol_to_list (actual_name, strlen (actual_name),
6136                                  built_actual_name != NULL,
6137                                  VAR_DOMAIN, LOC_STATIC,
6138                                  &objfile->global_psymbols,
6139                                  0, addr + baseaddr,
6140                                  cu->language, objfile);
6141         }
6142       else
6143         {
6144           /* Static Variable.  Skip symbols without location descriptors.  */
6145           if (pdi->d.locdesc == NULL)
6146             {
6147               xfree (built_actual_name);
6148               return;
6149             }
6150           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6151              mst_file_data, objfile); */
6152           add_psymbol_to_list (actual_name, strlen (actual_name),
6153                                built_actual_name != NULL,
6154                                VAR_DOMAIN, LOC_STATIC,
6155                                &objfile->static_psymbols,
6156                                0, addr + baseaddr,
6157                                cu->language, objfile);
6158         }
6159       break;
6160     case DW_TAG_typedef:
6161     case DW_TAG_base_type:
6162     case DW_TAG_subrange_type:
6163       add_psymbol_to_list (actual_name, strlen (actual_name),
6164                            built_actual_name != NULL,
6165                            VAR_DOMAIN, LOC_TYPEDEF,
6166                            &objfile->static_psymbols,
6167                            0, (CORE_ADDR) 0, cu->language, objfile);
6168       break;
6169     case DW_TAG_namespace:
6170       add_psymbol_to_list (actual_name, strlen (actual_name),
6171                            built_actual_name != NULL,
6172                            VAR_DOMAIN, LOC_TYPEDEF,
6173                            &objfile->global_psymbols,
6174                            0, (CORE_ADDR) 0, cu->language, objfile);
6175       break;
6176     case DW_TAG_class_type:
6177     case DW_TAG_interface_type:
6178     case DW_TAG_structure_type:
6179     case DW_TAG_union_type:
6180     case DW_TAG_enumeration_type:
6181       /* Skip external references.  The DWARF standard says in the section
6182          about "Structure, Union, and Class Type Entries": "An incomplete
6183          structure, union or class type is represented by a structure,
6184          union or class entry that does not have a byte size attribute
6185          and that has a DW_AT_declaration attribute."  */
6186       if (!pdi->has_byte_size && pdi->is_declaration)
6187         {
6188           xfree (built_actual_name);
6189           return;
6190         }
6191
6192       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6193          static vs. global.  */
6194       add_psymbol_to_list (actual_name, strlen (actual_name),
6195                            built_actual_name != NULL,
6196                            STRUCT_DOMAIN, LOC_TYPEDEF,
6197                            (cu->language == language_cplus
6198                             || cu->language == language_java)
6199                            ? &objfile->global_psymbols
6200                            : &objfile->static_psymbols,
6201                            0, (CORE_ADDR) 0, cu->language, objfile);
6202
6203       break;
6204     case DW_TAG_enumerator:
6205       add_psymbol_to_list (actual_name, strlen (actual_name),
6206                            built_actual_name != NULL,
6207                            VAR_DOMAIN, LOC_CONST,
6208                            (cu->language == language_cplus
6209                             || cu->language == language_java)
6210                            ? &objfile->global_psymbols
6211                            : &objfile->static_psymbols,
6212                            0, (CORE_ADDR) 0, cu->language, objfile);
6213       break;
6214     default:
6215       break;
6216     }
6217
6218   xfree (built_actual_name);
6219 }
6220
6221 /* Read a partial die corresponding to a namespace; also, add a symbol
6222    corresponding to that namespace to the symbol table.  NAMESPACE is
6223    the name of the enclosing namespace.  */
6224
6225 static void
6226 add_partial_namespace (struct partial_die_info *pdi,
6227                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6228                        int need_pc, struct dwarf2_cu *cu)
6229 {
6230   /* Add a symbol for the namespace.  */
6231
6232   add_partial_symbol (pdi, cu);
6233
6234   /* Now scan partial symbols in that namespace.  */
6235
6236   if (pdi->has_children)
6237     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6238 }
6239
6240 /* Read a partial die corresponding to a Fortran module.  */
6241
6242 static void
6243 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6244                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6245 {
6246   /* Now scan partial symbols in that module.  */
6247
6248   if (pdi->has_children)
6249     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6250 }
6251
6252 /* Read a partial die corresponding to a subprogram and create a partial
6253    symbol for that subprogram.  When the CU language allows it, this
6254    routine also defines a partial symbol for each nested subprogram
6255    that this subprogram contains.
6256
6257    DIE my also be a lexical block, in which case we simply search
6258    recursively for suprograms defined inside that lexical block.
6259    Again, this is only performed when the CU language allows this
6260    type of definitions.  */
6261
6262 static void
6263 add_partial_subprogram (struct partial_die_info *pdi,
6264                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6265                         int need_pc, struct dwarf2_cu *cu)
6266 {
6267   if (pdi->tag == DW_TAG_subprogram)
6268     {
6269       if (pdi->has_pc_info)
6270         {
6271           if (pdi->lowpc < *lowpc)
6272             *lowpc = pdi->lowpc;
6273           if (pdi->highpc > *highpc)
6274             *highpc = pdi->highpc;
6275           if (need_pc)
6276             {
6277               CORE_ADDR baseaddr;
6278               struct objfile *objfile = cu->objfile;
6279
6280               baseaddr = ANOFFSET (objfile->section_offsets,
6281                                    SECT_OFF_TEXT (objfile));
6282               addrmap_set_empty (objfile->psymtabs_addrmap,
6283                                  pdi->lowpc + baseaddr,
6284                                  pdi->highpc - 1 + baseaddr,
6285                                  cu->per_cu->v.psymtab);
6286             }
6287         }
6288
6289       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6290         {
6291           if (!pdi->is_declaration)
6292             /* Ignore subprogram DIEs that do not have a name, they are
6293                illegal.  Do not emit a complaint at this point, we will
6294                do so when we convert this psymtab into a symtab.  */
6295             if (pdi->name)
6296               add_partial_symbol (pdi, cu);
6297         }
6298     }
6299
6300   if (! pdi->has_children)
6301     return;
6302
6303   if (cu->language == language_ada)
6304     {
6305       pdi = pdi->die_child;
6306       while (pdi != NULL)
6307         {
6308           fixup_partial_die (pdi, cu);
6309           if (pdi->tag == DW_TAG_subprogram
6310               || pdi->tag == DW_TAG_lexical_block)
6311             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6312           pdi = pdi->die_sibling;
6313         }
6314     }
6315 }
6316
6317 /* Read a partial die corresponding to an enumeration type.  */
6318
6319 static void
6320 add_partial_enumeration (struct partial_die_info *enum_pdi,
6321                          struct dwarf2_cu *cu)
6322 {
6323   struct partial_die_info *pdi;
6324
6325   if (enum_pdi->name != NULL)
6326     add_partial_symbol (enum_pdi, cu);
6327
6328   pdi = enum_pdi->die_child;
6329   while (pdi)
6330     {
6331       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6332         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6333       else
6334         add_partial_symbol (pdi, cu);
6335       pdi = pdi->die_sibling;
6336     }
6337 }
6338
6339 /* Return the initial uleb128 in the die at INFO_PTR.  */
6340
6341 static unsigned int
6342 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6343 {
6344   unsigned int bytes_read;
6345
6346   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6347 }
6348
6349 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6350    Return the corresponding abbrev, or NULL if the number is zero (indicating
6351    an empty DIE).  In either case *BYTES_READ will be set to the length of
6352    the initial number.  */
6353
6354 static struct abbrev_info *
6355 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6356                  struct dwarf2_cu *cu)
6357 {
6358   bfd *abfd = cu->objfile->obfd;
6359   unsigned int abbrev_number;
6360   struct abbrev_info *abbrev;
6361
6362   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6363
6364   if (abbrev_number == 0)
6365     return NULL;
6366
6367   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6368   if (!abbrev)
6369     {
6370       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6371              abbrev_number, bfd_get_filename (abfd));
6372     }
6373
6374   return abbrev;
6375 }
6376
6377 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6378    Returns a pointer to the end of a series of DIEs, terminated by an empty
6379    DIE.  Any children of the skipped DIEs will also be skipped.  */
6380
6381 static const gdb_byte *
6382 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6383 {
6384   struct dwarf2_cu *cu = reader->cu;
6385   struct abbrev_info *abbrev;
6386   unsigned int bytes_read;
6387
6388   while (1)
6389     {
6390       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6391       if (abbrev == NULL)
6392         return info_ptr + bytes_read;
6393       else
6394         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6395     }
6396 }
6397
6398 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6399    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6400    abbrev corresponding to that skipped uleb128 should be passed in
6401    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6402    children.  */
6403
6404 static const gdb_byte *
6405 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6406               struct abbrev_info *abbrev)
6407 {
6408   unsigned int bytes_read;
6409   struct attribute attr;
6410   bfd *abfd = reader->abfd;
6411   struct dwarf2_cu *cu = reader->cu;
6412   const gdb_byte *buffer = reader->buffer;
6413   const gdb_byte *buffer_end = reader->buffer_end;
6414   const gdb_byte *start_info_ptr = info_ptr;
6415   unsigned int form, i;
6416
6417   for (i = 0; i < abbrev->num_attrs; i++)
6418     {
6419       /* The only abbrev we care about is DW_AT_sibling.  */
6420       if (abbrev->attrs[i].name == DW_AT_sibling)
6421         {
6422           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6423           if (attr.form == DW_FORM_ref_addr)
6424             complaint (&symfile_complaints,
6425                        _("ignoring absolute DW_AT_sibling"));
6426           else
6427             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6428         }
6429
6430       /* If it isn't DW_AT_sibling, skip this attribute.  */
6431       form = abbrev->attrs[i].form;
6432     skip_attribute:
6433       switch (form)
6434         {
6435         case DW_FORM_ref_addr:
6436           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6437              and later it is offset sized.  */
6438           if (cu->header.version == 2)
6439             info_ptr += cu->header.addr_size;
6440           else
6441             info_ptr += cu->header.offset_size;
6442           break;
6443         case DW_FORM_GNU_ref_alt:
6444           info_ptr += cu->header.offset_size;
6445           break;
6446         case DW_FORM_addr:
6447           info_ptr += cu->header.addr_size;
6448           break;
6449         case DW_FORM_data1:
6450         case DW_FORM_ref1:
6451         case DW_FORM_flag:
6452           info_ptr += 1;
6453           break;
6454         case DW_FORM_flag_present:
6455           break;
6456         case DW_FORM_data2:
6457         case DW_FORM_ref2:
6458           info_ptr += 2;
6459           break;
6460         case DW_FORM_data4:
6461         case DW_FORM_ref4:
6462           info_ptr += 4;
6463           break;
6464         case DW_FORM_data8:
6465         case DW_FORM_ref8:
6466         case DW_FORM_ref_sig8:
6467           info_ptr += 8;
6468           break;
6469         case DW_FORM_string:
6470           read_direct_string (abfd, info_ptr, &bytes_read);
6471           info_ptr += bytes_read;
6472           break;
6473         case DW_FORM_sec_offset:
6474         case DW_FORM_strp:
6475         case DW_FORM_GNU_strp_alt:
6476           info_ptr += cu->header.offset_size;
6477           break;
6478         case DW_FORM_exprloc:
6479         case DW_FORM_block:
6480           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6481           info_ptr += bytes_read;
6482           break;
6483         case DW_FORM_block1:
6484           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6485           break;
6486         case DW_FORM_block2:
6487           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6488           break;
6489         case DW_FORM_block4:
6490           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6491           break;
6492         case DW_FORM_sdata:
6493         case DW_FORM_udata:
6494         case DW_FORM_ref_udata:
6495         case DW_FORM_GNU_addr_index:
6496         case DW_FORM_GNU_str_index:
6497           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6498           break;
6499         case DW_FORM_indirect:
6500           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6501           info_ptr += bytes_read;
6502           /* We need to continue parsing from here, so just go back to
6503              the top.  */
6504           goto skip_attribute;
6505
6506         default:
6507           error (_("Dwarf Error: Cannot handle %s "
6508                    "in DWARF reader [in module %s]"),
6509                  dwarf_form_name (form),
6510                  bfd_get_filename (abfd));
6511         }
6512     }
6513
6514   if (abbrev->has_children)
6515     return skip_children (reader, info_ptr);
6516   else
6517     return info_ptr;
6518 }
6519
6520 /* Locate ORIG_PDI's sibling.
6521    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6522
6523 static const gdb_byte *
6524 locate_pdi_sibling (const struct die_reader_specs *reader,
6525                     struct partial_die_info *orig_pdi,
6526                     const gdb_byte *info_ptr)
6527 {
6528   /* Do we know the sibling already?  */
6529
6530   if (orig_pdi->sibling)
6531     return orig_pdi->sibling;
6532
6533   /* Are there any children to deal with?  */
6534
6535   if (!orig_pdi->has_children)
6536     return info_ptr;
6537
6538   /* Skip the children the long way.  */
6539
6540   return skip_children (reader, info_ptr);
6541 }
6542
6543 /* Expand this partial symbol table into a full symbol table.  SELF is
6544    not NULL.  */
6545
6546 static void
6547 dwarf2_read_symtab (struct partial_symtab *self,
6548                     struct objfile *objfile)
6549 {
6550   if (self->readin)
6551     {
6552       warning (_("bug: psymtab for %s is already read in."),
6553                self->filename);
6554     }
6555   else
6556     {
6557       if (info_verbose)
6558         {
6559           printf_filtered (_("Reading in symbols for %s..."),
6560                            self->filename);
6561           gdb_flush (gdb_stdout);
6562         }
6563
6564       /* Restore our global data.  */
6565       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6566
6567       /* If this psymtab is constructed from a debug-only objfile, the
6568          has_section_at_zero flag will not necessarily be correct.  We
6569          can get the correct value for this flag by looking at the data
6570          associated with the (presumably stripped) associated objfile.  */
6571       if (objfile->separate_debug_objfile_backlink)
6572         {
6573           struct dwarf2_per_objfile *dpo_backlink
6574             = objfile_data (objfile->separate_debug_objfile_backlink,
6575                             dwarf2_objfile_data_key);
6576
6577           dwarf2_per_objfile->has_section_at_zero
6578             = dpo_backlink->has_section_at_zero;
6579         }
6580
6581       dwarf2_per_objfile->reading_partial_symbols = 0;
6582
6583       psymtab_to_symtab_1 (self);
6584
6585       /* Finish up the debug error message.  */
6586       if (info_verbose)
6587         printf_filtered (_("done.\n"));
6588     }
6589
6590   process_cu_includes ();
6591 }
6592 \f
6593 /* Reading in full CUs.  */
6594
6595 /* Add PER_CU to the queue.  */
6596
6597 static void
6598 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6599                  enum language pretend_language)
6600 {
6601   struct dwarf2_queue_item *item;
6602
6603   per_cu->queued = 1;
6604   item = xmalloc (sizeof (*item));
6605   item->per_cu = per_cu;
6606   item->pretend_language = pretend_language;
6607   item->next = NULL;
6608
6609   if (dwarf2_queue == NULL)
6610     dwarf2_queue = item;
6611   else
6612     dwarf2_queue_tail->next = item;
6613
6614   dwarf2_queue_tail = item;
6615 }
6616
6617 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6618    unit and add it to our queue.
6619    The result is non-zero if PER_CU was queued, otherwise the result is zero
6620    meaning either PER_CU is already queued or it is already loaded.  */
6621
6622 static int
6623 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6624                        struct dwarf2_per_cu_data *per_cu,
6625                        enum language pretend_language)
6626 {
6627   /* We may arrive here during partial symbol reading, if we need full
6628      DIEs to process an unusual case (e.g. template arguments).  Do
6629      not queue PER_CU, just tell our caller to load its DIEs.  */
6630   if (dwarf2_per_objfile->reading_partial_symbols)
6631     {
6632       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6633         return 1;
6634       return 0;
6635     }
6636
6637   /* Mark the dependence relation so that we don't flush PER_CU
6638      too early.  */
6639   dwarf2_add_dependence (this_cu, per_cu);
6640
6641   /* If it's already on the queue, we have nothing to do.  */
6642   if (per_cu->queued)
6643     return 0;
6644
6645   /* If the compilation unit is already loaded, just mark it as
6646      used.  */
6647   if (per_cu->cu != NULL)
6648     {
6649       per_cu->cu->last_used = 0;
6650       return 0;
6651     }
6652
6653   /* Add it to the queue.  */
6654   queue_comp_unit (per_cu, pretend_language);
6655
6656   return 1;
6657 }
6658
6659 /* Process the queue.  */
6660
6661 static void
6662 process_queue (void)
6663 {
6664   struct dwarf2_queue_item *item, *next_item;
6665
6666   if (dwarf2_read_debug)
6667     {
6668       fprintf_unfiltered (gdb_stdlog,
6669                           "Expanding one or more symtabs of objfile %s ...\n",
6670                           dwarf2_per_objfile->objfile->name);
6671     }
6672
6673   /* The queue starts out with one item, but following a DIE reference
6674      may load a new CU, adding it to the end of the queue.  */
6675   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6676     {
6677       if (dwarf2_per_objfile->using_index
6678           ? !item->per_cu->v.quick->symtab
6679           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6680         {
6681           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6682
6683           if (dwarf2_read_debug)
6684             {
6685               fprintf_unfiltered (gdb_stdlog,
6686                                   "Expanding symtab of %s at offset 0x%x\n",
6687                                   per_cu->is_debug_types ? "TU" : "CU",
6688                                   per_cu->offset.sect_off);
6689             }
6690
6691           if (per_cu->is_debug_types)
6692             process_full_type_unit (per_cu, item->pretend_language);
6693           else
6694             process_full_comp_unit (per_cu, item->pretend_language);
6695
6696           if (dwarf2_read_debug)
6697             {
6698               fprintf_unfiltered (gdb_stdlog,
6699                                   "Done expanding %s at offset 0x%x\n",
6700                                   per_cu->is_debug_types ? "TU" : "CU",
6701                                   per_cu->offset.sect_off);
6702             }
6703         }
6704
6705       item->per_cu->queued = 0;
6706       next_item = item->next;
6707       xfree (item);
6708     }
6709
6710   dwarf2_queue_tail = NULL;
6711
6712   if (dwarf2_read_debug)
6713     {
6714       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6715                           dwarf2_per_objfile->objfile->name);
6716     }
6717 }
6718
6719 /* Free all allocated queue entries.  This function only releases anything if
6720    an error was thrown; if the queue was processed then it would have been
6721    freed as we went along.  */
6722
6723 static void
6724 dwarf2_release_queue (void *dummy)
6725 {
6726   struct dwarf2_queue_item *item, *last;
6727
6728   item = dwarf2_queue;
6729   while (item)
6730     {
6731       /* Anything still marked queued is likely to be in an
6732          inconsistent state, so discard it.  */
6733       if (item->per_cu->queued)
6734         {
6735           if (item->per_cu->cu != NULL)
6736             free_one_cached_comp_unit (item->per_cu);
6737           item->per_cu->queued = 0;
6738         }
6739
6740       last = item;
6741       item = item->next;
6742       xfree (last);
6743     }
6744
6745   dwarf2_queue = dwarf2_queue_tail = NULL;
6746 }
6747
6748 /* Read in full symbols for PST, and anything it depends on.  */
6749
6750 static void
6751 psymtab_to_symtab_1 (struct partial_symtab *pst)
6752 {
6753   struct dwarf2_per_cu_data *per_cu;
6754   int i;
6755
6756   if (pst->readin)
6757     return;
6758
6759   for (i = 0; i < pst->number_of_dependencies; i++)
6760     if (!pst->dependencies[i]->readin
6761         && pst->dependencies[i]->user == NULL)
6762       {
6763         /* Inform about additional files that need to be read in.  */
6764         if (info_verbose)
6765           {
6766             /* FIXME: i18n: Need to make this a single string.  */
6767             fputs_filtered (" ", gdb_stdout);
6768             wrap_here ("");
6769             fputs_filtered ("and ", gdb_stdout);
6770             wrap_here ("");
6771             printf_filtered ("%s...", pst->dependencies[i]->filename);
6772             wrap_here ("");     /* Flush output.  */
6773             gdb_flush (gdb_stdout);
6774           }
6775         psymtab_to_symtab_1 (pst->dependencies[i]);
6776       }
6777
6778   per_cu = pst->read_symtab_private;
6779
6780   if (per_cu == NULL)
6781     {
6782       /* It's an include file, no symbols to read for it.
6783          Everything is in the parent symtab.  */
6784       pst->readin = 1;
6785       return;
6786     }
6787
6788   dw2_do_instantiate_symtab (per_cu);
6789 }
6790
6791 /* Trivial hash function for die_info: the hash value of a DIE
6792    is its offset in .debug_info for this objfile.  */
6793
6794 static hashval_t
6795 die_hash (const void *item)
6796 {
6797   const struct die_info *die = item;
6798
6799   return die->offset.sect_off;
6800 }
6801
6802 /* Trivial comparison function for die_info structures: two DIEs
6803    are equal if they have the same offset.  */
6804
6805 static int
6806 die_eq (const void *item_lhs, const void *item_rhs)
6807 {
6808   const struct die_info *die_lhs = item_lhs;
6809   const struct die_info *die_rhs = item_rhs;
6810
6811   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6812 }
6813
6814 /* die_reader_func for load_full_comp_unit.
6815    This is identical to read_signatured_type_reader,
6816    but is kept separate for now.  */
6817
6818 static void
6819 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6820                             const gdb_byte *info_ptr,
6821                             struct die_info *comp_unit_die,
6822                             int has_children,
6823                             void *data)
6824 {
6825   struct dwarf2_cu *cu = reader->cu;
6826   enum language *language_ptr = data;
6827
6828   gdb_assert (cu->die_hash == NULL);
6829   cu->die_hash =
6830     htab_create_alloc_ex (cu->header.length / 12,
6831                           die_hash,
6832                           die_eq,
6833                           NULL,
6834                           &cu->comp_unit_obstack,
6835                           hashtab_obstack_allocate,
6836                           dummy_obstack_deallocate);
6837
6838   if (has_children)
6839     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6840                                                   &info_ptr, comp_unit_die);
6841   cu->dies = comp_unit_die;
6842   /* comp_unit_die is not stored in die_hash, no need.  */
6843
6844   /* We try not to read any attributes in this function, because not
6845      all CUs needed for references have been loaded yet, and symbol
6846      table processing isn't initialized.  But we have to set the CU language,
6847      or we won't be able to build types correctly.
6848      Similarly, if we do not read the producer, we can not apply
6849      producer-specific interpretation.  */
6850   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6851 }
6852
6853 /* Load the DIEs associated with PER_CU into memory.  */
6854
6855 static void
6856 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6857                      enum language pretend_language)
6858 {
6859   gdb_assert (! this_cu->is_debug_types);
6860
6861   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6862                            load_full_comp_unit_reader, &pretend_language);
6863 }
6864
6865 /* Add a DIE to the delayed physname list.  */
6866
6867 static void
6868 add_to_method_list (struct type *type, int fnfield_index, int index,
6869                     const char *name, struct die_info *die,
6870                     struct dwarf2_cu *cu)
6871 {
6872   struct delayed_method_info mi;
6873   mi.type = type;
6874   mi.fnfield_index = fnfield_index;
6875   mi.index = index;
6876   mi.name = name;
6877   mi.die = die;
6878   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6879 }
6880
6881 /* A cleanup for freeing the delayed method list.  */
6882
6883 static void
6884 free_delayed_list (void *ptr)
6885 {
6886   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6887   if (cu->method_list != NULL)
6888     {
6889       VEC_free (delayed_method_info, cu->method_list);
6890       cu->method_list = NULL;
6891     }
6892 }
6893
6894 /* Compute the physnames of any methods on the CU's method list.
6895
6896    The computation of method physnames is delayed in order to avoid the
6897    (bad) condition that one of the method's formal parameters is of an as yet
6898    incomplete type.  */
6899
6900 static void
6901 compute_delayed_physnames (struct dwarf2_cu *cu)
6902 {
6903   int i;
6904   struct delayed_method_info *mi;
6905   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6906     {
6907       const char *physname;
6908       struct fn_fieldlist *fn_flp
6909         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6910       physname = dwarf2_physname (mi->name, mi->die, cu);
6911       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6912     }
6913 }
6914
6915 /* Go objects should be embedded in a DW_TAG_module DIE,
6916    and it's not clear if/how imported objects will appear.
6917    To keep Go support simple until that's worked out,
6918    go back through what we've read and create something usable.
6919    We could do this while processing each DIE, and feels kinda cleaner,
6920    but that way is more invasive.
6921    This is to, for example, allow the user to type "p var" or "b main"
6922    without having to specify the package name, and allow lookups
6923    of module.object to work in contexts that use the expression
6924    parser.  */
6925
6926 static void
6927 fixup_go_packaging (struct dwarf2_cu *cu)
6928 {
6929   char *package_name = NULL;
6930   struct pending *list;
6931   int i;
6932
6933   for (list = global_symbols; list != NULL; list = list->next)
6934     {
6935       for (i = 0; i < list->nsyms; ++i)
6936         {
6937           struct symbol *sym = list->symbol[i];
6938
6939           if (SYMBOL_LANGUAGE (sym) == language_go
6940               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6941             {
6942               char *this_package_name = go_symbol_package_name (sym);
6943
6944               if (this_package_name == NULL)
6945                 continue;
6946               if (package_name == NULL)
6947                 package_name = this_package_name;
6948               else
6949                 {
6950                   if (strcmp (package_name, this_package_name) != 0)
6951                     complaint (&symfile_complaints,
6952                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6953                                (SYMBOL_SYMTAB (sym)
6954                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
6955                                 : cu->objfile->name),
6956                                this_package_name, package_name);
6957                   xfree (this_package_name);
6958                 }
6959             }
6960         }
6961     }
6962
6963   if (package_name != NULL)
6964     {
6965       struct objfile *objfile = cu->objfile;
6966       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6967                                                       package_name,
6968                                                       strlen (package_name));
6969       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6970                                      saved_package_name, objfile);
6971       struct symbol *sym;
6972
6973       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6974
6975       sym = allocate_symbol (objfile);
6976       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
6977       SYMBOL_SET_NAMES (sym, saved_package_name,
6978                         strlen (saved_package_name), 0, objfile);
6979       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6980          e.g., "main" finds the "main" module and not C's main().  */
6981       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6982       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
6983       SYMBOL_TYPE (sym) = type;
6984
6985       add_symbol_to_list (sym, &global_symbols);
6986
6987       xfree (package_name);
6988     }
6989 }
6990
6991 /* Return the symtab for PER_CU.  This works properly regardless of
6992    whether we're using the index or psymtabs.  */
6993
6994 static struct symtab *
6995 get_symtab (struct dwarf2_per_cu_data *per_cu)
6996 {
6997   return (dwarf2_per_objfile->using_index
6998           ? per_cu->v.quick->symtab
6999           : per_cu->v.psymtab->symtab);
7000 }
7001
7002 /* A helper function for computing the list of all symbol tables
7003    included by PER_CU.  */
7004
7005 static void
7006 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
7007                                 htab_t all_children,
7008                                 struct dwarf2_per_cu_data *per_cu)
7009 {
7010   void **slot;
7011   int ix;
7012   struct dwarf2_per_cu_data *iter;
7013
7014   slot = htab_find_slot (all_children, per_cu, INSERT);
7015   if (*slot != NULL)
7016     {
7017       /* This inclusion and its children have been processed.  */
7018       return;
7019     }
7020
7021   *slot = per_cu;
7022   /* Only add a CU if it has a symbol table.  */
7023   if (get_symtab (per_cu) != NULL)
7024     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
7025
7026   for (ix = 0;
7027        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7028        ++ix)
7029     recursively_compute_inclusions (result, all_children, iter);
7030 }
7031
7032 /* Compute the symtab 'includes' fields for the symtab related to
7033    PER_CU.  */
7034
7035 static void
7036 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7037 {
7038   gdb_assert (! per_cu->is_debug_types);
7039
7040   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7041     {
7042       int ix, len;
7043       struct dwarf2_per_cu_data *iter;
7044       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
7045       htab_t all_children;
7046       struct symtab *symtab = get_symtab (per_cu);
7047
7048       /* If we don't have a symtab, we can just skip this case.  */
7049       if (symtab == NULL)
7050         return;
7051
7052       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7053                                         NULL, xcalloc, xfree);
7054
7055       for (ix = 0;
7056            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7057                         ix, iter);
7058            ++ix)
7059         recursively_compute_inclusions (&result_children, all_children, iter);
7060
7061       /* Now we have a transitive closure of all the included CUs, and
7062          for .gdb_index version 7 the included TUs, so we can convert it
7063          to a list of symtabs.  */
7064       len = VEC_length (dwarf2_per_cu_ptr, result_children);
7065       symtab->includes
7066         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7067                          (len + 1) * sizeof (struct symtab *));
7068       for (ix = 0;
7069            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
7070            ++ix)
7071         symtab->includes[ix] = get_symtab (iter);
7072       symtab->includes[len] = NULL;
7073
7074       VEC_free (dwarf2_per_cu_ptr, result_children);
7075       htab_delete (all_children);
7076     }
7077 }
7078
7079 /* Compute the 'includes' field for the symtabs of all the CUs we just
7080    read.  */
7081
7082 static void
7083 process_cu_includes (void)
7084 {
7085   int ix;
7086   struct dwarf2_per_cu_data *iter;
7087
7088   for (ix = 0;
7089        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7090                     ix, iter);
7091        ++ix)
7092     {
7093       if (! iter->is_debug_types)
7094         compute_symtab_includes (iter);
7095     }
7096
7097   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7098 }
7099
7100 /* Generate full symbol information for PER_CU, whose DIEs have
7101    already been loaded into memory.  */
7102
7103 static void
7104 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7105                         enum language pretend_language)
7106 {
7107   struct dwarf2_cu *cu = per_cu->cu;
7108   struct objfile *objfile = per_cu->objfile;
7109   CORE_ADDR lowpc, highpc;
7110   struct symtab *symtab;
7111   struct cleanup *back_to, *delayed_list_cleanup;
7112   CORE_ADDR baseaddr;
7113   struct block *static_block;
7114
7115   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7116
7117   buildsym_init ();
7118   back_to = make_cleanup (really_free_pendings, NULL);
7119   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7120
7121   cu->list_in_scope = &file_symbols;
7122
7123   cu->language = pretend_language;
7124   cu->language_defn = language_def (cu->language);
7125
7126   /* Do line number decoding in read_file_scope () */
7127   process_die (cu->dies, cu);
7128
7129   /* For now fudge the Go package.  */
7130   if (cu->language == language_go)
7131     fixup_go_packaging (cu);
7132
7133   /* Now that we have processed all the DIEs in the CU, all the types 
7134      should be complete, and it should now be safe to compute all of the
7135      physnames.  */
7136   compute_delayed_physnames (cu);
7137   do_cleanups (delayed_list_cleanup);
7138
7139   /* Some compilers don't define a DW_AT_high_pc attribute for the
7140      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7141      it, by scanning the DIE's below the compilation unit.  */
7142   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7143
7144   static_block
7145     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7146
7147   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7148      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7149      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7150      addrmap to help ensure it has an accurate map of pc values belonging to
7151      this comp unit.  */
7152   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7153
7154   symtab = end_symtab_from_static_block (static_block, objfile,
7155                                          SECT_OFF_TEXT (objfile), 0);
7156
7157   if (symtab != NULL)
7158     {
7159       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7160
7161       /* Set symtab language to language from DW_AT_language.  If the
7162          compilation is from a C file generated by language preprocessors, do
7163          not set the language if it was already deduced by start_subfile.  */
7164       if (!(cu->language == language_c && symtab->language != language_c))
7165         symtab->language = cu->language;
7166
7167       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7168          produce DW_AT_location with location lists but it can be possibly
7169          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7170          there were bugs in prologue debug info, fixed later in GCC-4.5
7171          by "unwind info for epilogues" patch (which is not directly related).
7172
7173          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7174          needed, it would be wrong due to missing DW_AT_producer there.
7175
7176          Still one can confuse GDB by using non-standard GCC compilation
7177          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7178          */ 
7179       if (cu->has_loclist && gcc_4_minor >= 5)
7180         symtab->locations_valid = 1;
7181
7182       if (gcc_4_minor >= 5)
7183         symtab->epilogue_unwind_valid = 1;
7184
7185       symtab->call_site_htab = cu->call_site_htab;
7186     }
7187
7188   if (dwarf2_per_objfile->using_index)
7189     per_cu->v.quick->symtab = symtab;
7190   else
7191     {
7192       struct partial_symtab *pst = per_cu->v.psymtab;
7193       pst->symtab = symtab;
7194       pst->readin = 1;
7195     }
7196
7197   /* Push it for inclusion processing later.  */
7198   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7199
7200   do_cleanups (back_to);
7201 }
7202
7203 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7204    already been loaded into memory.  */
7205
7206 static void
7207 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7208                         enum language pretend_language)
7209 {
7210   struct dwarf2_cu *cu = per_cu->cu;
7211   struct objfile *objfile = per_cu->objfile;
7212   struct symtab *symtab;
7213   struct cleanup *back_to, *delayed_list_cleanup;
7214   struct signatured_type *sig_type;
7215
7216   gdb_assert (per_cu->is_debug_types);
7217   sig_type = (struct signatured_type *) per_cu;
7218
7219   buildsym_init ();
7220   back_to = make_cleanup (really_free_pendings, NULL);
7221   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7222
7223   cu->list_in_scope = &file_symbols;
7224
7225   cu->language = pretend_language;
7226   cu->language_defn = language_def (cu->language);
7227
7228   /* The symbol tables are set up in read_type_unit_scope.  */
7229   process_die (cu->dies, cu);
7230
7231   /* For now fudge the Go package.  */
7232   if (cu->language == language_go)
7233     fixup_go_packaging (cu);
7234
7235   /* Now that we have processed all the DIEs in the CU, all the types 
7236      should be complete, and it should now be safe to compute all of the
7237      physnames.  */
7238   compute_delayed_physnames (cu);
7239   do_cleanups (delayed_list_cleanup);
7240
7241   /* TUs share symbol tables.
7242      If this is the first TU to use this symtab, complete the construction
7243      of it with end_expandable_symtab.  Otherwise, complete the addition of
7244      this TU's symbols to the existing symtab.  */
7245   if (sig_type->type_unit_group->primary_symtab == NULL)
7246     {
7247       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7248       sig_type->type_unit_group->primary_symtab = symtab;
7249
7250       if (symtab != NULL)
7251         {
7252           /* Set symtab language to language from DW_AT_language.  If the
7253              compilation is from a C file generated by language preprocessors,
7254              do not set the language if it was already deduced by
7255              start_subfile.  */
7256           if (!(cu->language == language_c && symtab->language != language_c))
7257             symtab->language = cu->language;
7258         }
7259     }
7260   else
7261     {
7262       augment_type_symtab (objfile,
7263                            sig_type->type_unit_group->primary_symtab);
7264       symtab = sig_type->type_unit_group->primary_symtab;
7265     }
7266
7267   if (dwarf2_per_objfile->using_index)
7268     per_cu->v.quick->symtab = symtab;
7269   else
7270     {
7271       struct partial_symtab *pst = per_cu->v.psymtab;
7272       pst->symtab = symtab;
7273       pst->readin = 1;
7274     }
7275
7276   do_cleanups (back_to);
7277 }
7278
7279 /* Process an imported unit DIE.  */
7280
7281 static void
7282 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7283 {
7284   struct attribute *attr;
7285
7286   /* For now we don't handle imported units in type units.  */
7287   if (cu->per_cu->is_debug_types)
7288     {
7289       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7290                " supported in type units [in module %s]"),
7291              cu->objfile->name);
7292     }
7293
7294   attr = dwarf2_attr (die, DW_AT_import, cu);
7295   if (attr != NULL)
7296     {
7297       struct dwarf2_per_cu_data *per_cu;
7298       struct symtab *imported_symtab;
7299       sect_offset offset;
7300       int is_dwz;
7301
7302       offset = dwarf2_get_ref_die_offset (attr);
7303       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7304       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7305
7306       /* Queue the unit, if needed.  */
7307       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7308         load_full_comp_unit (per_cu, cu->language);
7309
7310       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7311                      per_cu);
7312     }
7313 }
7314
7315 /* Process a die and its children.  */
7316
7317 static void
7318 process_die (struct die_info *die, struct dwarf2_cu *cu)
7319 {
7320   switch (die->tag)
7321     {
7322     case DW_TAG_padding:
7323       break;
7324     case DW_TAG_compile_unit:
7325     case DW_TAG_partial_unit:
7326       read_file_scope (die, cu);
7327       break;
7328     case DW_TAG_type_unit:
7329       read_type_unit_scope (die, cu);
7330       break;
7331     case DW_TAG_subprogram:
7332     case DW_TAG_inlined_subroutine:
7333       read_func_scope (die, cu);
7334       break;
7335     case DW_TAG_lexical_block:
7336     case DW_TAG_try_block:
7337     case DW_TAG_catch_block:
7338       read_lexical_block_scope (die, cu);
7339       break;
7340     case DW_TAG_GNU_call_site:
7341       read_call_site_scope (die, cu);
7342       break;
7343     case DW_TAG_class_type:
7344     case DW_TAG_interface_type:
7345     case DW_TAG_structure_type:
7346     case DW_TAG_union_type:
7347       process_structure_scope (die, cu);
7348       break;
7349     case DW_TAG_enumeration_type:
7350       process_enumeration_scope (die, cu);
7351       break;
7352
7353     /* These dies have a type, but processing them does not create
7354        a symbol or recurse to process the children.  Therefore we can
7355        read them on-demand through read_type_die.  */
7356     case DW_TAG_subroutine_type:
7357     case DW_TAG_set_type:
7358     case DW_TAG_array_type:
7359     case DW_TAG_pointer_type:
7360     case DW_TAG_ptr_to_member_type:
7361     case DW_TAG_reference_type:
7362     case DW_TAG_string_type:
7363       break;
7364
7365     case DW_TAG_base_type:
7366     case DW_TAG_subrange_type:
7367     case DW_TAG_typedef:
7368       /* Add a typedef symbol for the type definition, if it has a
7369          DW_AT_name.  */
7370       new_symbol (die, read_type_die (die, cu), cu);
7371       break;
7372     case DW_TAG_common_block:
7373       read_common_block (die, cu);
7374       break;
7375     case DW_TAG_common_inclusion:
7376       break;
7377     case DW_TAG_namespace:
7378       cu->processing_has_namespace_info = 1;
7379       read_namespace (die, cu);
7380       break;
7381     case DW_TAG_module:
7382       cu->processing_has_namespace_info = 1;
7383       read_module (die, cu);
7384       break;
7385     case DW_TAG_imported_declaration:
7386     case DW_TAG_imported_module:
7387       cu->processing_has_namespace_info = 1;
7388       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7389                                  || cu->language != language_fortran))
7390         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7391                    dwarf_tag_name (die->tag));
7392       read_import_statement (die, cu);
7393       break;
7394
7395     case DW_TAG_imported_unit:
7396       process_imported_unit_die (die, cu);
7397       break;
7398
7399     default:
7400       new_symbol (die, NULL, cu);
7401       break;
7402     }
7403 }
7404 \f
7405 /* DWARF name computation.  */
7406
7407 /* A helper function for dwarf2_compute_name which determines whether DIE
7408    needs to have the name of the scope prepended to the name listed in the
7409    die.  */
7410
7411 static int
7412 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7413 {
7414   struct attribute *attr;
7415
7416   switch (die->tag)
7417     {
7418     case DW_TAG_namespace:
7419     case DW_TAG_typedef:
7420     case DW_TAG_class_type:
7421     case DW_TAG_interface_type:
7422     case DW_TAG_structure_type:
7423     case DW_TAG_union_type:
7424     case DW_TAG_enumeration_type:
7425     case DW_TAG_enumerator:
7426     case DW_TAG_subprogram:
7427     case DW_TAG_member:
7428       return 1;
7429
7430     case DW_TAG_variable:
7431     case DW_TAG_constant:
7432       /* We only need to prefix "globally" visible variables.  These include
7433          any variable marked with DW_AT_external or any variable that
7434          lives in a namespace.  [Variables in anonymous namespaces
7435          require prefixing, but they are not DW_AT_external.]  */
7436
7437       if (dwarf2_attr (die, DW_AT_specification, cu))
7438         {
7439           struct dwarf2_cu *spec_cu = cu;
7440
7441           return die_needs_namespace (die_specification (die, &spec_cu),
7442                                       spec_cu);
7443         }
7444
7445       attr = dwarf2_attr (die, DW_AT_external, cu);
7446       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7447           && die->parent->tag != DW_TAG_module)
7448         return 0;
7449       /* A variable in a lexical block of some kind does not need a
7450          namespace, even though in C++ such variables may be external
7451          and have a mangled name.  */
7452       if (die->parent->tag ==  DW_TAG_lexical_block
7453           || die->parent->tag ==  DW_TAG_try_block
7454           || die->parent->tag ==  DW_TAG_catch_block
7455           || die->parent->tag == DW_TAG_subprogram)
7456         return 0;
7457       return 1;
7458
7459     default:
7460       return 0;
7461     }
7462 }
7463
7464 /* Retrieve the last character from a mem_file.  */
7465
7466 static void
7467 do_ui_file_peek_last (void *object, const char *buffer, long length)
7468 {
7469   char *last_char_p = (char *) object;
7470
7471   if (length > 0)
7472     *last_char_p = buffer[length - 1];
7473 }
7474
7475 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7476    compute the physname for the object, which include a method's:
7477    - formal parameters (C++/Java),
7478    - receiver type (Go),
7479    - return type (Java).
7480
7481    The term "physname" is a bit confusing.
7482    For C++, for example, it is the demangled name.
7483    For Go, for example, it's the mangled name.
7484
7485    For Ada, return the DIE's linkage name rather than the fully qualified
7486    name.  PHYSNAME is ignored..
7487
7488    The result is allocated on the objfile_obstack and canonicalized.  */
7489
7490 static const char *
7491 dwarf2_compute_name (const char *name,
7492                      struct die_info *die, struct dwarf2_cu *cu,
7493                      int physname)
7494 {
7495   struct objfile *objfile = cu->objfile;
7496
7497   if (name == NULL)
7498     name = dwarf2_name (die, cu);
7499
7500   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7501      compute it by typename_concat inside GDB.  */
7502   if (cu->language == language_ada
7503       || (cu->language == language_fortran && physname))
7504     {
7505       /* For Ada unit, we prefer the linkage name over the name, as
7506          the former contains the exported name, which the user expects
7507          to be able to reference.  Ideally, we want the user to be able
7508          to reference this entity using either natural or linkage name,
7509          but we haven't started looking at this enhancement yet.  */
7510       struct attribute *attr;
7511
7512       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7513       if (attr == NULL)
7514         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7515       if (attr && DW_STRING (attr))
7516         return DW_STRING (attr);
7517     }
7518
7519   /* These are the only languages we know how to qualify names in.  */
7520   if (name != NULL
7521       && (cu->language == language_cplus || cu->language == language_java
7522           || cu->language == language_fortran))
7523     {
7524       if (die_needs_namespace (die, cu))
7525         {
7526           long length;
7527           const char *prefix;
7528           struct ui_file *buf;
7529
7530           prefix = determine_prefix (die, cu);
7531           buf = mem_fileopen ();
7532           if (*prefix != '\0')
7533             {
7534               char *prefixed_name = typename_concat (NULL, prefix, name,
7535                                                      physname, cu);
7536
7537               fputs_unfiltered (prefixed_name, buf);
7538               xfree (prefixed_name);
7539             }
7540           else
7541             fputs_unfiltered (name, buf);
7542
7543           /* Template parameters may be specified in the DIE's DW_AT_name, or
7544              as children with DW_TAG_template_type_param or
7545              DW_TAG_value_type_param.  If the latter, add them to the name
7546              here.  If the name already has template parameters, then
7547              skip this step; some versions of GCC emit both, and
7548              it is more efficient to use the pre-computed name.
7549
7550              Something to keep in mind about this process: it is very
7551              unlikely, or in some cases downright impossible, to produce
7552              something that will match the mangled name of a function.
7553              If the definition of the function has the same debug info,
7554              we should be able to match up with it anyway.  But fallbacks
7555              using the minimal symbol, for instance to find a method
7556              implemented in a stripped copy of libstdc++, will not work.
7557              If we do not have debug info for the definition, we will have to
7558              match them up some other way.
7559
7560              When we do name matching there is a related problem with function
7561              templates; two instantiated function templates are allowed to
7562              differ only by their return types, which we do not add here.  */
7563
7564           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7565             {
7566               struct attribute *attr;
7567               struct die_info *child;
7568               int first = 1;
7569
7570               die->building_fullname = 1;
7571
7572               for (child = die->child; child != NULL; child = child->sibling)
7573                 {
7574                   struct type *type;
7575                   LONGEST value;
7576                   const gdb_byte *bytes;
7577                   struct dwarf2_locexpr_baton *baton;
7578                   struct value *v;
7579
7580                   if (child->tag != DW_TAG_template_type_param
7581                       && child->tag != DW_TAG_template_value_param)
7582                     continue;
7583
7584                   if (first)
7585                     {
7586                       fputs_unfiltered ("<", buf);
7587                       first = 0;
7588                     }
7589                   else
7590                     fputs_unfiltered (", ", buf);
7591
7592                   attr = dwarf2_attr (child, DW_AT_type, cu);
7593                   if (attr == NULL)
7594                     {
7595                       complaint (&symfile_complaints,
7596                                  _("template parameter missing DW_AT_type"));
7597                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7598                       continue;
7599                     }
7600                   type = die_type (child, cu);
7601
7602                   if (child->tag == DW_TAG_template_type_param)
7603                     {
7604                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7605                       continue;
7606                     }
7607
7608                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7609                   if (attr == NULL)
7610                     {
7611                       complaint (&symfile_complaints,
7612                                  _("template parameter missing "
7613                                    "DW_AT_const_value"));
7614                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7615                       continue;
7616                     }
7617
7618                   dwarf2_const_value_attr (attr, type, name,
7619                                            &cu->comp_unit_obstack, cu,
7620                                            &value, &bytes, &baton);
7621
7622                   if (TYPE_NOSIGN (type))
7623                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7624                        changed, this can use value_print instead.  */
7625                     c_printchar (value, type, buf);
7626                   else
7627                     {
7628                       struct value_print_options opts;
7629
7630                       if (baton != NULL)
7631                         v = dwarf2_evaluate_loc_desc (type, NULL,
7632                                                       baton->data,
7633                                                       baton->size,
7634                                                       baton->per_cu);
7635                       else if (bytes != NULL)
7636                         {
7637                           v = allocate_value (type);
7638                           memcpy (value_contents_writeable (v), bytes,
7639                                   TYPE_LENGTH (type));
7640                         }
7641                       else
7642                         v = value_from_longest (type, value);
7643
7644                       /* Specify decimal so that we do not depend on
7645                          the radix.  */
7646                       get_formatted_print_options (&opts, 'd');
7647                       opts.raw = 1;
7648                       value_print (v, buf, &opts);
7649                       release_value (v);
7650                       value_free (v);
7651                     }
7652                 }
7653
7654               die->building_fullname = 0;
7655
7656               if (!first)
7657                 {
7658                   /* Close the argument list, with a space if necessary
7659                      (nested templates).  */
7660                   char last_char = '\0';
7661                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7662                   if (last_char == '>')
7663                     fputs_unfiltered (" >", buf);
7664                   else
7665                     fputs_unfiltered (">", buf);
7666                 }
7667             }
7668
7669           /* For Java and C++ methods, append formal parameter type
7670              information, if PHYSNAME.  */
7671
7672           if (physname && die->tag == DW_TAG_subprogram
7673               && (cu->language == language_cplus
7674                   || cu->language == language_java))
7675             {
7676               struct type *type = read_type_die (die, cu);
7677
7678               c_type_print_args (type, buf, 1, cu->language,
7679                                  &type_print_raw_options);
7680
7681               if (cu->language == language_java)
7682                 {
7683                   /* For java, we must append the return type to method
7684                      names.  */
7685                   if (die->tag == DW_TAG_subprogram)
7686                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7687                                      0, 0, &type_print_raw_options);
7688                 }
7689               else if (cu->language == language_cplus)
7690                 {
7691                   /* Assume that an artificial first parameter is
7692                      "this", but do not crash if it is not.  RealView
7693                      marks unnamed (and thus unused) parameters as
7694                      artificial; there is no way to differentiate
7695                      the two cases.  */
7696                   if (TYPE_NFIELDS (type) > 0
7697                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7698                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7699                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7700                                                                         0))))
7701                     fputs_unfiltered (" const", buf);
7702                 }
7703             }
7704
7705           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7706                                        &length);
7707           ui_file_delete (buf);
7708
7709           if (cu->language == language_cplus)
7710             {
7711               const char *cname
7712                 = dwarf2_canonicalize_name (name, cu,
7713                                             &objfile->objfile_obstack);
7714
7715               if (cname != NULL)
7716                 name = cname;
7717             }
7718         }
7719     }
7720
7721   return name;
7722 }
7723
7724 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7725    If scope qualifiers are appropriate they will be added.  The result
7726    will be allocated on the objfile_obstack, or NULL if the DIE does
7727    not have a name.  NAME may either be from a previous call to
7728    dwarf2_name or NULL.
7729
7730    The output string will be canonicalized (if C++/Java).  */
7731
7732 static const char *
7733 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7734 {
7735   return dwarf2_compute_name (name, die, cu, 0);
7736 }
7737
7738 /* Construct a physname for the given DIE in CU.  NAME may either be
7739    from a previous call to dwarf2_name or NULL.  The result will be
7740    allocated on the objfile_objstack or NULL if the DIE does not have a
7741    name.
7742
7743    The output string will be canonicalized (if C++/Java).  */
7744
7745 static const char *
7746 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7747 {
7748   struct objfile *objfile = cu->objfile;
7749   struct attribute *attr;
7750   const char *retval, *mangled = NULL, *canon = NULL;
7751   struct cleanup *back_to;
7752   int need_copy = 1;
7753
7754   /* In this case dwarf2_compute_name is just a shortcut not building anything
7755      on its own.  */
7756   if (!die_needs_namespace (die, cu))
7757     return dwarf2_compute_name (name, die, cu, 1);
7758
7759   back_to = make_cleanup (null_cleanup, NULL);
7760
7761   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7762   if (!attr)
7763     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7764
7765   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7766      has computed.  */
7767   if (attr && DW_STRING (attr))
7768     {
7769       char *demangled;
7770
7771       mangled = DW_STRING (attr);
7772
7773       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7774          type.  It is easier for GDB users to search for such functions as
7775          `name(params)' than `long name(params)'.  In such case the minimal
7776          symbol names do not match the full symbol names but for template
7777          functions there is never a need to look up their definition from their
7778          declaration so the only disadvantage remains the minimal symbol
7779          variant `long name(params)' does not have the proper inferior type.
7780          */
7781
7782       if (cu->language == language_go)
7783         {
7784           /* This is a lie, but we already lie to the caller new_symbol_full.
7785              new_symbol_full assumes we return the mangled name.
7786              This just undoes that lie until things are cleaned up.  */
7787           demangled = NULL;
7788         }
7789       else
7790         {
7791           demangled = gdb_demangle (mangled,
7792                                     (DMGL_PARAMS | DMGL_ANSI
7793                                      | (cu->language == language_java
7794                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
7795                                         : DMGL_RET_DROP)));
7796         }
7797       if (demangled)
7798         {
7799           make_cleanup (xfree, demangled);
7800           canon = demangled;
7801         }
7802       else
7803         {
7804           canon = mangled;
7805           need_copy = 0;
7806         }
7807     }
7808
7809   if (canon == NULL || check_physname)
7810     {
7811       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7812
7813       if (canon != NULL && strcmp (physname, canon) != 0)
7814         {
7815           /* It may not mean a bug in GDB.  The compiler could also
7816              compute DW_AT_linkage_name incorrectly.  But in such case
7817              GDB would need to be bug-to-bug compatible.  */
7818
7819           complaint (&symfile_complaints,
7820                      _("Computed physname <%s> does not match demangled <%s> "
7821                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7822                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7823
7824           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7825              is available here - over computed PHYSNAME.  It is safer
7826              against both buggy GDB and buggy compilers.  */
7827
7828           retval = canon;
7829         }
7830       else
7831         {
7832           retval = physname;
7833           need_copy = 0;
7834         }
7835     }
7836   else
7837     retval = canon;
7838
7839   if (need_copy)
7840     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7841
7842   do_cleanups (back_to);
7843   return retval;
7844 }
7845
7846 /* Read the import statement specified by the given die and record it.  */
7847
7848 static void
7849 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7850 {
7851   struct objfile *objfile = cu->objfile;
7852   struct attribute *import_attr;
7853   struct die_info *imported_die, *child_die;
7854   struct dwarf2_cu *imported_cu;
7855   const char *imported_name;
7856   const char *imported_name_prefix;
7857   const char *canonical_name;
7858   const char *import_alias;
7859   const char *imported_declaration = NULL;
7860   const char *import_prefix;
7861   VEC (const_char_ptr) *excludes = NULL;
7862   struct cleanup *cleanups;
7863
7864   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7865   if (import_attr == NULL)
7866     {
7867       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7868                  dwarf_tag_name (die->tag));
7869       return;
7870     }
7871
7872   imported_cu = cu;
7873   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7874   imported_name = dwarf2_name (imported_die, imported_cu);
7875   if (imported_name == NULL)
7876     {
7877       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7878
7879         The import in the following code:
7880         namespace A
7881           {
7882             typedef int B;
7883           }
7884
7885         int main ()
7886           {
7887             using A::B;
7888             B b;
7889             return b;
7890           }
7891
7892         ...
7893          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7894             <52>   DW_AT_decl_file   : 1
7895             <53>   DW_AT_decl_line   : 6
7896             <54>   DW_AT_import      : <0x75>
7897          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7898             <59>   DW_AT_name        : B
7899             <5b>   DW_AT_decl_file   : 1
7900             <5c>   DW_AT_decl_line   : 2
7901             <5d>   DW_AT_type        : <0x6e>
7902         ...
7903          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7904             <76>   DW_AT_byte_size   : 4
7905             <77>   DW_AT_encoding    : 5        (signed)
7906
7907         imports the wrong die ( 0x75 instead of 0x58 ).
7908         This case will be ignored until the gcc bug is fixed.  */
7909       return;
7910     }
7911
7912   /* Figure out the local name after import.  */
7913   import_alias = dwarf2_name (die, cu);
7914
7915   /* Figure out where the statement is being imported to.  */
7916   import_prefix = determine_prefix (die, cu);
7917
7918   /* Figure out what the scope of the imported die is and prepend it
7919      to the name of the imported die.  */
7920   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7921
7922   if (imported_die->tag != DW_TAG_namespace
7923       && imported_die->tag != DW_TAG_module)
7924     {
7925       imported_declaration = imported_name;
7926       canonical_name = imported_name_prefix;
7927     }
7928   else if (strlen (imported_name_prefix) > 0)
7929     canonical_name = obconcat (&objfile->objfile_obstack,
7930                                imported_name_prefix, "::", imported_name,
7931                                (char *) NULL);
7932   else
7933     canonical_name = imported_name;
7934
7935   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7936
7937   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7938     for (child_die = die->child; child_die && child_die->tag;
7939          child_die = sibling_die (child_die))
7940       {
7941         /* DWARF-4: A Fortran use statement with a “rename list” may be
7942            represented by an imported module entry with an import attribute
7943            referring to the module and owned entries corresponding to those
7944            entities that are renamed as part of being imported.  */
7945
7946         if (child_die->tag != DW_TAG_imported_declaration)
7947           {
7948             complaint (&symfile_complaints,
7949                        _("child DW_TAG_imported_declaration expected "
7950                          "- DIE at 0x%x [in module %s]"),
7951                        child_die->offset.sect_off, objfile->name);
7952             continue;
7953           }
7954
7955         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7956         if (import_attr == NULL)
7957           {
7958             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7959                        dwarf_tag_name (child_die->tag));
7960             continue;
7961           }
7962
7963         imported_cu = cu;
7964         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7965                                               &imported_cu);
7966         imported_name = dwarf2_name (imported_die, imported_cu);
7967         if (imported_name == NULL)
7968           {
7969             complaint (&symfile_complaints,
7970                        _("child DW_TAG_imported_declaration has unknown "
7971                          "imported name - DIE at 0x%x [in module %s]"),
7972                        child_die->offset.sect_off, objfile->name);
7973             continue;
7974           }
7975
7976         VEC_safe_push (const_char_ptr, excludes, imported_name);
7977
7978         process_die (child_die, cu);
7979       }
7980
7981   cp_add_using_directive (import_prefix,
7982                           canonical_name,
7983                           import_alias,
7984                           imported_declaration,
7985                           excludes,
7986                           0,
7987                           &objfile->objfile_obstack);
7988
7989   do_cleanups (cleanups);
7990 }
7991
7992 /* Cleanup function for handle_DW_AT_stmt_list.  */
7993
7994 static void
7995 free_cu_line_header (void *arg)
7996 {
7997   struct dwarf2_cu *cu = arg;
7998
7999   free_line_header (cu->line_header);
8000   cu->line_header = NULL;
8001 }
8002
8003 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8004    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8005    this, it was first present in GCC release 4.3.0.  */
8006
8007 static int
8008 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8009 {
8010   if (!cu->checked_producer)
8011     check_producer (cu);
8012
8013   return cu->producer_is_gcc_lt_4_3;
8014 }
8015
8016 static void
8017 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8018                          const char **name, const char **comp_dir)
8019 {
8020   struct attribute *attr;
8021
8022   *name = NULL;
8023   *comp_dir = NULL;
8024
8025   /* Find the filename.  Do not use dwarf2_name here, since the filename
8026      is not a source language identifier.  */
8027   attr = dwarf2_attr (die, DW_AT_name, cu);
8028   if (attr)
8029     {
8030       *name = DW_STRING (attr);
8031     }
8032
8033   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8034   if (attr)
8035     *comp_dir = DW_STRING (attr);
8036   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8037            && IS_ABSOLUTE_PATH (*name))
8038     {
8039       char *d = ldirname (*name);
8040
8041       *comp_dir = d;
8042       if (d != NULL)
8043         make_cleanup (xfree, d);
8044     }
8045   if (*comp_dir != NULL)
8046     {
8047       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8048          directory, get rid of it.  */
8049       char *cp = strchr (*comp_dir, ':');
8050
8051       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8052         *comp_dir = cp + 1;
8053     }
8054
8055   if (*name == NULL)
8056     *name = "<unknown>";
8057 }
8058
8059 /* Handle DW_AT_stmt_list for a compilation unit.
8060    DIE is the DW_TAG_compile_unit die for CU.
8061    COMP_DIR is the compilation directory.
8062    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8063
8064 static void
8065 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8066                         const char *comp_dir) /* ARI: editCase function */
8067 {
8068   struct attribute *attr;
8069
8070   gdb_assert (! cu->per_cu->is_debug_types);
8071
8072   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8073   if (attr)
8074     {
8075       unsigned int line_offset = DW_UNSND (attr);
8076       struct line_header *line_header
8077         = dwarf_decode_line_header (line_offset, cu);
8078
8079       if (line_header)
8080         {
8081           cu->line_header = line_header;
8082           make_cleanup (free_cu_line_header, cu);
8083           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8084         }
8085     }
8086 }
8087
8088 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8089
8090 static void
8091 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8092 {
8093   struct objfile *objfile = dwarf2_per_objfile->objfile;
8094   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8095   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8096   CORE_ADDR highpc = ((CORE_ADDR) 0);
8097   struct attribute *attr;
8098   const char *name = NULL;
8099   const char *comp_dir = NULL;
8100   struct die_info *child_die;
8101   bfd *abfd = objfile->obfd;
8102   CORE_ADDR baseaddr;
8103
8104   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8105
8106   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8107
8108   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8109      from finish_block.  */
8110   if (lowpc == ((CORE_ADDR) -1))
8111     lowpc = highpc;
8112   lowpc += baseaddr;
8113   highpc += baseaddr;
8114
8115   find_file_and_directory (die, cu, &name, &comp_dir);
8116
8117   prepare_one_comp_unit (cu, die, cu->language);
8118
8119   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8120      standardised yet.  As a workaround for the language detection we fall
8121      back to the DW_AT_producer string.  */
8122   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8123     cu->language = language_opencl;
8124
8125   /* Similar hack for Go.  */
8126   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8127     set_cu_language (DW_LANG_Go, cu);
8128
8129   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8130
8131   /* Decode line number information if present.  We do this before
8132      processing child DIEs, so that the line header table is available
8133      for DW_AT_decl_file.  */
8134   handle_DW_AT_stmt_list (die, cu, comp_dir);
8135
8136   /* Process all dies in compilation unit.  */
8137   if (die->child != NULL)
8138     {
8139       child_die = die->child;
8140       while (child_die && child_die->tag)
8141         {
8142           process_die (child_die, cu);
8143           child_die = sibling_die (child_die);
8144         }
8145     }
8146
8147   /* Decode macro information, if present.  Dwarf 2 macro information
8148      refers to information in the line number info statement program
8149      header, so we can only read it if we've read the header
8150      successfully.  */
8151   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8152   if (attr && cu->line_header)
8153     {
8154       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8155         complaint (&symfile_complaints,
8156                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8157
8158       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8159     }
8160   else
8161     {
8162       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8163       if (attr && cu->line_header)
8164         {
8165           unsigned int macro_offset = DW_UNSND (attr);
8166
8167           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8168         }
8169     }
8170
8171   do_cleanups (back_to);
8172 }
8173
8174 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8175    Create the set of symtabs used by this TU, or if this TU is sharing
8176    symtabs with another TU and the symtabs have already been created
8177    then restore those symtabs in the line header.
8178    We don't need the pc/line-number mapping for type units.  */
8179
8180 static void
8181 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8182 {
8183   struct objfile *objfile = dwarf2_per_objfile->objfile;
8184   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8185   struct type_unit_group *tu_group;
8186   int first_time;
8187   struct line_header *lh;
8188   struct attribute *attr;
8189   unsigned int i, line_offset;
8190   struct signatured_type *sig_type;
8191
8192   gdb_assert (per_cu->is_debug_types);
8193   sig_type = (struct signatured_type *) per_cu;
8194
8195   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8196
8197   /* If we're using .gdb_index (includes -readnow) then
8198      per_cu->type_unit_group may not have been set up yet.  */
8199   if (sig_type->type_unit_group == NULL)
8200     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8201   tu_group = sig_type->type_unit_group;
8202
8203   /* If we've already processed this stmt_list there's no real need to
8204      do it again, we could fake it and just recreate the part we need
8205      (file name,index -> symtab mapping).  If data shows this optimization
8206      is useful we can do it then.  */
8207   first_time = tu_group->primary_symtab == NULL;
8208
8209   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8210      debug info.  */
8211   lh = NULL;
8212   if (attr != NULL)
8213     {
8214       line_offset = DW_UNSND (attr);
8215       lh = dwarf_decode_line_header (line_offset, cu);
8216     }
8217   if (lh == NULL)
8218     {
8219       if (first_time)
8220         dwarf2_start_symtab (cu, "", NULL, 0);
8221       else
8222         {
8223           gdb_assert (tu_group->symtabs == NULL);
8224           restart_symtab (0);
8225         }
8226       /* Note: The primary symtab will get allocated at the end.  */
8227       return;
8228     }
8229
8230   cu->line_header = lh;
8231   make_cleanup (free_cu_line_header, cu);
8232
8233   if (first_time)
8234     {
8235       dwarf2_start_symtab (cu, "", NULL, 0);
8236
8237       tu_group->num_symtabs = lh->num_file_names;
8238       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8239
8240       for (i = 0; i < lh->num_file_names; ++i)
8241         {
8242           const char *dir = NULL;
8243           struct file_entry *fe = &lh->file_names[i];
8244
8245           if (fe->dir_index)
8246             dir = lh->include_dirs[fe->dir_index - 1];
8247           dwarf2_start_subfile (fe->name, dir, NULL);
8248
8249           /* Note: We don't have to watch for the main subfile here, type units
8250              don't have DW_AT_name.  */
8251
8252           if (current_subfile->symtab == NULL)
8253             {
8254               /* NOTE: start_subfile will recognize when it's been passed
8255                  a file it has already seen.  So we can't assume there's a
8256                  simple mapping from lh->file_names to subfiles,
8257                  lh->file_names may contain dups.  */
8258               current_subfile->symtab = allocate_symtab (current_subfile->name,
8259                                                          objfile);
8260             }
8261
8262           fe->symtab = current_subfile->symtab;
8263           tu_group->symtabs[i] = fe->symtab;
8264         }
8265     }
8266   else
8267     {
8268       restart_symtab (0);
8269
8270       for (i = 0; i < lh->num_file_names; ++i)
8271         {
8272           struct file_entry *fe = &lh->file_names[i];
8273
8274           fe->symtab = tu_group->symtabs[i];
8275         }
8276     }
8277
8278   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8279      so they don't have a "real" (so to speak) symtab anyway.
8280      There is later code that will assign the main symtab to all symbols
8281      that don't have one.  We need to handle the case of a symbol with a
8282      missing symtab (DW_AT_decl_file) anyway.  */
8283 }
8284
8285 /* Process DW_TAG_type_unit.
8286    For TUs we want to skip the first top level sibling if it's not the
8287    actual type being defined by this TU.  In this case the first top
8288    level sibling is there to provide context only.  */
8289
8290 static void
8291 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8292 {
8293   struct die_info *child_die;
8294
8295   prepare_one_comp_unit (cu, die, language_minimal);
8296
8297   /* Initialize (or reinitialize) the machinery for building symtabs.
8298      We do this before processing child DIEs, so that the line header table
8299      is available for DW_AT_decl_file.  */
8300   setup_type_unit_groups (die, cu);
8301
8302   if (die->child != NULL)
8303     {
8304       child_die = die->child;
8305       while (child_die && child_die->tag)
8306         {
8307           process_die (child_die, cu);
8308           child_die = sibling_die (child_die);
8309         }
8310     }
8311 }
8312 \f
8313 /* DWO/DWP files.
8314
8315    http://gcc.gnu.org/wiki/DebugFission
8316    http://gcc.gnu.org/wiki/DebugFissionDWP
8317
8318    To simplify handling of both DWO files ("object" files with the DWARF info)
8319    and DWP files (a file with the DWOs packaged up into one file), we treat
8320    DWP files as having a collection of virtual DWO files.  */
8321
8322 static hashval_t
8323 hash_dwo_file (const void *item)
8324 {
8325   const struct dwo_file *dwo_file = item;
8326
8327   return (htab_hash_string (dwo_file->dwo_name)
8328           + htab_hash_string (dwo_file->comp_dir));
8329 }
8330
8331 static int
8332 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8333 {
8334   const struct dwo_file *lhs = item_lhs;
8335   const struct dwo_file *rhs = item_rhs;
8336
8337   return (strcmp (lhs->dwo_name, rhs->dwo_name) == 0
8338           && strcmp (lhs->comp_dir, rhs->comp_dir) == 0);
8339 }
8340
8341 /* Allocate a hash table for DWO files.  */
8342
8343 static htab_t
8344 allocate_dwo_file_hash_table (void)
8345 {
8346   struct objfile *objfile = dwarf2_per_objfile->objfile;
8347
8348   return htab_create_alloc_ex (41,
8349                                hash_dwo_file,
8350                                eq_dwo_file,
8351                                NULL,
8352                                &objfile->objfile_obstack,
8353                                hashtab_obstack_allocate,
8354                                dummy_obstack_deallocate);
8355 }
8356
8357 /* Lookup DWO file DWO_NAME.  */
8358
8359 static void **
8360 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8361 {
8362   struct dwo_file find_entry;
8363   void **slot;
8364
8365   if (dwarf2_per_objfile->dwo_files == NULL)
8366     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8367
8368   memset (&find_entry, 0, sizeof (find_entry));
8369   find_entry.dwo_name = dwo_name;
8370   find_entry.comp_dir = comp_dir;
8371   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8372
8373   return slot;
8374 }
8375
8376 static hashval_t
8377 hash_dwo_unit (const void *item)
8378 {
8379   const struct dwo_unit *dwo_unit = item;
8380
8381   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8382   return dwo_unit->signature;
8383 }
8384
8385 static int
8386 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8387 {
8388   const struct dwo_unit *lhs = item_lhs;
8389   const struct dwo_unit *rhs = item_rhs;
8390
8391   /* The signature is assumed to be unique within the DWO file.
8392      So while object file CU dwo_id's always have the value zero,
8393      that's OK, assuming each object file DWO file has only one CU,
8394      and that's the rule for now.  */
8395   return lhs->signature == rhs->signature;
8396 }
8397
8398 /* Allocate a hash table for DWO CUs,TUs.
8399    There is one of these tables for each of CUs,TUs for each DWO file.  */
8400
8401 static htab_t
8402 allocate_dwo_unit_table (struct objfile *objfile)
8403 {
8404   /* Start out with a pretty small number.
8405      Generally DWO files contain only one CU and maybe some TUs.  */
8406   return htab_create_alloc_ex (3,
8407                                hash_dwo_unit,
8408                                eq_dwo_unit,
8409                                NULL,
8410                                &objfile->objfile_obstack,
8411                                hashtab_obstack_allocate,
8412                                dummy_obstack_deallocate);
8413 }
8414
8415 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8416
8417 struct create_dwo_cu_data
8418 {
8419   struct dwo_file *dwo_file;
8420   struct dwo_unit dwo_unit;
8421 };
8422
8423 /* die_reader_func for create_dwo_cu.  */
8424
8425 static void
8426 create_dwo_cu_reader (const struct die_reader_specs *reader,
8427                       const gdb_byte *info_ptr,
8428                       struct die_info *comp_unit_die,
8429                       int has_children,
8430                       void *datap)
8431 {
8432   struct dwarf2_cu *cu = reader->cu;
8433   struct objfile *objfile = dwarf2_per_objfile->objfile;
8434   sect_offset offset = cu->per_cu->offset;
8435   struct dwarf2_section_info *section = cu->per_cu->section;
8436   struct create_dwo_cu_data *data = datap;
8437   struct dwo_file *dwo_file = data->dwo_file;
8438   struct dwo_unit *dwo_unit = &data->dwo_unit;
8439   struct attribute *attr;
8440
8441   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8442   if (attr == NULL)
8443     {
8444       complaint (&symfile_complaints,
8445                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8446                    " its dwo_id [in module %s]"),
8447                  offset.sect_off, dwo_file->dwo_name);
8448       return;
8449     }
8450
8451   dwo_unit->dwo_file = dwo_file;
8452   dwo_unit->signature = DW_UNSND (attr);
8453   dwo_unit->section = section;
8454   dwo_unit->offset = offset;
8455   dwo_unit->length = cu->per_cu->length;
8456
8457   if (dwarf2_read_debug)
8458     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8459                         offset.sect_off, hex_string (dwo_unit->signature));
8460 }
8461
8462 /* Create the dwo_unit for the lone CU in DWO_FILE.
8463    Note: This function processes DWO files only, not DWP files.  */
8464
8465 static struct dwo_unit *
8466 create_dwo_cu (struct dwo_file *dwo_file)
8467 {
8468   struct objfile *objfile = dwarf2_per_objfile->objfile;
8469   struct dwarf2_section_info *section = &dwo_file->sections.info;
8470   bfd *abfd;
8471   htab_t cu_htab;
8472   const gdb_byte *info_ptr, *end_ptr;
8473   struct create_dwo_cu_data create_dwo_cu_data;
8474   struct dwo_unit *dwo_unit;
8475
8476   dwarf2_read_section (objfile, section);
8477   info_ptr = section->buffer;
8478
8479   if (info_ptr == NULL)
8480     return NULL;
8481
8482   /* We can't set abfd until now because the section may be empty or
8483      not present, in which case section->asection will be NULL.  */
8484   abfd = section->asection->owner;
8485
8486   if (dwarf2_read_debug)
8487     {
8488       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8489                           bfd_section_name (abfd, section->asection),
8490                           bfd_get_filename (abfd));
8491     }
8492
8493   create_dwo_cu_data.dwo_file = dwo_file;
8494   dwo_unit = NULL;
8495
8496   end_ptr = info_ptr + section->size;
8497   while (info_ptr < end_ptr)
8498     {
8499       struct dwarf2_per_cu_data per_cu;
8500
8501       memset (&create_dwo_cu_data.dwo_unit, 0,
8502               sizeof (create_dwo_cu_data.dwo_unit));
8503       memset (&per_cu, 0, sizeof (per_cu));
8504       per_cu.objfile = objfile;
8505       per_cu.is_debug_types = 0;
8506       per_cu.offset.sect_off = info_ptr - section->buffer;
8507       per_cu.section = section;
8508
8509       init_cutu_and_read_dies_no_follow (&per_cu,
8510                                          &dwo_file->sections.abbrev,
8511                                          dwo_file,
8512                                          create_dwo_cu_reader,
8513                                          &create_dwo_cu_data);
8514
8515       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8516         {
8517           /* If we've already found one, complain.  We only support one
8518              because having more than one requires hacking the dwo_name of
8519              each to match, which is highly unlikely to happen.  */
8520           if (dwo_unit != NULL)
8521             {
8522               complaint (&symfile_complaints,
8523                          _("Multiple CUs in DWO file %s [in module %s]"),
8524                          dwo_file->dwo_name, objfile->name);
8525               break;
8526             }
8527
8528           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8529           *dwo_unit = create_dwo_cu_data.dwo_unit;
8530         }
8531
8532       info_ptr += per_cu.length;
8533     }
8534
8535   return dwo_unit;
8536 }
8537
8538 /* DWP file .debug_{cu,tu}_index section format:
8539    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8540
8541    Both index sections have the same format, and serve to map a 64-bit
8542    signature to a set of section numbers.  Each section begins with a header,
8543    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8544    indexes, and a pool of 32-bit section numbers.  The index sections will be
8545    aligned at 8-byte boundaries in the file.
8546
8547    The index section header contains two unsigned 32-bit values (using the
8548    byte order of the application binary):
8549
8550     N, the number of compilation units or type units in the index
8551     M, the number of slots in the hash table
8552
8553   (We assume that N and M will not exceed 2^32 - 1.)
8554
8555   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8556
8557   The hash table begins at offset 8 in the section, and consists of an array
8558   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8559   order of the application binary).  Unused slots in the hash table are 0.
8560   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8561
8562   The parallel table begins immediately after the hash table
8563   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8564   array of 32-bit indexes (using the byte order of the application binary),
8565   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8566   table contains a 32-bit index into the pool of section numbers.  For unused
8567   hash table slots, the corresponding entry in the parallel table will be 0.
8568
8569   Given a 64-bit compilation unit signature or a type signature S, an entry
8570   in the hash table is located as follows:
8571
8572   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8573      the low-order k bits all set to 1.
8574
8575   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8576
8577   3) If the hash table entry at index H matches the signature, use that
8578      entry.  If the hash table entry at index H is unused (all zeroes),
8579      terminate the search: the signature is not present in the table.
8580
8581   4) Let H = (H + H') modulo M. Repeat at Step 3.
8582
8583   Because M > N and H' and M are relatively prime, the search is guaranteed
8584   to stop at an unused slot or find the match.
8585
8586   The pool of section numbers begins immediately following the hash table
8587   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8588   section numbers consists of an array of 32-bit words (using the byte order
8589   of the application binary).  Each item in the array is indexed starting
8590   from 0.  The hash table entry provides the index of the first section
8591   number in the set.  Additional section numbers in the set follow, and the
8592   set is terminated by a 0 entry (section number 0 is not used in ELF).
8593
8594   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8595   section must be the first entry in the set, and the .debug_abbrev.dwo must
8596   be the second entry. Other members of the set may follow in any order.  */
8597
8598 /* Create a hash table to map DWO IDs to their CU/TU entry in
8599    .debug_{info,types}.dwo in DWP_FILE.
8600    Returns NULL if there isn't one.
8601    Note: This function processes DWP files only, not DWO files.  */
8602
8603 static struct dwp_hash_table *
8604 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8605 {
8606   struct objfile *objfile = dwarf2_per_objfile->objfile;
8607   bfd *dbfd = dwp_file->dbfd;
8608   const gdb_byte *index_ptr, *index_end;
8609   struct dwarf2_section_info *index;
8610   uint32_t version, nr_units, nr_slots;
8611   struct dwp_hash_table *htab;
8612
8613   if (is_debug_types)
8614     index = &dwp_file->sections.tu_index;
8615   else
8616     index = &dwp_file->sections.cu_index;
8617
8618   if (dwarf2_section_empty_p (index))
8619     return NULL;
8620   dwarf2_read_section (objfile, index);
8621
8622   index_ptr = index->buffer;
8623   index_end = index_ptr + index->size;
8624
8625   version = read_4_bytes (dbfd, index_ptr);
8626   index_ptr += 8; /* Skip the unused word.  */
8627   nr_units = read_4_bytes (dbfd, index_ptr);
8628   index_ptr += 4;
8629   nr_slots = read_4_bytes (dbfd, index_ptr);
8630   index_ptr += 4;
8631
8632   if (version != 1)
8633     {
8634       error (_("Dwarf Error: unsupported DWP file version (%u)"
8635                " [in module %s]"),
8636              version, dwp_file->name);
8637     }
8638   if (nr_slots != (nr_slots & -nr_slots))
8639     {
8640       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8641                " is not power of 2 [in module %s]"),
8642              nr_slots, dwp_file->name);
8643     }
8644
8645   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8646   htab->nr_units = nr_units;
8647   htab->nr_slots = nr_slots;
8648   htab->hash_table = index_ptr;
8649   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8650   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8651
8652   return htab;
8653 }
8654
8655 /* Update SECTIONS with the data from SECTP.
8656
8657    This function is like the other "locate" section routines that are
8658    passed to bfd_map_over_sections, but in this context the sections to
8659    read comes from the DWP hash table, not the full ELF section table.
8660
8661    The result is non-zero for success, or zero if an error was found.  */
8662
8663 static int
8664 locate_virtual_dwo_sections (asection *sectp,
8665                              struct virtual_dwo_sections *sections)
8666 {
8667   const struct dwop_section_names *names = &dwop_section_names;
8668
8669   if (section_is_p (sectp->name, &names->abbrev_dwo))
8670     {
8671       /* There can be only one.  */
8672       if (sections->abbrev.asection != NULL)
8673         return 0;
8674       sections->abbrev.asection = sectp;
8675       sections->abbrev.size = bfd_get_section_size (sectp);
8676     }
8677   else if (section_is_p (sectp->name, &names->info_dwo)
8678            || section_is_p (sectp->name, &names->types_dwo))
8679     {
8680       /* There can be only one.  */
8681       if (sections->info_or_types.asection != NULL)
8682         return 0;
8683       sections->info_or_types.asection = sectp;
8684       sections->info_or_types.size = bfd_get_section_size (sectp);
8685     }
8686   else if (section_is_p (sectp->name, &names->line_dwo))
8687     {
8688       /* There can be only one.  */
8689       if (sections->line.asection != NULL)
8690         return 0;
8691       sections->line.asection = sectp;
8692       sections->line.size = bfd_get_section_size (sectp);
8693     }
8694   else if (section_is_p (sectp->name, &names->loc_dwo))
8695     {
8696       /* There can be only one.  */
8697       if (sections->loc.asection != NULL)
8698         return 0;
8699       sections->loc.asection = sectp;
8700       sections->loc.size = bfd_get_section_size (sectp);
8701     }
8702   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8703     {
8704       /* There can be only one.  */
8705       if (sections->macinfo.asection != NULL)
8706         return 0;
8707       sections->macinfo.asection = sectp;
8708       sections->macinfo.size = bfd_get_section_size (sectp);
8709     }
8710   else if (section_is_p (sectp->name, &names->macro_dwo))
8711     {
8712       /* There can be only one.  */
8713       if (sections->macro.asection != NULL)
8714         return 0;
8715       sections->macro.asection = sectp;
8716       sections->macro.size = bfd_get_section_size (sectp);
8717     }
8718   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8719     {
8720       /* There can be only one.  */
8721       if (sections->str_offsets.asection != NULL)
8722         return 0;
8723       sections->str_offsets.asection = sectp;
8724       sections->str_offsets.size = bfd_get_section_size (sectp);
8725     }
8726   else
8727     {
8728       /* No other kind of section is valid.  */
8729       return 0;
8730     }
8731
8732   return 1;
8733 }
8734
8735 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8736    HTAB is the hash table from the DWP file.
8737    SECTION_INDEX is the index of the DWO in HTAB.
8738    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
8739
8740 static struct dwo_unit *
8741 create_dwo_in_dwp (struct dwp_file *dwp_file,
8742                    const struct dwp_hash_table *htab,
8743                    uint32_t section_index,
8744                    const char *comp_dir,
8745                    ULONGEST signature, int is_debug_types)
8746 {
8747   struct objfile *objfile = dwarf2_per_objfile->objfile;
8748   bfd *dbfd = dwp_file->dbfd;
8749   const char *kind = is_debug_types ? "TU" : "CU";
8750   struct dwo_file *dwo_file;
8751   struct dwo_unit *dwo_unit;
8752   struct virtual_dwo_sections sections;
8753   void **dwo_file_slot;
8754   char *virtual_dwo_name;
8755   struct dwarf2_section_info *cutu;
8756   struct cleanup *cleanups;
8757   int i;
8758
8759   if (dwarf2_read_debug)
8760     {
8761       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/%s in DWP file: %s\n",
8762                           kind,
8763                           section_index, hex_string (signature),
8764                           dwp_file->name);
8765     }
8766
8767   /* Fetch the sections of this DWO.
8768      Put a limit on the number of sections we look for so that bad data
8769      doesn't cause us to loop forever.  */
8770
8771 #define MAX_NR_DWO_SECTIONS \
8772   (1 /* .debug_info or .debug_types */ \
8773    + 1 /* .debug_abbrev */ \
8774    + 1 /* .debug_line */ \
8775    + 1 /* .debug_loc */ \
8776    + 1 /* .debug_str_offsets */ \
8777    + 1 /* .debug_macro */ \
8778    + 1 /* .debug_macinfo */ \
8779    + 1 /* trailing zero */)
8780
8781   memset (&sections, 0, sizeof (sections));
8782   cleanups = make_cleanup (null_cleanup, 0);
8783
8784   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8785     {
8786       asection *sectp;
8787       uint32_t section_nr =
8788         read_4_bytes (dbfd,
8789                       htab->section_pool
8790                       + (section_index + i) * sizeof (uint32_t));
8791
8792       if (section_nr == 0)
8793         break;
8794       if (section_nr >= dwp_file->num_sections)
8795         {
8796           error (_("Dwarf Error: bad DWP hash table, section number too large"
8797                    " [in module %s]"),
8798                  dwp_file->name);
8799         }
8800
8801       sectp = dwp_file->elf_sections[section_nr];
8802       if (! locate_virtual_dwo_sections (sectp, &sections))
8803         {
8804           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8805                    " [in module %s]"),
8806                  dwp_file->name);
8807         }
8808     }
8809
8810   if (i < 2
8811       || sections.info_or_types.asection == NULL
8812       || sections.abbrev.asection == NULL)
8813     {
8814       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8815                " [in module %s]"),
8816              dwp_file->name);
8817     }
8818   if (i == MAX_NR_DWO_SECTIONS)
8819     {
8820       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8821                " [in module %s]"),
8822              dwp_file->name);
8823     }
8824
8825   /* It's easier for the rest of the code if we fake a struct dwo_file and
8826      have dwo_unit "live" in that.  At least for now.
8827
8828      The DWP file can be made up of a random collection of CUs and TUs.
8829      However, for each CU + set of TUs that came from the same original DWO
8830      file, we want to combine them back into a virtual DWO file to save space
8831      (fewer struct dwo_file objects to allocated).  Remember that for really
8832      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8833
8834   virtual_dwo_name =
8835     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8836                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8837                 sections.line.asection ? sections.line.asection->id : 0,
8838                 sections.loc.asection ? sections.loc.asection->id : 0,
8839                 (sections.str_offsets.asection
8840                 ? sections.str_offsets.asection->id
8841                 : 0));
8842   make_cleanup (xfree, virtual_dwo_name);
8843   /* Can we use an existing virtual DWO file?  */
8844   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
8845   /* Create one if necessary.  */
8846   if (*dwo_file_slot == NULL)
8847     {
8848       if (dwarf2_read_debug)
8849         {
8850           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8851                               virtual_dwo_name);
8852         }
8853       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8854       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
8855                                           virtual_dwo_name,
8856                                           strlen (virtual_dwo_name));
8857       dwo_file->comp_dir = comp_dir;
8858       dwo_file->sections.abbrev = sections.abbrev;
8859       dwo_file->sections.line = sections.line;
8860       dwo_file->sections.loc = sections.loc;
8861       dwo_file->sections.macinfo = sections.macinfo;
8862       dwo_file->sections.macro = sections.macro;
8863       dwo_file->sections.str_offsets = sections.str_offsets;
8864       /* The "str" section is global to the entire DWP file.  */
8865       dwo_file->sections.str = dwp_file->sections.str;
8866       /* The info or types section is assigned later to dwo_unit,
8867          there's no need to record it in dwo_file.
8868          Also, we can't simply record type sections in dwo_file because
8869          we record a pointer into the vector in dwo_unit.  As we collect more
8870          types we'll grow the vector and eventually have to reallocate space
8871          for it, invalidating all the pointers into the current copy.  */
8872       *dwo_file_slot = dwo_file;
8873     }
8874   else
8875     {
8876       if (dwarf2_read_debug)
8877         {
8878           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8879                               virtual_dwo_name);
8880         }
8881       dwo_file = *dwo_file_slot;
8882     }
8883   do_cleanups (cleanups);
8884
8885   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8886   dwo_unit->dwo_file = dwo_file;
8887   dwo_unit->signature = signature;
8888   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
8889                                      sizeof (struct dwarf2_section_info));
8890   *dwo_unit->section = sections.info_or_types;
8891   /* offset, length, type_offset_in_tu are set later.  */
8892
8893   return dwo_unit;
8894 }
8895
8896 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8897
8898 static struct dwo_unit *
8899 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8900                    const struct dwp_hash_table *htab,
8901                    const char *comp_dir,
8902                    ULONGEST signature, int is_debug_types)
8903 {
8904   bfd *dbfd = dwp_file->dbfd;
8905   uint32_t mask = htab->nr_slots - 1;
8906   uint32_t hash = signature & mask;
8907   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8908   unsigned int i;
8909   void **slot;
8910   struct dwo_unit find_dwo_cu, *dwo_cu;
8911
8912   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8913   find_dwo_cu.signature = signature;
8914   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8915
8916   if (*slot != NULL)
8917     return *slot;
8918
8919   /* Use a for loop so that we don't loop forever on bad debug info.  */
8920   for (i = 0; i < htab->nr_slots; ++i)
8921     {
8922       ULONGEST signature_in_table;
8923
8924       signature_in_table =
8925         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8926       if (signature_in_table == signature)
8927         {
8928           uint32_t section_index =
8929             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8930
8931           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8932                                      comp_dir, signature, is_debug_types);
8933           return *slot;
8934         }
8935       if (signature_in_table == 0)
8936         return NULL;
8937       hash = (hash + hash2) & mask;
8938     }
8939
8940   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8941            " [in module %s]"),
8942          dwp_file->name);
8943 }
8944
8945 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
8946    Open the file specified by FILE_NAME and hand it off to BFD for
8947    preliminary analysis.  Return a newly initialized bfd *, which
8948    includes a canonicalized copy of FILE_NAME.
8949    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8950    In case of trouble, return NULL.
8951    NOTE: This function is derived from symfile_bfd_open.  */
8952
8953 static bfd *
8954 try_open_dwop_file (const char *file_name, int is_dwp)
8955 {
8956   bfd *sym_bfd;
8957   int desc, flags;
8958   char *absolute_name;
8959
8960   flags = OPF_TRY_CWD_FIRST;
8961   if (is_dwp)
8962     flags |= OPF_SEARCH_IN_PATH;
8963   desc = openp (debug_file_directory, flags, file_name,
8964                 O_RDONLY | O_BINARY, &absolute_name);
8965   if (desc < 0)
8966     return NULL;
8967
8968   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8969   if (!sym_bfd)
8970     {
8971       xfree (absolute_name);
8972       return NULL;
8973     }
8974   xfree (absolute_name);
8975   bfd_set_cacheable (sym_bfd, 1);
8976
8977   if (!bfd_check_format (sym_bfd, bfd_object))
8978     {
8979       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8980       return NULL;
8981     }
8982
8983   return sym_bfd;
8984 }
8985
8986 /* Try to open DWO file FILE_NAME.
8987    COMP_DIR is the DW_AT_comp_dir attribute.
8988    The result is the bfd handle of the file.
8989    If there is a problem finding or opening the file, return NULL.
8990    Upon success, the canonicalized path of the file is stored in the bfd,
8991    same as symfile_bfd_open.  */
8992
8993 static bfd *
8994 open_dwo_file (const char *file_name, const char *comp_dir)
8995 {
8996   bfd *abfd;
8997
8998   if (IS_ABSOLUTE_PATH (file_name))
8999     return try_open_dwop_file (file_name, 0 /*is_dwp*/);
9000
9001   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9002
9003   if (comp_dir != NULL)
9004     {
9005       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9006
9007       /* NOTE: If comp_dir is a relative path, this will also try the
9008          search path, which seems useful.  */
9009       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/);
9010       xfree (path_to_try);
9011       if (abfd != NULL)
9012         return abfd;
9013     }
9014
9015   /* That didn't work, try debug-file-directory, which, despite its name,
9016      is a list of paths.  */
9017
9018   if (*debug_file_directory == '\0')
9019     return NULL;
9020
9021   return try_open_dwop_file (file_name, 0 /*is_dwp*/);
9022 }
9023
9024 /* This function is mapped across the sections and remembers the offset and
9025    size of each of the DWO debugging sections we are interested in.  */
9026
9027 static void
9028 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9029 {
9030   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9031   const struct dwop_section_names *names = &dwop_section_names;
9032
9033   if (section_is_p (sectp->name, &names->abbrev_dwo))
9034     {
9035       dwo_sections->abbrev.asection = sectp;
9036       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9037     }
9038   else if (section_is_p (sectp->name, &names->info_dwo))
9039     {
9040       dwo_sections->info.asection = sectp;
9041       dwo_sections->info.size = bfd_get_section_size (sectp);
9042     }
9043   else if (section_is_p (sectp->name, &names->line_dwo))
9044     {
9045       dwo_sections->line.asection = sectp;
9046       dwo_sections->line.size = bfd_get_section_size (sectp);
9047     }
9048   else if (section_is_p (sectp->name, &names->loc_dwo))
9049     {
9050       dwo_sections->loc.asection = sectp;
9051       dwo_sections->loc.size = bfd_get_section_size (sectp);
9052     }
9053   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9054     {
9055       dwo_sections->macinfo.asection = sectp;
9056       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9057     }
9058   else if (section_is_p (sectp->name, &names->macro_dwo))
9059     {
9060       dwo_sections->macro.asection = sectp;
9061       dwo_sections->macro.size = bfd_get_section_size (sectp);
9062     }
9063   else if (section_is_p (sectp->name, &names->str_dwo))
9064     {
9065       dwo_sections->str.asection = sectp;
9066       dwo_sections->str.size = bfd_get_section_size (sectp);
9067     }
9068   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9069     {
9070       dwo_sections->str_offsets.asection = sectp;
9071       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9072     }
9073   else if (section_is_p (sectp->name, &names->types_dwo))
9074     {
9075       struct dwarf2_section_info type_section;
9076
9077       memset (&type_section, 0, sizeof (type_section));
9078       type_section.asection = sectp;
9079       type_section.size = bfd_get_section_size (sectp);
9080       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9081                      &type_section);
9082     }
9083 }
9084
9085 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9086    by PER_CU.  This is for the non-DWP case.
9087    The result is NULL if DWO_NAME can't be found.  */
9088
9089 static struct dwo_file *
9090 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9091                         const char *dwo_name, const char *comp_dir)
9092 {
9093   struct objfile *objfile = dwarf2_per_objfile->objfile;
9094   struct dwo_file *dwo_file;
9095   bfd *dbfd;
9096   struct cleanup *cleanups;
9097
9098   dbfd = open_dwo_file (dwo_name, comp_dir);
9099   if (dbfd == NULL)
9100     {
9101       if (dwarf2_read_debug)
9102         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9103       return NULL;
9104     }
9105   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9106   dwo_file->dwo_name = dwo_name;
9107   dwo_file->comp_dir = comp_dir;
9108   dwo_file->dbfd = dbfd;
9109
9110   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9111
9112   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9113
9114   dwo_file->cu = create_dwo_cu (dwo_file);
9115
9116   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9117                                                  dwo_file->sections.types);
9118
9119   discard_cleanups (cleanups);
9120
9121   if (dwarf2_read_debug)
9122     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9123
9124   return dwo_file;
9125 }
9126
9127 /* This function is mapped across the sections and remembers the offset and
9128    size of each of the DWP debugging sections we are interested in.  */
9129
9130 static void
9131 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9132 {
9133   struct dwp_file *dwp_file = dwp_file_ptr;
9134   const struct dwop_section_names *names = &dwop_section_names;
9135   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9136
9137   /* Record the ELF section number for later lookup: this is what the
9138      .debug_cu_index,.debug_tu_index tables use.  */
9139   gdb_assert (elf_section_nr < dwp_file->num_sections);
9140   dwp_file->elf_sections[elf_section_nr] = sectp;
9141
9142   /* Look for specific sections that we need.  */
9143   if (section_is_p (sectp->name, &names->str_dwo))
9144     {
9145       dwp_file->sections.str.asection = sectp;
9146       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9147     }
9148   else if (section_is_p (sectp->name, &names->cu_index))
9149     {
9150       dwp_file->sections.cu_index.asection = sectp;
9151       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9152     }
9153   else if (section_is_p (sectp->name, &names->tu_index))
9154     {
9155       dwp_file->sections.tu_index.asection = sectp;
9156       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9157     }
9158 }
9159
9160 /* Hash function for dwp_file loaded CUs/TUs.  */
9161
9162 static hashval_t
9163 hash_dwp_loaded_cutus (const void *item)
9164 {
9165   const struct dwo_unit *dwo_unit = item;
9166
9167   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9168   return dwo_unit->signature;
9169 }
9170
9171 /* Equality function for dwp_file loaded CUs/TUs.  */
9172
9173 static int
9174 eq_dwp_loaded_cutus (const void *a, const void *b)
9175 {
9176   const struct dwo_unit *dua = a;
9177   const struct dwo_unit *dub = b;
9178
9179   return dua->signature == dub->signature;
9180 }
9181
9182 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9183
9184 static htab_t
9185 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9186 {
9187   return htab_create_alloc_ex (3,
9188                                hash_dwp_loaded_cutus,
9189                                eq_dwp_loaded_cutus,
9190                                NULL,
9191                                &objfile->objfile_obstack,
9192                                hashtab_obstack_allocate,
9193                                dummy_obstack_deallocate);
9194 }
9195
9196 /* Try to open DWP file FILE_NAME.
9197    The result is the bfd handle of the file.
9198    If there is a problem finding or opening the file, return NULL.
9199    Upon success, the canonicalized path of the file is stored in the bfd,
9200    same as symfile_bfd_open.  */
9201
9202 static bfd *
9203 open_dwp_file (const char *file_name)
9204 {
9205   return try_open_dwop_file (file_name, 1 /*is_dwp*/);
9206 }
9207
9208 /* Initialize the use of the DWP file for the current objfile.
9209    By convention the name of the DWP file is ${objfile}.dwp.
9210    The result is NULL if it can't be found.  */
9211
9212 static struct dwp_file *
9213 open_and_init_dwp_file (void)
9214 {
9215   struct objfile *objfile = dwarf2_per_objfile->objfile;
9216   struct dwp_file *dwp_file;
9217   char *dwp_name;
9218   bfd *dbfd;
9219   struct cleanup *cleanups;
9220
9221   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9222   cleanups = make_cleanup (xfree, dwp_name);
9223
9224   dbfd = open_dwp_file (dwp_name);
9225   if (dbfd == NULL)
9226     {
9227       if (dwarf2_read_debug)
9228         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9229       do_cleanups (cleanups);
9230       return NULL;
9231     }
9232   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9233   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9234                                   dwp_name, strlen (dwp_name));
9235   dwp_file->dbfd = dbfd;
9236   do_cleanups (cleanups);
9237
9238   /* +1: section 0 is unused */
9239   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9240   dwp_file->elf_sections =
9241     OBSTACK_CALLOC (&objfile->objfile_obstack,
9242                     dwp_file->num_sections, asection *);
9243
9244   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9245
9246   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9247
9248   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9249
9250   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9251
9252   if (dwarf2_read_debug)
9253     {
9254       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9255       fprintf_unfiltered (gdb_stdlog,
9256                           "    %u CUs, %u TUs\n",
9257                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9258                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9259     }
9260
9261   return dwp_file;
9262 }
9263
9264 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9265
9266 static struct dwp_file *
9267 get_dwp_file (void)
9268 {
9269   if (! dwarf2_per_objfile->dwp_checked)
9270     {
9271       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9272       dwarf2_per_objfile->dwp_checked = 1;
9273     }
9274   return dwarf2_per_objfile->dwp_file;
9275 }
9276
9277 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9278    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9279    or in the DWP file for the objfile, referenced by THIS_UNIT.
9280    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9281    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9282
9283    This is called, for example, when wanting to read a variable with a
9284    complex location.  Therefore we don't want to do file i/o for every call.
9285    Therefore we don't want to look for a DWO file on every call.
9286    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9287    then we check if we've already seen DWO_NAME, and only THEN do we check
9288    for a DWO file.
9289
9290    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9291    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9292
9293 static struct dwo_unit *
9294 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9295                  const char *dwo_name, const char *comp_dir,
9296                  ULONGEST signature, int is_debug_types)
9297 {
9298   struct objfile *objfile = dwarf2_per_objfile->objfile;
9299   const char *kind = is_debug_types ? "TU" : "CU";
9300   void **dwo_file_slot;
9301   struct dwo_file *dwo_file;
9302   struct dwp_file *dwp_file;
9303
9304   /* First see if there's a DWP file.
9305      If we have a DWP file but didn't find the DWO inside it, don't
9306      look for the original DWO file.  It makes gdb behave differently
9307      depending on whether one is debugging in the build tree.  */
9308
9309   dwp_file = get_dwp_file ();
9310   if (dwp_file != NULL)
9311     {
9312       const struct dwp_hash_table *dwp_htab =
9313         is_debug_types ? dwp_file->tus : dwp_file->cus;
9314
9315       if (dwp_htab != NULL)
9316         {
9317           struct dwo_unit *dwo_cutu =
9318             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9319                                signature, is_debug_types);
9320
9321           if (dwo_cutu != NULL)
9322             {
9323               if (dwarf2_read_debug)
9324                 {
9325                   fprintf_unfiltered (gdb_stdlog,
9326                                       "Virtual DWO %s %s found: @%s\n",
9327                                       kind, hex_string (signature),
9328                                       host_address_to_string (dwo_cutu));
9329                 }
9330               return dwo_cutu;
9331             }
9332         }
9333     }
9334   else
9335     {
9336       /* No DWP file, look for the DWO file.  */
9337
9338       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9339       if (*dwo_file_slot == NULL)
9340         {
9341           /* Read in the file and build a table of the CUs/TUs it contains.  */
9342           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9343         }
9344       /* NOTE: This will be NULL if unable to open the file.  */
9345       dwo_file = *dwo_file_slot;
9346
9347       if (dwo_file != NULL)
9348         {
9349           struct dwo_unit *dwo_cutu = NULL;
9350
9351           if (is_debug_types && dwo_file->tus)
9352             {
9353               struct dwo_unit find_dwo_cutu;
9354
9355               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9356               find_dwo_cutu.signature = signature;
9357               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9358             }
9359           else if (!is_debug_types && dwo_file->cu)
9360             {
9361               if (signature == dwo_file->cu->signature)
9362                 dwo_cutu = dwo_file->cu;
9363             }
9364
9365           if (dwo_cutu != NULL)
9366             {
9367               if (dwarf2_read_debug)
9368                 {
9369                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9370                                       kind, dwo_name, hex_string (signature),
9371                                       host_address_to_string (dwo_cutu));
9372                 }
9373               return dwo_cutu;
9374             }
9375         }
9376     }
9377
9378   /* We didn't find it.  This could mean a dwo_id mismatch, or
9379      someone deleted the DWO/DWP file, or the search path isn't set up
9380      correctly to find the file.  */
9381
9382   if (dwarf2_read_debug)
9383     {
9384       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9385                           kind, dwo_name, hex_string (signature));
9386     }
9387
9388   complaint (&symfile_complaints,
9389              _("Could not find DWO %s %s(%s) referenced by CU at offset 0x%x"
9390                " [in module %s]"),
9391              kind, dwo_name, hex_string (signature),
9392              this_unit->offset.sect_off, objfile->name);
9393   return NULL;
9394 }
9395
9396 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9397    See lookup_dwo_cutu_unit for details.  */
9398
9399 static struct dwo_unit *
9400 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9401                       const char *dwo_name, const char *comp_dir,
9402                       ULONGEST signature)
9403 {
9404   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9405 }
9406
9407 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9408    See lookup_dwo_cutu_unit for details.  */
9409
9410 static struct dwo_unit *
9411 lookup_dwo_type_unit (struct signatured_type *this_tu,
9412                       const char *dwo_name, const char *comp_dir)
9413 {
9414   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9415 }
9416
9417 /* Free all resources associated with DWO_FILE.
9418    Close the DWO file and munmap the sections.
9419    All memory should be on the objfile obstack.  */
9420
9421 static void
9422 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9423 {
9424   int ix;
9425   struct dwarf2_section_info *section;
9426
9427   /* Note: dbfd is NULL for virtual DWO files.  */
9428   gdb_bfd_unref (dwo_file->dbfd);
9429
9430   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9431 }
9432
9433 /* Wrapper for free_dwo_file for use in cleanups.  */
9434
9435 static void
9436 free_dwo_file_cleanup (void *arg)
9437 {
9438   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9439   struct objfile *objfile = dwarf2_per_objfile->objfile;
9440
9441   free_dwo_file (dwo_file, objfile);
9442 }
9443
9444 /* Traversal function for free_dwo_files.  */
9445
9446 static int
9447 free_dwo_file_from_slot (void **slot, void *info)
9448 {
9449   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9450   struct objfile *objfile = (struct objfile *) info;
9451
9452   free_dwo_file (dwo_file, objfile);
9453
9454   return 1;
9455 }
9456
9457 /* Free all resources associated with DWO_FILES.  */
9458
9459 static void
9460 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9461 {
9462   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9463 }
9464 \f
9465 /* Read in various DIEs.  */
9466
9467 /* qsort helper for inherit_abstract_dies.  */
9468
9469 static int
9470 unsigned_int_compar (const void *ap, const void *bp)
9471 {
9472   unsigned int a = *(unsigned int *) ap;
9473   unsigned int b = *(unsigned int *) bp;
9474
9475   return (a > b) - (b > a);
9476 }
9477
9478 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9479    Inherit only the children of the DW_AT_abstract_origin DIE not being
9480    already referenced by DW_AT_abstract_origin from the children of the
9481    current DIE.  */
9482
9483 static void
9484 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9485 {
9486   struct die_info *child_die;
9487   unsigned die_children_count;
9488   /* CU offsets which were referenced by children of the current DIE.  */
9489   sect_offset *offsets;
9490   sect_offset *offsets_end, *offsetp;
9491   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9492   struct die_info *origin_die;
9493   /* Iterator of the ORIGIN_DIE children.  */
9494   struct die_info *origin_child_die;
9495   struct cleanup *cleanups;
9496   struct attribute *attr;
9497   struct dwarf2_cu *origin_cu;
9498   struct pending **origin_previous_list_in_scope;
9499
9500   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9501   if (!attr)
9502     return;
9503
9504   /* Note that following die references may follow to a die in a
9505      different cu.  */
9506
9507   origin_cu = cu;
9508   origin_die = follow_die_ref (die, attr, &origin_cu);
9509
9510   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9511      symbols in.  */
9512   origin_previous_list_in_scope = origin_cu->list_in_scope;
9513   origin_cu->list_in_scope = cu->list_in_scope;
9514
9515   if (die->tag != origin_die->tag
9516       && !(die->tag == DW_TAG_inlined_subroutine
9517            && origin_die->tag == DW_TAG_subprogram))
9518     complaint (&symfile_complaints,
9519                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9520                die->offset.sect_off, origin_die->offset.sect_off);
9521
9522   child_die = die->child;
9523   die_children_count = 0;
9524   while (child_die && child_die->tag)
9525     {
9526       child_die = sibling_die (child_die);
9527       die_children_count++;
9528     }
9529   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9530   cleanups = make_cleanup (xfree, offsets);
9531
9532   offsets_end = offsets;
9533   child_die = die->child;
9534   while (child_die && child_die->tag)
9535     {
9536       /* For each CHILD_DIE, find the corresponding child of
9537          ORIGIN_DIE.  If there is more than one layer of
9538          DW_AT_abstract_origin, follow them all; there shouldn't be,
9539          but GCC versions at least through 4.4 generate this (GCC PR
9540          40573).  */
9541       struct die_info *child_origin_die = child_die;
9542       struct dwarf2_cu *child_origin_cu = cu;
9543
9544       while (1)
9545         {
9546           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9547                               child_origin_cu);
9548           if (attr == NULL)
9549             break;
9550           child_origin_die = follow_die_ref (child_origin_die, attr,
9551                                              &child_origin_cu);
9552         }
9553
9554       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9555          counterpart may exist.  */
9556       if (child_origin_die != child_die)
9557         {
9558           if (child_die->tag != child_origin_die->tag
9559               && !(child_die->tag == DW_TAG_inlined_subroutine
9560                    && child_origin_die->tag == DW_TAG_subprogram))
9561             complaint (&symfile_complaints,
9562                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9563                          "different tags"), child_die->offset.sect_off,
9564                        child_origin_die->offset.sect_off);
9565           if (child_origin_die->parent != origin_die)
9566             complaint (&symfile_complaints,
9567                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9568                          "different parents"), child_die->offset.sect_off,
9569                        child_origin_die->offset.sect_off);
9570           else
9571             *offsets_end++ = child_origin_die->offset;
9572         }
9573       child_die = sibling_die (child_die);
9574     }
9575   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9576          unsigned_int_compar);
9577   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9578     if (offsetp[-1].sect_off == offsetp->sect_off)
9579       complaint (&symfile_complaints,
9580                  _("Multiple children of DIE 0x%x refer "
9581                    "to DIE 0x%x as their abstract origin"),
9582                  die->offset.sect_off, offsetp->sect_off);
9583
9584   offsetp = offsets;
9585   origin_child_die = origin_die->child;
9586   while (origin_child_die && origin_child_die->tag)
9587     {
9588       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9589       while (offsetp < offsets_end
9590              && offsetp->sect_off < origin_child_die->offset.sect_off)
9591         offsetp++;
9592       if (offsetp >= offsets_end
9593           || offsetp->sect_off > origin_child_die->offset.sect_off)
9594         {
9595           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9596           process_die (origin_child_die, origin_cu);
9597         }
9598       origin_child_die = sibling_die (origin_child_die);
9599     }
9600   origin_cu->list_in_scope = origin_previous_list_in_scope;
9601
9602   do_cleanups (cleanups);
9603 }
9604
9605 static void
9606 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9607 {
9608   struct objfile *objfile = cu->objfile;
9609   struct context_stack *new;
9610   CORE_ADDR lowpc;
9611   CORE_ADDR highpc;
9612   struct die_info *child_die;
9613   struct attribute *attr, *call_line, *call_file;
9614   const char *name;
9615   CORE_ADDR baseaddr;
9616   struct block *block;
9617   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9618   VEC (symbolp) *template_args = NULL;
9619   struct template_symbol *templ_func = NULL;
9620
9621   if (inlined_func)
9622     {
9623       /* If we do not have call site information, we can't show the
9624          caller of this inlined function.  That's too confusing, so
9625          only use the scope for local variables.  */
9626       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9627       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9628       if (call_line == NULL || call_file == NULL)
9629         {
9630           read_lexical_block_scope (die, cu);
9631           return;
9632         }
9633     }
9634
9635   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9636
9637   name = dwarf2_name (die, cu);
9638
9639   /* Ignore functions with missing or empty names.  These are actually
9640      illegal according to the DWARF standard.  */
9641   if (name == NULL)
9642     {
9643       complaint (&symfile_complaints,
9644                  _("missing name for subprogram DIE at %d"),
9645                  die->offset.sect_off);
9646       return;
9647     }
9648
9649   /* Ignore functions with missing or invalid low and high pc attributes.  */
9650   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9651     {
9652       attr = dwarf2_attr (die, DW_AT_external, cu);
9653       if (!attr || !DW_UNSND (attr))
9654         complaint (&symfile_complaints,
9655                    _("cannot get low and high bounds "
9656                      "for subprogram DIE at %d"),
9657                    die->offset.sect_off);
9658       return;
9659     }
9660
9661   lowpc += baseaddr;
9662   highpc += baseaddr;
9663
9664   /* If we have any template arguments, then we must allocate a
9665      different sort of symbol.  */
9666   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9667     {
9668       if (child_die->tag == DW_TAG_template_type_param
9669           || child_die->tag == DW_TAG_template_value_param)
9670         {
9671           templ_func = allocate_template_symbol (objfile);
9672           templ_func->base.is_cplus_template_function = 1;
9673           break;
9674         }
9675     }
9676
9677   new = push_context (0, lowpc);
9678   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9679                                (struct symbol *) templ_func);
9680
9681   /* If there is a location expression for DW_AT_frame_base, record
9682      it.  */
9683   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9684   if (attr)
9685     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
9686
9687   cu->list_in_scope = &local_symbols;
9688
9689   if (die->child != NULL)
9690     {
9691       child_die = die->child;
9692       while (child_die && child_die->tag)
9693         {
9694           if (child_die->tag == DW_TAG_template_type_param
9695               || child_die->tag == DW_TAG_template_value_param)
9696             {
9697               struct symbol *arg = new_symbol (child_die, NULL, cu);
9698
9699               if (arg != NULL)
9700                 VEC_safe_push (symbolp, template_args, arg);
9701             }
9702           else
9703             process_die (child_die, cu);
9704           child_die = sibling_die (child_die);
9705         }
9706     }
9707
9708   inherit_abstract_dies (die, cu);
9709
9710   /* If we have a DW_AT_specification, we might need to import using
9711      directives from the context of the specification DIE.  See the
9712      comment in determine_prefix.  */
9713   if (cu->language == language_cplus
9714       && dwarf2_attr (die, DW_AT_specification, cu))
9715     {
9716       struct dwarf2_cu *spec_cu = cu;
9717       struct die_info *spec_die = die_specification (die, &spec_cu);
9718
9719       while (spec_die)
9720         {
9721           child_die = spec_die->child;
9722           while (child_die && child_die->tag)
9723             {
9724               if (child_die->tag == DW_TAG_imported_module)
9725                 process_die (child_die, spec_cu);
9726               child_die = sibling_die (child_die);
9727             }
9728
9729           /* In some cases, GCC generates specification DIEs that
9730              themselves contain DW_AT_specification attributes.  */
9731           spec_die = die_specification (spec_die, &spec_cu);
9732         }
9733     }
9734
9735   new = pop_context ();
9736   /* Make a block for the local symbols within.  */
9737   block = finish_block (new->name, &local_symbols, new->old_blocks,
9738                         lowpc, highpc, objfile);
9739
9740   /* For C++, set the block's scope.  */
9741   if ((cu->language == language_cplus || cu->language == language_fortran)
9742       && cu->processing_has_namespace_info)
9743     block_set_scope (block, determine_prefix (die, cu),
9744                      &objfile->objfile_obstack);
9745
9746   /* If we have address ranges, record them.  */
9747   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9748
9749   /* Attach template arguments to function.  */
9750   if (! VEC_empty (symbolp, template_args))
9751     {
9752       gdb_assert (templ_func != NULL);
9753
9754       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9755       templ_func->template_arguments
9756         = obstack_alloc (&objfile->objfile_obstack,
9757                          (templ_func->n_template_arguments
9758                           * sizeof (struct symbol *)));
9759       memcpy (templ_func->template_arguments,
9760               VEC_address (symbolp, template_args),
9761               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9762       VEC_free (symbolp, template_args);
9763     }
9764
9765   /* In C++, we can have functions nested inside functions (e.g., when
9766      a function declares a class that has methods).  This means that
9767      when we finish processing a function scope, we may need to go
9768      back to building a containing block's symbol lists.  */
9769   local_symbols = new->locals;
9770   using_directives = new->using_directives;
9771
9772   /* If we've finished processing a top-level function, subsequent
9773      symbols go in the file symbol list.  */
9774   if (outermost_context_p ())
9775     cu->list_in_scope = &file_symbols;
9776 }
9777
9778 /* Process all the DIES contained within a lexical block scope.  Start
9779    a new scope, process the dies, and then close the scope.  */
9780
9781 static void
9782 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9783 {
9784   struct objfile *objfile = cu->objfile;
9785   struct context_stack *new;
9786   CORE_ADDR lowpc, highpc;
9787   struct die_info *child_die;
9788   CORE_ADDR baseaddr;
9789
9790   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9791
9792   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9793   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9794      as multiple lexical blocks?  Handling children in a sane way would
9795      be nasty.  Might be easier to properly extend generic blocks to
9796      describe ranges.  */
9797   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9798     return;
9799   lowpc += baseaddr;
9800   highpc += baseaddr;
9801
9802   push_context (0, lowpc);
9803   if (die->child != NULL)
9804     {
9805       child_die = die->child;
9806       while (child_die && child_die->tag)
9807         {
9808           process_die (child_die, cu);
9809           child_die = sibling_die (child_die);
9810         }
9811     }
9812   new = pop_context ();
9813
9814   if (local_symbols != NULL || using_directives != NULL)
9815     {
9816       struct block *block
9817         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9818                         highpc, objfile);
9819
9820       /* Note that recording ranges after traversing children, as we
9821          do here, means that recording a parent's ranges entails
9822          walking across all its children's ranges as they appear in
9823          the address map, which is quadratic behavior.
9824
9825          It would be nicer to record the parent's ranges before
9826          traversing its children, simply overriding whatever you find
9827          there.  But since we don't even decide whether to create a
9828          block until after we've traversed its children, that's hard
9829          to do.  */
9830       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9831     }
9832   local_symbols = new->locals;
9833   using_directives = new->using_directives;
9834 }
9835
9836 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9837
9838 static void
9839 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9840 {
9841   struct objfile *objfile = cu->objfile;
9842   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9843   CORE_ADDR pc, baseaddr;
9844   struct attribute *attr;
9845   struct call_site *call_site, call_site_local;
9846   void **slot;
9847   int nparams;
9848   struct die_info *child_die;
9849
9850   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9851
9852   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9853   if (!attr)
9854     {
9855       complaint (&symfile_complaints,
9856                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9857                    "DIE 0x%x [in module %s]"),
9858                  die->offset.sect_off, objfile->name);
9859       return;
9860     }
9861   pc = DW_ADDR (attr) + baseaddr;
9862
9863   if (cu->call_site_htab == NULL)
9864     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9865                                                NULL, &objfile->objfile_obstack,
9866                                                hashtab_obstack_allocate, NULL);
9867   call_site_local.pc = pc;
9868   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9869   if (*slot != NULL)
9870     {
9871       complaint (&symfile_complaints,
9872                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9873                    "DIE 0x%x [in module %s]"),
9874                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9875       return;
9876     }
9877
9878   /* Count parameters at the caller.  */
9879
9880   nparams = 0;
9881   for (child_die = die->child; child_die && child_die->tag;
9882        child_die = sibling_die (child_die))
9883     {
9884       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9885         {
9886           complaint (&symfile_complaints,
9887                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9888                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9889                      child_die->tag, child_die->offset.sect_off, objfile->name);
9890           continue;
9891         }
9892
9893       nparams++;
9894     }
9895
9896   call_site = obstack_alloc (&objfile->objfile_obstack,
9897                              (sizeof (*call_site)
9898                               + (sizeof (*call_site->parameter)
9899                                  * (nparams - 1))));
9900   *slot = call_site;
9901   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9902   call_site->pc = pc;
9903
9904   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9905     {
9906       struct die_info *func_die;
9907
9908       /* Skip also over DW_TAG_inlined_subroutine.  */
9909       for (func_die = die->parent;
9910            func_die && func_die->tag != DW_TAG_subprogram
9911            && func_die->tag != DW_TAG_subroutine_type;
9912            func_die = func_die->parent);
9913
9914       /* DW_AT_GNU_all_call_sites is a superset
9915          of DW_AT_GNU_all_tail_call_sites.  */
9916       if (func_die
9917           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9918           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9919         {
9920           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9921              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9922              both the initial caller containing the real return address PC and
9923              the final callee containing the current PC of a chain of tail
9924              calls do not need to have the tail call list complete.  But any
9925              function candidate for a virtual tail call frame searched via
9926              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9927              determined unambiguously.  */
9928         }
9929       else
9930         {
9931           struct type *func_type = NULL;
9932
9933           if (func_die)
9934             func_type = get_die_type (func_die, cu);
9935           if (func_type != NULL)
9936             {
9937               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9938
9939               /* Enlist this call site to the function.  */
9940               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9941               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9942             }
9943           else
9944             complaint (&symfile_complaints,
9945                        _("Cannot find function owning DW_TAG_GNU_call_site "
9946                          "DIE 0x%x [in module %s]"),
9947                        die->offset.sect_off, objfile->name);
9948         }
9949     }
9950
9951   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9952   if (attr == NULL)
9953     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9954   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9955   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9956     /* Keep NULL DWARF_BLOCK.  */;
9957   else if (attr_form_is_block (attr))
9958     {
9959       struct dwarf2_locexpr_baton *dlbaton;
9960
9961       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9962       dlbaton->data = DW_BLOCK (attr)->data;
9963       dlbaton->size = DW_BLOCK (attr)->size;
9964       dlbaton->per_cu = cu->per_cu;
9965
9966       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9967     }
9968   else if (is_ref_attr (attr))
9969     {
9970       struct dwarf2_cu *target_cu = cu;
9971       struct die_info *target_die;
9972
9973       target_die = follow_die_ref (die, attr, &target_cu);
9974       gdb_assert (target_cu->objfile == objfile);
9975       if (die_is_declaration (target_die, target_cu))
9976         {
9977           const char *target_physname = NULL;
9978           struct attribute *target_attr;
9979
9980           /* Prefer the mangled name; otherwise compute the demangled one.  */
9981           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
9982           if (target_attr == NULL)
9983             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
9984                                        target_cu);
9985           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
9986             target_physname = DW_STRING (target_attr);
9987           else
9988             target_physname = dwarf2_physname (NULL, target_die, target_cu);
9989           if (target_physname == NULL)
9990             complaint (&symfile_complaints,
9991                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9992                          "physname, for referencing DIE 0x%x [in module %s]"),
9993                        die->offset.sect_off, objfile->name);
9994           else
9995             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9996         }
9997       else
9998         {
9999           CORE_ADDR lowpc;
10000
10001           /* DW_AT_entry_pc should be preferred.  */
10002           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10003             complaint (&symfile_complaints,
10004                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10005                          "low pc, for referencing DIE 0x%x [in module %s]"),
10006                        die->offset.sect_off, objfile->name);
10007           else
10008             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10009         }
10010     }
10011   else
10012     complaint (&symfile_complaints,
10013                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10014                  "block nor reference, for DIE 0x%x [in module %s]"),
10015                die->offset.sect_off, objfile->name);
10016
10017   call_site->per_cu = cu->per_cu;
10018
10019   for (child_die = die->child;
10020        child_die && child_die->tag;
10021        child_die = sibling_die (child_die))
10022     {
10023       struct call_site_parameter *parameter;
10024       struct attribute *loc, *origin;
10025
10026       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10027         {
10028           /* Already printed the complaint above.  */
10029           continue;
10030         }
10031
10032       gdb_assert (call_site->parameter_count < nparams);
10033       parameter = &call_site->parameter[call_site->parameter_count];
10034
10035       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10036          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10037          register is contained in DW_AT_GNU_call_site_value.  */
10038
10039       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10040       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10041       if (loc == NULL && origin != NULL && is_ref_attr (origin))
10042         {
10043           sect_offset offset;
10044
10045           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10046           offset = dwarf2_get_ref_die_offset (origin);
10047           if (!offset_in_cu_p (&cu->header, offset))
10048             {
10049               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10050                  binding can be done only inside one CU.  Such referenced DIE
10051                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10052               complaint (&symfile_complaints,
10053                          _("DW_AT_abstract_origin offset is not in CU for "
10054                            "DW_TAG_GNU_call_site child DIE 0x%x "
10055                            "[in module %s]"),
10056                          child_die->offset.sect_off, objfile->name);
10057               continue;
10058             }
10059           parameter->u.param_offset.cu_off = (offset.sect_off
10060                                               - cu->header.offset.sect_off);
10061         }
10062       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10063         {
10064           complaint (&symfile_complaints,
10065                      _("No DW_FORM_block* DW_AT_location for "
10066                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10067                      child_die->offset.sect_off, objfile->name);
10068           continue;
10069         }
10070       else
10071         {
10072           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10073             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10074           if (parameter->u.dwarf_reg != -1)
10075             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10076           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10077                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10078                                              &parameter->u.fb_offset))
10079             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10080           else
10081             {
10082               complaint (&symfile_complaints,
10083                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10084                            "for DW_FORM_block* DW_AT_location is supported for "
10085                            "DW_TAG_GNU_call_site child DIE 0x%x "
10086                            "[in module %s]"),
10087                          child_die->offset.sect_off, objfile->name);
10088               continue;
10089             }
10090         }
10091
10092       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10093       if (!attr_form_is_block (attr))
10094         {
10095           complaint (&symfile_complaints,
10096                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10097                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10098                      child_die->offset.sect_off, objfile->name);
10099           continue;
10100         }
10101       parameter->value = DW_BLOCK (attr)->data;
10102       parameter->value_size = DW_BLOCK (attr)->size;
10103
10104       /* Parameters are not pre-cleared by memset above.  */
10105       parameter->data_value = NULL;
10106       parameter->data_value_size = 0;
10107       call_site->parameter_count++;
10108
10109       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10110       if (attr)
10111         {
10112           if (!attr_form_is_block (attr))
10113             complaint (&symfile_complaints,
10114                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10115                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10116                        child_die->offset.sect_off, objfile->name);
10117           else
10118             {
10119               parameter->data_value = DW_BLOCK (attr)->data;
10120               parameter->data_value_size = DW_BLOCK (attr)->size;
10121             }
10122         }
10123     }
10124 }
10125
10126 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10127    Return 1 if the attributes are present and valid, otherwise, return 0.
10128    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10129
10130 static int
10131 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10132                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10133                     struct partial_symtab *ranges_pst)
10134 {
10135   struct objfile *objfile = cu->objfile;
10136   struct comp_unit_head *cu_header = &cu->header;
10137   bfd *obfd = objfile->obfd;
10138   unsigned int addr_size = cu_header->addr_size;
10139   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10140   /* Base address selection entry.  */
10141   CORE_ADDR base;
10142   int found_base;
10143   unsigned int dummy;
10144   const gdb_byte *buffer;
10145   CORE_ADDR marker;
10146   int low_set;
10147   CORE_ADDR low = 0;
10148   CORE_ADDR high = 0;
10149   CORE_ADDR baseaddr;
10150
10151   found_base = cu->base_known;
10152   base = cu->base_address;
10153
10154   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10155   if (offset >= dwarf2_per_objfile->ranges.size)
10156     {
10157       complaint (&symfile_complaints,
10158                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10159                  offset);
10160       return 0;
10161     }
10162   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10163
10164   /* Read in the largest possible address.  */
10165   marker = read_address (obfd, buffer, cu, &dummy);
10166   if ((marker & mask) == mask)
10167     {
10168       /* If we found the largest possible address, then
10169          read the base address.  */
10170       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10171       buffer += 2 * addr_size;
10172       offset += 2 * addr_size;
10173       found_base = 1;
10174     }
10175
10176   low_set = 0;
10177
10178   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10179
10180   while (1)
10181     {
10182       CORE_ADDR range_beginning, range_end;
10183
10184       range_beginning = read_address (obfd, buffer, cu, &dummy);
10185       buffer += addr_size;
10186       range_end = read_address (obfd, buffer, cu, &dummy);
10187       buffer += addr_size;
10188       offset += 2 * addr_size;
10189
10190       /* An end of list marker is a pair of zero addresses.  */
10191       if (range_beginning == 0 && range_end == 0)
10192         /* Found the end of list entry.  */
10193         break;
10194
10195       /* Each base address selection entry is a pair of 2 values.
10196          The first is the largest possible address, the second is
10197          the base address.  Check for a base address here.  */
10198       if ((range_beginning & mask) == mask)
10199         {
10200           /* If we found the largest possible address, then
10201              read the base address.  */
10202           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10203           found_base = 1;
10204           continue;
10205         }
10206
10207       if (!found_base)
10208         {
10209           /* We have no valid base address for the ranges
10210              data.  */
10211           complaint (&symfile_complaints,
10212                      _("Invalid .debug_ranges data (no base address)"));
10213           return 0;
10214         }
10215
10216       if (range_beginning > range_end)
10217         {
10218           /* Inverted range entries are invalid.  */
10219           complaint (&symfile_complaints,
10220                      _("Invalid .debug_ranges data (inverted range)"));
10221           return 0;
10222         }
10223
10224       /* Empty range entries have no effect.  */
10225       if (range_beginning == range_end)
10226         continue;
10227
10228       range_beginning += base;
10229       range_end += base;
10230
10231       /* A not-uncommon case of bad debug info.
10232          Don't pollute the addrmap with bad data.  */
10233       if (range_beginning + baseaddr == 0
10234           && !dwarf2_per_objfile->has_section_at_zero)
10235         {
10236           complaint (&symfile_complaints,
10237                      _(".debug_ranges entry has start address of zero"
10238                        " [in module %s]"), objfile->name);
10239           continue;
10240         }
10241
10242       if (ranges_pst != NULL)
10243         addrmap_set_empty (objfile->psymtabs_addrmap,
10244                            range_beginning + baseaddr,
10245                            range_end - 1 + baseaddr,
10246                            ranges_pst);
10247
10248       /* FIXME: This is recording everything as a low-high
10249          segment of consecutive addresses.  We should have a
10250          data structure for discontiguous block ranges
10251          instead.  */
10252       if (! low_set)
10253         {
10254           low = range_beginning;
10255           high = range_end;
10256           low_set = 1;
10257         }
10258       else
10259         {
10260           if (range_beginning < low)
10261             low = range_beginning;
10262           if (range_end > high)
10263             high = range_end;
10264         }
10265     }
10266
10267   if (! low_set)
10268     /* If the first entry is an end-of-list marker, the range
10269        describes an empty scope, i.e. no instructions.  */
10270     return 0;
10271
10272   if (low_return)
10273     *low_return = low;
10274   if (high_return)
10275     *high_return = high;
10276   return 1;
10277 }
10278
10279 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10280    are present and valid, otherwise, return 0.  Return -1 if the range is
10281    discontinuous, i.e. derived from DW_AT_ranges information.  */
10282
10283 static int
10284 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10285                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10286                       struct partial_symtab *pst)
10287 {
10288   struct attribute *attr;
10289   struct attribute *attr_high;
10290   CORE_ADDR low = 0;
10291   CORE_ADDR high = 0;
10292   int ret = 0;
10293
10294   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10295   if (attr_high)
10296     {
10297       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10298       if (attr)
10299         {
10300           low = DW_ADDR (attr);
10301           if (attr_high->form == DW_FORM_addr
10302               || attr_high->form == DW_FORM_GNU_addr_index)
10303             high = DW_ADDR (attr_high);
10304           else
10305             high = low + DW_UNSND (attr_high);
10306         }
10307       else
10308         /* Found high w/o low attribute.  */
10309         return 0;
10310
10311       /* Found consecutive range of addresses.  */
10312       ret = 1;
10313     }
10314   else
10315     {
10316       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10317       if (attr != NULL)
10318         {
10319           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10320              We take advantage of the fact that DW_AT_ranges does not appear
10321              in DW_TAG_compile_unit of DWO files.  */
10322           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10323           unsigned int ranges_offset = (DW_UNSND (attr)
10324                                         + (need_ranges_base
10325                                            ? cu->ranges_base
10326                                            : 0));
10327
10328           /* Value of the DW_AT_ranges attribute is the offset in the
10329              .debug_ranges section.  */
10330           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10331             return 0;
10332           /* Found discontinuous range of addresses.  */
10333           ret = -1;
10334         }
10335     }
10336
10337   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10338   if (high <= low)
10339     return 0;
10340
10341   /* When using the GNU linker, .gnu.linkonce. sections are used to
10342      eliminate duplicate copies of functions and vtables and such.
10343      The linker will arbitrarily choose one and discard the others.
10344      The AT_*_pc values for such functions refer to local labels in
10345      these sections.  If the section from that file was discarded, the
10346      labels are not in the output, so the relocs get a value of 0.
10347      If this is a discarded function, mark the pc bounds as invalid,
10348      so that GDB will ignore it.  */
10349   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10350     return 0;
10351
10352   *lowpc = low;
10353   if (highpc)
10354     *highpc = high;
10355   return ret;
10356 }
10357
10358 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10359    its low and high PC addresses.  Do nothing if these addresses could not
10360    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10361    and HIGHPC to the high address if greater than HIGHPC.  */
10362
10363 static void
10364 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10365                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10366                                  struct dwarf2_cu *cu)
10367 {
10368   CORE_ADDR low, high;
10369   struct die_info *child = die->child;
10370
10371   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10372     {
10373       *lowpc = min (*lowpc, low);
10374       *highpc = max (*highpc, high);
10375     }
10376
10377   /* If the language does not allow nested subprograms (either inside
10378      subprograms or lexical blocks), we're done.  */
10379   if (cu->language != language_ada)
10380     return;
10381
10382   /* Check all the children of the given DIE.  If it contains nested
10383      subprograms, then check their pc bounds.  Likewise, we need to
10384      check lexical blocks as well, as they may also contain subprogram
10385      definitions.  */
10386   while (child && child->tag)
10387     {
10388       if (child->tag == DW_TAG_subprogram
10389           || child->tag == DW_TAG_lexical_block)
10390         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10391       child = sibling_die (child);
10392     }
10393 }
10394
10395 /* Get the low and high pc's represented by the scope DIE, and store
10396    them in *LOWPC and *HIGHPC.  If the correct values can't be
10397    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10398
10399 static void
10400 get_scope_pc_bounds (struct die_info *die,
10401                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10402                      struct dwarf2_cu *cu)
10403 {
10404   CORE_ADDR best_low = (CORE_ADDR) -1;
10405   CORE_ADDR best_high = (CORE_ADDR) 0;
10406   CORE_ADDR current_low, current_high;
10407
10408   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10409     {
10410       best_low = current_low;
10411       best_high = current_high;
10412     }
10413   else
10414     {
10415       struct die_info *child = die->child;
10416
10417       while (child && child->tag)
10418         {
10419           switch (child->tag) {
10420           case DW_TAG_subprogram:
10421             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10422             break;
10423           case DW_TAG_namespace:
10424           case DW_TAG_module:
10425             /* FIXME: carlton/2004-01-16: Should we do this for
10426                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10427                that current GCC's always emit the DIEs corresponding
10428                to definitions of methods of classes as children of a
10429                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10430                the DIEs giving the declarations, which could be
10431                anywhere).  But I don't see any reason why the
10432                standards says that they have to be there.  */
10433             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10434
10435             if (current_low != ((CORE_ADDR) -1))
10436               {
10437                 best_low = min (best_low, current_low);
10438                 best_high = max (best_high, current_high);
10439               }
10440             break;
10441           default:
10442             /* Ignore.  */
10443             break;
10444           }
10445
10446           child = sibling_die (child);
10447         }
10448     }
10449
10450   *lowpc = best_low;
10451   *highpc = best_high;
10452 }
10453
10454 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10455    in DIE.  */
10456
10457 static void
10458 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10459                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10460 {
10461   struct objfile *objfile = cu->objfile;
10462   struct attribute *attr;
10463   struct attribute *attr_high;
10464
10465   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10466   if (attr_high)
10467     {
10468       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10469       if (attr)
10470         {
10471           CORE_ADDR low = DW_ADDR (attr);
10472           CORE_ADDR high;
10473           if (attr_high->form == DW_FORM_addr
10474               || attr_high->form == DW_FORM_GNU_addr_index)
10475             high = DW_ADDR (attr_high);
10476           else
10477             high = low + DW_UNSND (attr_high);
10478
10479           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10480         }
10481     }
10482
10483   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10484   if (attr)
10485     {
10486       bfd *obfd = objfile->obfd;
10487       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10488          We take advantage of the fact that DW_AT_ranges does not appear
10489          in DW_TAG_compile_unit of DWO files.  */
10490       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10491
10492       /* The value of the DW_AT_ranges attribute is the offset of the
10493          address range list in the .debug_ranges section.  */
10494       unsigned long offset = (DW_UNSND (attr)
10495                               + (need_ranges_base ? cu->ranges_base : 0));
10496       const gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10497
10498       /* For some target architectures, but not others, the
10499          read_address function sign-extends the addresses it returns.
10500          To recognize base address selection entries, we need a
10501          mask.  */
10502       unsigned int addr_size = cu->header.addr_size;
10503       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10504
10505       /* The base address, to which the next pair is relative.  Note
10506          that this 'base' is a DWARF concept: most entries in a range
10507          list are relative, to reduce the number of relocs against the
10508          debugging information.  This is separate from this function's
10509          'baseaddr' argument, which GDB uses to relocate debugging
10510          information from a shared library based on the address at
10511          which the library was loaded.  */
10512       CORE_ADDR base = cu->base_address;
10513       int base_known = cu->base_known;
10514
10515       gdb_assert (dwarf2_per_objfile->ranges.readin);
10516       if (offset >= dwarf2_per_objfile->ranges.size)
10517         {
10518           complaint (&symfile_complaints,
10519                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10520                      offset);
10521           return;
10522         }
10523
10524       for (;;)
10525         {
10526           unsigned int bytes_read;
10527           CORE_ADDR start, end;
10528
10529           start = read_address (obfd, buffer, cu, &bytes_read);
10530           buffer += bytes_read;
10531           end = read_address (obfd, buffer, cu, &bytes_read);
10532           buffer += bytes_read;
10533
10534           /* Did we find the end of the range list?  */
10535           if (start == 0 && end == 0)
10536             break;
10537
10538           /* Did we find a base address selection entry?  */
10539           else if ((start & base_select_mask) == base_select_mask)
10540             {
10541               base = end;
10542               base_known = 1;
10543             }
10544
10545           /* We found an ordinary address range.  */
10546           else
10547             {
10548               if (!base_known)
10549                 {
10550                   complaint (&symfile_complaints,
10551                              _("Invalid .debug_ranges data "
10552                                "(no base address)"));
10553                   return;
10554                 }
10555
10556               if (start > end)
10557                 {
10558                   /* Inverted range entries are invalid.  */
10559                   complaint (&symfile_complaints,
10560                              _("Invalid .debug_ranges data "
10561                                "(inverted range)"));
10562                   return;
10563                 }
10564
10565               /* Empty range entries have no effect.  */
10566               if (start == end)
10567                 continue;
10568
10569               start += base + baseaddr;
10570               end += base + baseaddr;
10571
10572               /* A not-uncommon case of bad debug info.
10573                  Don't pollute the addrmap with bad data.  */
10574               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10575                 {
10576                   complaint (&symfile_complaints,
10577                              _(".debug_ranges entry has start address of zero"
10578                                " [in module %s]"), objfile->name);
10579                   continue;
10580                 }
10581
10582               record_block_range (block, start, end - 1);
10583             }
10584         }
10585     }
10586 }
10587
10588 /* Check whether the producer field indicates either of GCC < 4.6, or the
10589    Intel C/C++ compiler, and cache the result in CU.  */
10590
10591 static void
10592 check_producer (struct dwarf2_cu *cu)
10593 {
10594   const char *cs;
10595   int major, minor, release;
10596
10597   if (cu->producer == NULL)
10598     {
10599       /* For unknown compilers expect their behavior is DWARF version
10600          compliant.
10601
10602          GCC started to support .debug_types sections by -gdwarf-4 since
10603          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10604          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10605          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10606          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10607     }
10608   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10609     {
10610       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10611
10612       cs = &cu->producer[strlen ("GNU ")];
10613       while (*cs && !isdigit (*cs))
10614         cs++;
10615       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10616         {
10617           /* Not recognized as GCC.  */
10618         }
10619       else
10620         {
10621           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10622           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10623         }
10624     }
10625   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10626     cu->producer_is_icc = 1;
10627   else
10628     {
10629       /* For other non-GCC compilers, expect their behavior is DWARF version
10630          compliant.  */
10631     }
10632
10633   cu->checked_producer = 1;
10634 }
10635
10636 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10637    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10638    during 4.6.0 experimental.  */
10639
10640 static int
10641 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10642 {
10643   if (!cu->checked_producer)
10644     check_producer (cu);
10645
10646   return cu->producer_is_gxx_lt_4_6;
10647 }
10648
10649 /* Return the default accessibility type if it is not overriden by
10650    DW_AT_accessibility.  */
10651
10652 static enum dwarf_access_attribute
10653 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10654 {
10655   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10656     {
10657       /* The default DWARF 2 accessibility for members is public, the default
10658          accessibility for inheritance is private.  */
10659
10660       if (die->tag != DW_TAG_inheritance)
10661         return DW_ACCESS_public;
10662       else
10663         return DW_ACCESS_private;
10664     }
10665   else
10666     {
10667       /* DWARF 3+ defines the default accessibility a different way.  The same
10668          rules apply now for DW_TAG_inheritance as for the members and it only
10669          depends on the container kind.  */
10670
10671       if (die->parent->tag == DW_TAG_class_type)
10672         return DW_ACCESS_private;
10673       else
10674         return DW_ACCESS_public;
10675     }
10676 }
10677
10678 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10679    offset.  If the attribute was not found return 0, otherwise return
10680    1.  If it was found but could not properly be handled, set *OFFSET
10681    to 0.  */
10682
10683 static int
10684 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10685                              LONGEST *offset)
10686 {
10687   struct attribute *attr;
10688
10689   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10690   if (attr != NULL)
10691     {
10692       *offset = 0;
10693
10694       /* Note that we do not check for a section offset first here.
10695          This is because DW_AT_data_member_location is new in DWARF 4,
10696          so if we see it, we can assume that a constant form is really
10697          a constant and not a section offset.  */
10698       if (attr_form_is_constant (attr))
10699         *offset = dwarf2_get_attr_constant_value (attr, 0);
10700       else if (attr_form_is_section_offset (attr))
10701         dwarf2_complex_location_expr_complaint ();
10702       else if (attr_form_is_block (attr))
10703         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10704       else
10705         dwarf2_complex_location_expr_complaint ();
10706
10707       return 1;
10708     }
10709
10710   return 0;
10711 }
10712
10713 /* Add an aggregate field to the field list.  */
10714
10715 static void
10716 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10717                   struct dwarf2_cu *cu)
10718 {
10719   struct objfile *objfile = cu->objfile;
10720   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10721   struct nextfield *new_field;
10722   struct attribute *attr;
10723   struct field *fp;
10724   const char *fieldname = "";
10725
10726   /* Allocate a new field list entry and link it in.  */
10727   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10728   make_cleanup (xfree, new_field);
10729   memset (new_field, 0, sizeof (struct nextfield));
10730
10731   if (die->tag == DW_TAG_inheritance)
10732     {
10733       new_field->next = fip->baseclasses;
10734       fip->baseclasses = new_field;
10735     }
10736   else
10737     {
10738       new_field->next = fip->fields;
10739       fip->fields = new_field;
10740     }
10741   fip->nfields++;
10742
10743   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10744   if (attr)
10745     new_field->accessibility = DW_UNSND (attr);
10746   else
10747     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10748   if (new_field->accessibility != DW_ACCESS_public)
10749     fip->non_public_fields = 1;
10750
10751   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10752   if (attr)
10753     new_field->virtuality = DW_UNSND (attr);
10754   else
10755     new_field->virtuality = DW_VIRTUALITY_none;
10756
10757   fp = &new_field->field;
10758
10759   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10760     {
10761       LONGEST offset;
10762
10763       /* Data member other than a C++ static data member.  */
10764
10765       /* Get type of field.  */
10766       fp->type = die_type (die, cu);
10767
10768       SET_FIELD_BITPOS (*fp, 0);
10769
10770       /* Get bit size of field (zero if none).  */
10771       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10772       if (attr)
10773         {
10774           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10775         }
10776       else
10777         {
10778           FIELD_BITSIZE (*fp) = 0;
10779         }
10780
10781       /* Get bit offset of field.  */
10782       if (handle_data_member_location (die, cu, &offset))
10783         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10784       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10785       if (attr)
10786         {
10787           if (gdbarch_bits_big_endian (gdbarch))
10788             {
10789               /* For big endian bits, the DW_AT_bit_offset gives the
10790                  additional bit offset from the MSB of the containing
10791                  anonymous object to the MSB of the field.  We don't
10792                  have to do anything special since we don't need to
10793                  know the size of the anonymous object.  */
10794               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10795             }
10796           else
10797             {
10798               /* For little endian bits, compute the bit offset to the
10799                  MSB of the anonymous object, subtract off the number of
10800                  bits from the MSB of the field to the MSB of the
10801                  object, and then subtract off the number of bits of
10802                  the field itself.  The result is the bit offset of
10803                  the LSB of the field.  */
10804               int anonymous_size;
10805               int bit_offset = DW_UNSND (attr);
10806
10807               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10808               if (attr)
10809                 {
10810                   /* The size of the anonymous object containing
10811                      the bit field is explicit, so use the
10812                      indicated size (in bytes).  */
10813                   anonymous_size = DW_UNSND (attr);
10814                 }
10815               else
10816                 {
10817                   /* The size of the anonymous object containing
10818                      the bit field must be inferred from the type
10819                      attribute of the data member containing the
10820                      bit field.  */
10821                   anonymous_size = TYPE_LENGTH (fp->type);
10822                 }
10823               SET_FIELD_BITPOS (*fp,
10824                                 (FIELD_BITPOS (*fp)
10825                                  + anonymous_size * bits_per_byte
10826                                  - bit_offset - FIELD_BITSIZE (*fp)));
10827             }
10828         }
10829
10830       /* Get name of field.  */
10831       fieldname = dwarf2_name (die, cu);
10832       if (fieldname == NULL)
10833         fieldname = "";
10834
10835       /* The name is already allocated along with this objfile, so we don't
10836          need to duplicate it for the type.  */
10837       fp->name = fieldname;
10838
10839       /* Change accessibility for artificial fields (e.g. virtual table
10840          pointer or virtual base class pointer) to private.  */
10841       if (dwarf2_attr (die, DW_AT_artificial, cu))
10842         {
10843           FIELD_ARTIFICIAL (*fp) = 1;
10844           new_field->accessibility = DW_ACCESS_private;
10845           fip->non_public_fields = 1;
10846         }
10847     }
10848   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10849     {
10850       /* C++ static member.  */
10851
10852       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10853          is a declaration, but all versions of G++ as of this writing
10854          (so through at least 3.2.1) incorrectly generate
10855          DW_TAG_variable tags.  */
10856
10857       const char *physname;
10858
10859       /* Get name of field.  */
10860       fieldname = dwarf2_name (die, cu);
10861       if (fieldname == NULL)
10862         return;
10863
10864       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10865       if (attr
10866           /* Only create a symbol if this is an external value.
10867              new_symbol checks this and puts the value in the global symbol
10868              table, which we want.  If it is not external, new_symbol
10869              will try to put the value in cu->list_in_scope which is wrong.  */
10870           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10871         {
10872           /* A static const member, not much different than an enum as far as
10873              we're concerned, except that we can support more types.  */
10874           new_symbol (die, NULL, cu);
10875         }
10876
10877       /* Get physical name.  */
10878       physname = dwarf2_physname (fieldname, die, cu);
10879
10880       /* The name is already allocated along with this objfile, so we don't
10881          need to duplicate it for the type.  */
10882       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10883       FIELD_TYPE (*fp) = die_type (die, cu);
10884       FIELD_NAME (*fp) = fieldname;
10885     }
10886   else if (die->tag == DW_TAG_inheritance)
10887     {
10888       LONGEST offset;
10889
10890       /* C++ base class field.  */
10891       if (handle_data_member_location (die, cu, &offset))
10892         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10893       FIELD_BITSIZE (*fp) = 0;
10894       FIELD_TYPE (*fp) = die_type (die, cu);
10895       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10896       fip->nbaseclasses++;
10897     }
10898 }
10899
10900 /* Add a typedef defined in the scope of the FIP's class.  */
10901
10902 static void
10903 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10904                     struct dwarf2_cu *cu)
10905 {
10906   struct objfile *objfile = cu->objfile;
10907   struct typedef_field_list *new_field;
10908   struct attribute *attr;
10909   struct typedef_field *fp;
10910   char *fieldname = "";
10911
10912   /* Allocate a new field list entry and link it in.  */
10913   new_field = xzalloc (sizeof (*new_field));
10914   make_cleanup (xfree, new_field);
10915
10916   gdb_assert (die->tag == DW_TAG_typedef);
10917
10918   fp = &new_field->field;
10919
10920   /* Get name of field.  */
10921   fp->name = dwarf2_name (die, cu);
10922   if (fp->name == NULL)
10923     return;
10924
10925   fp->type = read_type_die (die, cu);
10926
10927   new_field->next = fip->typedef_field_list;
10928   fip->typedef_field_list = new_field;
10929   fip->typedef_field_list_count++;
10930 }
10931
10932 /* Create the vector of fields, and attach it to the type.  */
10933
10934 static void
10935 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10936                               struct dwarf2_cu *cu)
10937 {
10938   int nfields = fip->nfields;
10939
10940   /* Record the field count, allocate space for the array of fields,
10941      and create blank accessibility bitfields if necessary.  */
10942   TYPE_NFIELDS (type) = nfields;
10943   TYPE_FIELDS (type) = (struct field *)
10944     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10945   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10946
10947   if (fip->non_public_fields && cu->language != language_ada)
10948     {
10949       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10950
10951       TYPE_FIELD_PRIVATE_BITS (type) =
10952         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10953       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10954
10955       TYPE_FIELD_PROTECTED_BITS (type) =
10956         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10957       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10958
10959       TYPE_FIELD_IGNORE_BITS (type) =
10960         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10961       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10962     }
10963
10964   /* If the type has baseclasses, allocate and clear a bit vector for
10965      TYPE_FIELD_VIRTUAL_BITS.  */
10966   if (fip->nbaseclasses && cu->language != language_ada)
10967     {
10968       int num_bytes = B_BYTES (fip->nbaseclasses);
10969       unsigned char *pointer;
10970
10971       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10972       pointer = TYPE_ALLOC (type, num_bytes);
10973       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10974       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10975       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10976     }
10977
10978   /* Copy the saved-up fields into the field vector.  Start from the head of
10979      the list, adding to the tail of the field array, so that they end up in
10980      the same order in the array in which they were added to the list.  */
10981   while (nfields-- > 0)
10982     {
10983       struct nextfield *fieldp;
10984
10985       if (fip->fields)
10986         {
10987           fieldp = fip->fields;
10988           fip->fields = fieldp->next;
10989         }
10990       else
10991         {
10992           fieldp = fip->baseclasses;
10993           fip->baseclasses = fieldp->next;
10994         }
10995
10996       TYPE_FIELD (type, nfields) = fieldp->field;
10997       switch (fieldp->accessibility)
10998         {
10999         case DW_ACCESS_private:
11000           if (cu->language != language_ada)
11001             SET_TYPE_FIELD_PRIVATE (type, nfields);
11002           break;
11003
11004         case DW_ACCESS_protected:
11005           if (cu->language != language_ada)
11006             SET_TYPE_FIELD_PROTECTED (type, nfields);
11007           break;
11008
11009         case DW_ACCESS_public:
11010           break;
11011
11012         default:
11013           /* Unknown accessibility.  Complain and treat it as public.  */
11014           {
11015             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11016                        fieldp->accessibility);
11017           }
11018           break;
11019         }
11020       if (nfields < fip->nbaseclasses)
11021         {
11022           switch (fieldp->virtuality)
11023             {
11024             case DW_VIRTUALITY_virtual:
11025             case DW_VIRTUALITY_pure_virtual:
11026               if (cu->language == language_ada)
11027                 error (_("unexpected virtuality in component of Ada type"));
11028               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11029               break;
11030             }
11031         }
11032     }
11033 }
11034
11035 /* Return true if this member function is a constructor, false
11036    otherwise.  */
11037
11038 static int
11039 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11040 {
11041   const char *fieldname;
11042   const char *typename;
11043   int len;
11044
11045   if (die->parent == NULL)
11046     return 0;
11047
11048   if (die->parent->tag != DW_TAG_structure_type
11049       && die->parent->tag != DW_TAG_union_type
11050       && die->parent->tag != DW_TAG_class_type)
11051     return 0;
11052
11053   fieldname = dwarf2_name (die, cu);
11054   typename = dwarf2_name (die->parent, cu);
11055   if (fieldname == NULL || typename == NULL)
11056     return 0;
11057
11058   len = strlen (fieldname);
11059   return (strncmp (fieldname, typename, len) == 0
11060           && (typename[len] == '\0' || typename[len] == '<'));
11061 }
11062
11063 /* Add a member function to the proper fieldlist.  */
11064
11065 static void
11066 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11067                       struct type *type, struct dwarf2_cu *cu)
11068 {
11069   struct objfile *objfile = cu->objfile;
11070   struct attribute *attr;
11071   struct fnfieldlist *flp;
11072   int i;
11073   struct fn_field *fnp;
11074   const char *fieldname;
11075   struct nextfnfield *new_fnfield;
11076   struct type *this_type;
11077   enum dwarf_access_attribute accessibility;
11078
11079   if (cu->language == language_ada)
11080     error (_("unexpected member function in Ada type"));
11081
11082   /* Get name of member function.  */
11083   fieldname = dwarf2_name (die, cu);
11084   if (fieldname == NULL)
11085     return;
11086
11087   /* Look up member function name in fieldlist.  */
11088   for (i = 0; i < fip->nfnfields; i++)
11089     {
11090       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11091         break;
11092     }
11093
11094   /* Create new list element if necessary.  */
11095   if (i < fip->nfnfields)
11096     flp = &fip->fnfieldlists[i];
11097   else
11098     {
11099       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11100         {
11101           fip->fnfieldlists = (struct fnfieldlist *)
11102             xrealloc (fip->fnfieldlists,
11103                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11104                       * sizeof (struct fnfieldlist));
11105           if (fip->nfnfields == 0)
11106             make_cleanup (free_current_contents, &fip->fnfieldlists);
11107         }
11108       flp = &fip->fnfieldlists[fip->nfnfields];
11109       flp->name = fieldname;
11110       flp->length = 0;
11111       flp->head = NULL;
11112       i = fip->nfnfields++;
11113     }
11114
11115   /* Create a new member function field and chain it to the field list
11116      entry.  */
11117   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11118   make_cleanup (xfree, new_fnfield);
11119   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11120   new_fnfield->next = flp->head;
11121   flp->head = new_fnfield;
11122   flp->length++;
11123
11124   /* Fill in the member function field info.  */
11125   fnp = &new_fnfield->fnfield;
11126
11127   /* Delay processing of the physname until later.  */
11128   if (cu->language == language_cplus || cu->language == language_java)
11129     {
11130       add_to_method_list (type, i, flp->length - 1, fieldname,
11131                           die, cu);
11132     }
11133   else
11134     {
11135       const char *physname = dwarf2_physname (fieldname, die, cu);
11136       fnp->physname = physname ? physname : "";
11137     }
11138
11139   fnp->type = alloc_type (objfile);
11140   this_type = read_type_die (die, cu);
11141   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11142     {
11143       int nparams = TYPE_NFIELDS (this_type);
11144
11145       /* TYPE is the domain of this method, and THIS_TYPE is the type
11146            of the method itself (TYPE_CODE_METHOD).  */
11147       smash_to_method_type (fnp->type, type,
11148                             TYPE_TARGET_TYPE (this_type),
11149                             TYPE_FIELDS (this_type),
11150                             TYPE_NFIELDS (this_type),
11151                             TYPE_VARARGS (this_type));
11152
11153       /* Handle static member functions.
11154          Dwarf2 has no clean way to discern C++ static and non-static
11155          member functions.  G++ helps GDB by marking the first
11156          parameter for non-static member functions (which is the this
11157          pointer) as artificial.  We obtain this information from
11158          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11159       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11160         fnp->voffset = VOFFSET_STATIC;
11161     }
11162   else
11163     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11164                dwarf2_full_name (fieldname, die, cu));
11165
11166   /* Get fcontext from DW_AT_containing_type if present.  */
11167   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11168     fnp->fcontext = die_containing_type (die, cu);
11169
11170   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11171      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11172
11173   /* Get accessibility.  */
11174   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11175   if (attr)
11176     accessibility = DW_UNSND (attr);
11177   else
11178     accessibility = dwarf2_default_access_attribute (die, cu);
11179   switch (accessibility)
11180     {
11181     case DW_ACCESS_private:
11182       fnp->is_private = 1;
11183       break;
11184     case DW_ACCESS_protected:
11185       fnp->is_protected = 1;
11186       break;
11187     }
11188
11189   /* Check for artificial methods.  */
11190   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11191   if (attr && DW_UNSND (attr) != 0)
11192     fnp->is_artificial = 1;
11193
11194   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11195
11196   /* Get index in virtual function table if it is a virtual member
11197      function.  For older versions of GCC, this is an offset in the
11198      appropriate virtual table, as specified by DW_AT_containing_type.
11199      For everyone else, it is an expression to be evaluated relative
11200      to the object address.  */
11201
11202   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11203   if (attr)
11204     {
11205       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11206         {
11207           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11208             {
11209               /* Old-style GCC.  */
11210               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11211             }
11212           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11213                    || (DW_BLOCK (attr)->size > 1
11214                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11215                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11216             {
11217               struct dwarf_block blk;
11218               int offset;
11219
11220               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11221                         ? 1 : 2);
11222               blk.size = DW_BLOCK (attr)->size - offset;
11223               blk.data = DW_BLOCK (attr)->data + offset;
11224               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11225               if ((fnp->voffset % cu->header.addr_size) != 0)
11226                 dwarf2_complex_location_expr_complaint ();
11227               else
11228                 fnp->voffset /= cu->header.addr_size;
11229               fnp->voffset += 2;
11230             }
11231           else
11232             dwarf2_complex_location_expr_complaint ();
11233
11234           if (!fnp->fcontext)
11235             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11236         }
11237       else if (attr_form_is_section_offset (attr))
11238         {
11239           dwarf2_complex_location_expr_complaint ();
11240         }
11241       else
11242         {
11243           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11244                                                  fieldname);
11245         }
11246     }
11247   else
11248     {
11249       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11250       if (attr && DW_UNSND (attr))
11251         {
11252           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11253           complaint (&symfile_complaints,
11254                      _("Member function \"%s\" (offset %d) is virtual "
11255                        "but the vtable offset is not specified"),
11256                      fieldname, die->offset.sect_off);
11257           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11258           TYPE_CPLUS_DYNAMIC (type) = 1;
11259         }
11260     }
11261 }
11262
11263 /* Create the vector of member function fields, and attach it to the type.  */
11264
11265 static void
11266 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11267                                  struct dwarf2_cu *cu)
11268 {
11269   struct fnfieldlist *flp;
11270   int i;
11271
11272   if (cu->language == language_ada)
11273     error (_("unexpected member functions in Ada type"));
11274
11275   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11276   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11277     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11278
11279   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11280     {
11281       struct nextfnfield *nfp = flp->head;
11282       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11283       int k;
11284
11285       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11286       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11287       fn_flp->fn_fields = (struct fn_field *)
11288         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11289       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11290         fn_flp->fn_fields[k] = nfp->fnfield;
11291     }
11292
11293   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11294 }
11295
11296 /* Returns non-zero if NAME is the name of a vtable member in CU's
11297    language, zero otherwise.  */
11298 static int
11299 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11300 {
11301   static const char vptr[] = "_vptr";
11302   static const char vtable[] = "vtable";
11303
11304   /* Look for the C++ and Java forms of the vtable.  */
11305   if ((cu->language == language_java
11306        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11307        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11308        && is_cplus_marker (name[sizeof (vptr) - 1])))
11309     return 1;
11310
11311   return 0;
11312 }
11313
11314 /* GCC outputs unnamed structures that are really pointers to member
11315    functions, with the ABI-specified layout.  If TYPE describes
11316    such a structure, smash it into a member function type.
11317
11318    GCC shouldn't do this; it should just output pointer to member DIEs.
11319    This is GCC PR debug/28767.  */
11320
11321 static void
11322 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11323 {
11324   struct type *pfn_type, *domain_type, *new_type;
11325
11326   /* Check for a structure with no name and two children.  */
11327   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11328     return;
11329
11330   /* Check for __pfn and __delta members.  */
11331   if (TYPE_FIELD_NAME (type, 0) == NULL
11332       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11333       || TYPE_FIELD_NAME (type, 1) == NULL
11334       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11335     return;
11336
11337   /* Find the type of the method.  */
11338   pfn_type = TYPE_FIELD_TYPE (type, 0);
11339   if (pfn_type == NULL
11340       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11341       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11342     return;
11343
11344   /* Look for the "this" argument.  */
11345   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11346   if (TYPE_NFIELDS (pfn_type) == 0
11347       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11348       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11349     return;
11350
11351   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11352   new_type = alloc_type (objfile);
11353   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11354                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11355                         TYPE_VARARGS (pfn_type));
11356   smash_to_methodptr_type (type, new_type);
11357 }
11358
11359 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11360    (icc).  */
11361
11362 static int
11363 producer_is_icc (struct dwarf2_cu *cu)
11364 {
11365   if (!cu->checked_producer)
11366     check_producer (cu);
11367
11368   return cu->producer_is_icc;
11369 }
11370
11371 /* Called when we find the DIE that starts a structure or union scope
11372    (definition) to create a type for the structure or union.  Fill in
11373    the type's name and general properties; the members will not be
11374    processed until process_structure_scope.
11375
11376    NOTE: we need to call these functions regardless of whether or not the
11377    DIE has a DW_AT_name attribute, since it might be an anonymous
11378    structure or union.  This gets the type entered into our set of
11379    user defined types.
11380
11381    However, if the structure is incomplete (an opaque struct/union)
11382    then suppress creating a symbol table entry for it since gdb only
11383    wants to find the one with the complete definition.  Note that if
11384    it is complete, we just call new_symbol, which does it's own
11385    checking about whether the struct/union is anonymous or not (and
11386    suppresses creating a symbol table entry itself).  */
11387
11388 static struct type *
11389 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11390 {
11391   struct objfile *objfile = cu->objfile;
11392   struct type *type;
11393   struct attribute *attr;
11394   const char *name;
11395
11396   /* If the definition of this type lives in .debug_types, read that type.
11397      Don't follow DW_AT_specification though, that will take us back up
11398      the chain and we want to go down.  */
11399   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11400   if (attr)
11401     {
11402       type = get_DW_AT_signature_type (die, attr, cu);
11403
11404       /* The type's CU may not be the same as CU.
11405          Ensure TYPE is recorded with CU in die_type_hash.  */
11406       return set_die_type (die, type, cu);
11407     }
11408
11409   type = alloc_type (objfile);
11410   INIT_CPLUS_SPECIFIC (type);
11411
11412   name = dwarf2_name (die, cu);
11413   if (name != NULL)
11414     {
11415       if (cu->language == language_cplus
11416           || cu->language == language_java)
11417         {
11418           const char *full_name = dwarf2_full_name (name, die, cu);
11419
11420           /* dwarf2_full_name might have already finished building the DIE's
11421              type.  If so, there is no need to continue.  */
11422           if (get_die_type (die, cu) != NULL)
11423             return get_die_type (die, cu);
11424
11425           TYPE_TAG_NAME (type) = full_name;
11426           if (die->tag == DW_TAG_structure_type
11427               || die->tag == DW_TAG_class_type)
11428             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11429         }
11430       else
11431         {
11432           /* The name is already allocated along with this objfile, so
11433              we don't need to duplicate it for the type.  */
11434           TYPE_TAG_NAME (type) = name;
11435           if (die->tag == DW_TAG_class_type)
11436             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11437         }
11438     }
11439
11440   if (die->tag == DW_TAG_structure_type)
11441     {
11442       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11443     }
11444   else if (die->tag == DW_TAG_union_type)
11445     {
11446       TYPE_CODE (type) = TYPE_CODE_UNION;
11447     }
11448   else
11449     {
11450       TYPE_CODE (type) = TYPE_CODE_CLASS;
11451     }
11452
11453   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11454     TYPE_DECLARED_CLASS (type) = 1;
11455
11456   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11457   if (attr)
11458     {
11459       TYPE_LENGTH (type) = DW_UNSND (attr);
11460     }
11461   else
11462     {
11463       TYPE_LENGTH (type) = 0;
11464     }
11465
11466   if (producer_is_icc (cu))
11467     {
11468       /* ICC does not output the required DW_AT_declaration
11469          on incomplete types, but gives them a size of zero.  */
11470     }
11471   else
11472     TYPE_STUB_SUPPORTED (type) = 1;
11473
11474   if (die_is_declaration (die, cu))
11475     TYPE_STUB (type) = 1;
11476   else if (attr == NULL && die->child == NULL
11477            && producer_is_realview (cu->producer))
11478     /* RealView does not output the required DW_AT_declaration
11479        on incomplete types.  */
11480     TYPE_STUB (type) = 1;
11481
11482   /* We need to add the type field to the die immediately so we don't
11483      infinitely recurse when dealing with pointers to the structure
11484      type within the structure itself.  */
11485   set_die_type (die, type, cu);
11486
11487   /* set_die_type should be already done.  */
11488   set_descriptive_type (type, die, cu);
11489
11490   return type;
11491 }
11492
11493 /* Finish creating a structure or union type, including filling in
11494    its members and creating a symbol for it.  */
11495
11496 static void
11497 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11498 {
11499   struct objfile *objfile = cu->objfile;
11500   struct die_info *child_die = die->child;
11501   struct type *type;
11502
11503   type = get_die_type (die, cu);
11504   if (type == NULL)
11505     type = read_structure_type (die, cu);
11506
11507   if (die->child != NULL && ! die_is_declaration (die, cu))
11508     {
11509       struct field_info fi;
11510       struct die_info *child_die;
11511       VEC (symbolp) *template_args = NULL;
11512       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11513
11514       memset (&fi, 0, sizeof (struct field_info));
11515
11516       child_die = die->child;
11517
11518       while (child_die && child_die->tag)
11519         {
11520           if (child_die->tag == DW_TAG_member
11521               || child_die->tag == DW_TAG_variable)
11522             {
11523               /* NOTE: carlton/2002-11-05: A C++ static data member
11524                  should be a DW_TAG_member that is a declaration, but
11525                  all versions of G++ as of this writing (so through at
11526                  least 3.2.1) incorrectly generate DW_TAG_variable
11527                  tags for them instead.  */
11528               dwarf2_add_field (&fi, child_die, cu);
11529             }
11530           else if (child_die->tag == DW_TAG_subprogram)
11531             {
11532               /* C++ member function.  */
11533               dwarf2_add_member_fn (&fi, child_die, type, cu);
11534             }
11535           else if (child_die->tag == DW_TAG_inheritance)
11536             {
11537               /* C++ base class field.  */
11538               dwarf2_add_field (&fi, child_die, cu);
11539             }
11540           else if (child_die->tag == DW_TAG_typedef)
11541             dwarf2_add_typedef (&fi, child_die, cu);
11542           else if (child_die->tag == DW_TAG_template_type_param
11543                    || child_die->tag == DW_TAG_template_value_param)
11544             {
11545               struct symbol *arg = new_symbol (child_die, NULL, cu);
11546
11547               if (arg != NULL)
11548                 VEC_safe_push (symbolp, template_args, arg);
11549             }
11550
11551           child_die = sibling_die (child_die);
11552         }
11553
11554       /* Attach template arguments to type.  */
11555       if (! VEC_empty (symbolp, template_args))
11556         {
11557           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11558           TYPE_N_TEMPLATE_ARGUMENTS (type)
11559             = VEC_length (symbolp, template_args);
11560           TYPE_TEMPLATE_ARGUMENTS (type)
11561             = obstack_alloc (&objfile->objfile_obstack,
11562                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11563                               * sizeof (struct symbol *)));
11564           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11565                   VEC_address (symbolp, template_args),
11566                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11567                    * sizeof (struct symbol *)));
11568           VEC_free (symbolp, template_args);
11569         }
11570
11571       /* Attach fields and member functions to the type.  */
11572       if (fi.nfields)
11573         dwarf2_attach_fields_to_type (&fi, type, cu);
11574       if (fi.nfnfields)
11575         {
11576           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11577
11578           /* Get the type which refers to the base class (possibly this
11579              class itself) which contains the vtable pointer for the current
11580              class from the DW_AT_containing_type attribute.  This use of
11581              DW_AT_containing_type is a GNU extension.  */
11582
11583           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11584             {
11585               struct type *t = die_containing_type (die, cu);
11586
11587               TYPE_VPTR_BASETYPE (type) = t;
11588               if (type == t)
11589                 {
11590                   int i;
11591
11592                   /* Our own class provides vtbl ptr.  */
11593                   for (i = TYPE_NFIELDS (t) - 1;
11594                        i >= TYPE_N_BASECLASSES (t);
11595                        --i)
11596                     {
11597                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11598
11599                       if (is_vtable_name (fieldname, cu))
11600                         {
11601                           TYPE_VPTR_FIELDNO (type) = i;
11602                           break;
11603                         }
11604                     }
11605
11606                   /* Complain if virtual function table field not found.  */
11607                   if (i < TYPE_N_BASECLASSES (t))
11608                     complaint (&symfile_complaints,
11609                                _("virtual function table pointer "
11610                                  "not found when defining class '%s'"),
11611                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11612                                "");
11613                 }
11614               else
11615                 {
11616                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11617                 }
11618             }
11619           else if (cu->producer
11620                    && strncmp (cu->producer,
11621                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11622             {
11623               /* The IBM XLC compiler does not provide direct indication
11624                  of the containing type, but the vtable pointer is
11625                  always named __vfp.  */
11626
11627               int i;
11628
11629               for (i = TYPE_NFIELDS (type) - 1;
11630                    i >= TYPE_N_BASECLASSES (type);
11631                    --i)
11632                 {
11633                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11634                     {
11635                       TYPE_VPTR_FIELDNO (type) = i;
11636                       TYPE_VPTR_BASETYPE (type) = type;
11637                       break;
11638                     }
11639                 }
11640             }
11641         }
11642
11643       /* Copy fi.typedef_field_list linked list elements content into the
11644          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11645       if (fi.typedef_field_list)
11646         {
11647           int i = fi.typedef_field_list_count;
11648
11649           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11650           TYPE_TYPEDEF_FIELD_ARRAY (type)
11651             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11652           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11653
11654           /* Reverse the list order to keep the debug info elements order.  */
11655           while (--i >= 0)
11656             {
11657               struct typedef_field *dest, *src;
11658
11659               dest = &TYPE_TYPEDEF_FIELD (type, i);
11660               src = &fi.typedef_field_list->field;
11661               fi.typedef_field_list = fi.typedef_field_list->next;
11662               *dest = *src;
11663             }
11664         }
11665
11666       do_cleanups (back_to);
11667
11668       if (HAVE_CPLUS_STRUCT (type))
11669         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11670     }
11671
11672   quirk_gcc_member_function_pointer (type, objfile);
11673
11674   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11675      snapshots) has been known to create a die giving a declaration
11676      for a class that has, as a child, a die giving a definition for a
11677      nested class.  So we have to process our children even if the
11678      current die is a declaration.  Normally, of course, a declaration
11679      won't have any children at all.  */
11680
11681   while (child_die != NULL && child_die->tag)
11682     {
11683       if (child_die->tag == DW_TAG_member
11684           || child_die->tag == DW_TAG_variable
11685           || child_die->tag == DW_TAG_inheritance
11686           || child_die->tag == DW_TAG_template_value_param
11687           || child_die->tag == DW_TAG_template_type_param)
11688         {
11689           /* Do nothing.  */
11690         }
11691       else
11692         process_die (child_die, cu);
11693
11694       child_die = sibling_die (child_die);
11695     }
11696
11697   /* Do not consider external references.  According to the DWARF standard,
11698      these DIEs are identified by the fact that they have no byte_size
11699      attribute, and a declaration attribute.  */
11700   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11701       || !die_is_declaration (die, cu))
11702     new_symbol (die, type, cu);
11703 }
11704
11705 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11706    complete the type's fields yet, or create any symbols.  */
11707
11708 static struct type *
11709 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11710 {
11711   struct objfile *objfile = cu->objfile;
11712   struct type *type;
11713   struct attribute *attr;
11714   const char *name;
11715
11716   /* If the definition of this type lives in .debug_types, read that type.
11717      Don't follow DW_AT_specification though, that will take us back up
11718      the chain and we want to go down.  */
11719   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11720   if (attr)
11721     {
11722       type = get_DW_AT_signature_type (die, attr, cu);
11723
11724       /* The type's CU may not be the same as CU.
11725          Ensure TYPE is recorded with CU in die_type_hash.  */
11726       return set_die_type (die, type, cu);
11727     }
11728
11729   type = alloc_type (objfile);
11730
11731   TYPE_CODE (type) = TYPE_CODE_ENUM;
11732   name = dwarf2_full_name (NULL, die, cu);
11733   if (name != NULL)
11734     TYPE_TAG_NAME (type) = name;
11735
11736   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11737   if (attr)
11738     {
11739       TYPE_LENGTH (type) = DW_UNSND (attr);
11740     }
11741   else
11742     {
11743       TYPE_LENGTH (type) = 0;
11744     }
11745
11746   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11747      declared as private in the package spec, and then defined only
11748      inside the package body.  Such types are known as Taft Amendment
11749      Types.  When another package uses such a type, an incomplete DIE
11750      may be generated by the compiler.  */
11751   if (die_is_declaration (die, cu))
11752     TYPE_STUB (type) = 1;
11753
11754   return set_die_type (die, type, cu);
11755 }
11756
11757 /* Given a pointer to a die which begins an enumeration, process all
11758    the dies that define the members of the enumeration, and create the
11759    symbol for the enumeration type.
11760
11761    NOTE: We reverse the order of the element list.  */
11762
11763 static void
11764 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11765 {
11766   struct type *this_type;
11767
11768   this_type = get_die_type (die, cu);
11769   if (this_type == NULL)
11770     this_type = read_enumeration_type (die, cu);
11771
11772   if (die->child != NULL)
11773     {
11774       struct die_info *child_die;
11775       struct symbol *sym;
11776       struct field *fields = NULL;
11777       int num_fields = 0;
11778       int unsigned_enum = 1;
11779       const char *name;
11780       int flag_enum = 1;
11781       ULONGEST mask = 0;
11782
11783       child_die = die->child;
11784       while (child_die && child_die->tag)
11785         {
11786           if (child_die->tag != DW_TAG_enumerator)
11787             {
11788               process_die (child_die, cu);
11789             }
11790           else
11791             {
11792               name = dwarf2_name (child_die, cu);
11793               if (name)
11794                 {
11795                   sym = new_symbol (child_die, this_type, cu);
11796                   if (SYMBOL_VALUE (sym) < 0)
11797                     {
11798                       unsigned_enum = 0;
11799                       flag_enum = 0;
11800                     }
11801                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11802                     flag_enum = 0;
11803                   else
11804                     mask |= SYMBOL_VALUE (sym);
11805
11806                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11807                     {
11808                       fields = (struct field *)
11809                         xrealloc (fields,
11810                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11811                                   * sizeof (struct field));
11812                     }
11813
11814                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11815                   FIELD_TYPE (fields[num_fields]) = NULL;
11816                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11817                   FIELD_BITSIZE (fields[num_fields]) = 0;
11818
11819                   num_fields++;
11820                 }
11821             }
11822
11823           child_die = sibling_die (child_die);
11824         }
11825
11826       if (num_fields)
11827         {
11828           TYPE_NFIELDS (this_type) = num_fields;
11829           TYPE_FIELDS (this_type) = (struct field *)
11830             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11831           memcpy (TYPE_FIELDS (this_type), fields,
11832                   sizeof (struct field) * num_fields);
11833           xfree (fields);
11834         }
11835       if (unsigned_enum)
11836         TYPE_UNSIGNED (this_type) = 1;
11837       if (flag_enum)
11838         TYPE_FLAG_ENUM (this_type) = 1;
11839     }
11840
11841   /* If we are reading an enum from a .debug_types unit, and the enum
11842      is a declaration, and the enum is not the signatured type in the
11843      unit, then we do not want to add a symbol for it.  Adding a
11844      symbol would in some cases obscure the true definition of the
11845      enum, giving users an incomplete type when the definition is
11846      actually available.  Note that we do not want to do this for all
11847      enums which are just declarations, because C++0x allows forward
11848      enum declarations.  */
11849   if (cu->per_cu->is_debug_types
11850       && die_is_declaration (die, cu))
11851     {
11852       struct signatured_type *sig_type;
11853
11854       sig_type = (struct signatured_type *) cu->per_cu;
11855       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11856       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11857         return;
11858     }
11859
11860   new_symbol (die, this_type, cu);
11861 }
11862
11863 /* Extract all information from a DW_TAG_array_type DIE and put it in
11864    the DIE's type field.  For now, this only handles one dimensional
11865    arrays.  */
11866
11867 static struct type *
11868 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11869 {
11870   struct objfile *objfile = cu->objfile;
11871   struct die_info *child_die;
11872   struct type *type;
11873   struct type *element_type, *range_type, *index_type;
11874   struct type **range_types = NULL;
11875   struct attribute *attr;
11876   int ndim = 0;
11877   struct cleanup *back_to;
11878   const char *name;
11879
11880   element_type = die_type (die, cu);
11881
11882   /* The die_type call above may have already set the type for this DIE.  */
11883   type = get_die_type (die, cu);
11884   if (type)
11885     return type;
11886
11887   /* Irix 6.2 native cc creates array types without children for
11888      arrays with unspecified length.  */
11889   if (die->child == NULL)
11890     {
11891       index_type = objfile_type (objfile)->builtin_int;
11892       range_type = create_range_type (NULL, index_type, 0, -1);
11893       type = create_array_type (NULL, element_type, range_type);
11894       return set_die_type (die, type, cu);
11895     }
11896
11897   back_to = make_cleanup (null_cleanup, NULL);
11898   child_die = die->child;
11899   while (child_die && child_die->tag)
11900     {
11901       if (child_die->tag == DW_TAG_subrange_type)
11902         {
11903           struct type *child_type = read_type_die (child_die, cu);
11904
11905           if (child_type != NULL)
11906             {
11907               /* The range type was succesfully read.  Save it for the
11908                  array type creation.  */
11909               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11910                 {
11911                   range_types = (struct type **)
11912                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11913                               * sizeof (struct type *));
11914                   if (ndim == 0)
11915                     make_cleanup (free_current_contents, &range_types);
11916                 }
11917               range_types[ndim++] = child_type;
11918             }
11919         }
11920       child_die = sibling_die (child_die);
11921     }
11922
11923   /* Dwarf2 dimensions are output from left to right, create the
11924      necessary array types in backwards order.  */
11925
11926   type = element_type;
11927
11928   if (read_array_order (die, cu) == DW_ORD_col_major)
11929     {
11930       int i = 0;
11931
11932       while (i < ndim)
11933         type = create_array_type (NULL, type, range_types[i++]);
11934     }
11935   else
11936     {
11937       while (ndim-- > 0)
11938         type = create_array_type (NULL, type, range_types[ndim]);
11939     }
11940
11941   /* Understand Dwarf2 support for vector types (like they occur on
11942      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11943      array type.  This is not part of the Dwarf2/3 standard yet, but a
11944      custom vendor extension.  The main difference between a regular
11945      array and the vector variant is that vectors are passed by value
11946      to functions.  */
11947   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11948   if (attr)
11949     make_vector_type (type);
11950
11951   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11952      implementation may choose to implement triple vectors using this
11953      attribute.  */
11954   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11955   if (attr)
11956     {
11957       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11958         TYPE_LENGTH (type) = DW_UNSND (attr);
11959       else
11960         complaint (&symfile_complaints,
11961                    _("DW_AT_byte_size for array type smaller "
11962                      "than the total size of elements"));
11963     }
11964
11965   name = dwarf2_name (die, cu);
11966   if (name)
11967     TYPE_NAME (type) = name;
11968
11969   /* Install the type in the die.  */
11970   set_die_type (die, type, cu);
11971
11972   /* set_die_type should be already done.  */
11973   set_descriptive_type (type, die, cu);
11974
11975   do_cleanups (back_to);
11976
11977   return type;
11978 }
11979
11980 static enum dwarf_array_dim_ordering
11981 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11982 {
11983   struct attribute *attr;
11984
11985   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11986
11987   if (attr) return DW_SND (attr);
11988
11989   /* GNU F77 is a special case, as at 08/2004 array type info is the
11990      opposite order to the dwarf2 specification, but data is still
11991      laid out as per normal fortran.
11992
11993      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11994      version checking.  */
11995
11996   if (cu->language == language_fortran
11997       && cu->producer && strstr (cu->producer, "GNU F77"))
11998     {
11999       return DW_ORD_row_major;
12000     }
12001
12002   switch (cu->language_defn->la_array_ordering)
12003     {
12004     case array_column_major:
12005       return DW_ORD_col_major;
12006     case array_row_major:
12007     default:
12008       return DW_ORD_row_major;
12009     };
12010 }
12011
12012 /* Extract all information from a DW_TAG_set_type DIE and put it in
12013    the DIE's type field.  */
12014
12015 static struct type *
12016 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12017 {
12018   struct type *domain_type, *set_type;
12019   struct attribute *attr;
12020
12021   domain_type = die_type (die, cu);
12022
12023   /* The die_type call above may have already set the type for this DIE.  */
12024   set_type = get_die_type (die, cu);
12025   if (set_type)
12026     return set_type;
12027
12028   set_type = create_set_type (NULL, domain_type);
12029
12030   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12031   if (attr)
12032     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12033
12034   return set_die_type (die, set_type, cu);
12035 }
12036
12037 /* A helper for read_common_block that creates a locexpr baton.
12038    SYM is the symbol which we are marking as computed.
12039    COMMON_DIE is the DIE for the common block.
12040    COMMON_LOC is the location expression attribute for the common
12041    block itself.
12042    MEMBER_LOC is the location expression attribute for the particular
12043    member of the common block that we are processing.
12044    CU is the CU from which the above come.  */
12045
12046 static void
12047 mark_common_block_symbol_computed (struct symbol *sym,
12048                                    struct die_info *common_die,
12049                                    struct attribute *common_loc,
12050                                    struct attribute *member_loc,
12051                                    struct dwarf2_cu *cu)
12052 {
12053   struct objfile *objfile = dwarf2_per_objfile->objfile;
12054   struct dwarf2_locexpr_baton *baton;
12055   gdb_byte *ptr;
12056   unsigned int cu_off;
12057   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12058   LONGEST offset = 0;
12059
12060   gdb_assert (common_loc && member_loc);
12061   gdb_assert (attr_form_is_block (common_loc));
12062   gdb_assert (attr_form_is_block (member_loc)
12063               || attr_form_is_constant (member_loc));
12064
12065   baton = obstack_alloc (&objfile->objfile_obstack,
12066                          sizeof (struct dwarf2_locexpr_baton));
12067   baton->per_cu = cu->per_cu;
12068   gdb_assert (baton->per_cu);
12069
12070   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12071
12072   if (attr_form_is_constant (member_loc))
12073     {
12074       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12075       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12076     }
12077   else
12078     baton->size += DW_BLOCK (member_loc)->size;
12079
12080   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12081   baton->data = ptr;
12082
12083   *ptr++ = DW_OP_call4;
12084   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12085   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12086   ptr += 4;
12087
12088   if (attr_form_is_constant (member_loc))
12089     {
12090       *ptr++ = DW_OP_addr;
12091       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12092       ptr += cu->header.addr_size;
12093     }
12094   else
12095     {
12096       /* We have to copy the data here, because DW_OP_call4 will only
12097          use a DW_AT_location attribute.  */
12098       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12099       ptr += DW_BLOCK (member_loc)->size;
12100     }
12101
12102   *ptr++ = DW_OP_plus;
12103   gdb_assert (ptr - baton->data == baton->size);
12104
12105   SYMBOL_LOCATION_BATON (sym) = baton;
12106   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12107 }
12108
12109 /* Create appropriate locally-scoped variables for all the
12110    DW_TAG_common_block entries.  Also create a struct common_block
12111    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12112    is used to sepate the common blocks name namespace from regular
12113    variable names.  */
12114
12115 static void
12116 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12117 {
12118   struct attribute *attr;
12119
12120   attr = dwarf2_attr (die, DW_AT_location, cu);
12121   if (attr)
12122     {
12123       /* Support the .debug_loc offsets.  */
12124       if (attr_form_is_block (attr))
12125         {
12126           /* Ok.  */
12127         }
12128       else if (attr_form_is_section_offset (attr))
12129         {
12130           dwarf2_complex_location_expr_complaint ();
12131           attr = NULL;
12132         }
12133       else
12134         {
12135           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12136                                                  "common block member");
12137           attr = NULL;
12138         }
12139     }
12140
12141   if (die->child != NULL)
12142     {
12143       struct objfile *objfile = cu->objfile;
12144       struct die_info *child_die;
12145       size_t n_entries = 0, size;
12146       struct common_block *common_block;
12147       struct symbol *sym;
12148
12149       for (child_die = die->child;
12150            child_die && child_die->tag;
12151            child_die = sibling_die (child_die))
12152         ++n_entries;
12153
12154       size = (sizeof (struct common_block)
12155               + (n_entries - 1) * sizeof (struct symbol *));
12156       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12157       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12158       common_block->n_entries = 0;
12159
12160       for (child_die = die->child;
12161            child_die && child_die->tag;
12162            child_die = sibling_die (child_die))
12163         {
12164           /* Create the symbol in the DW_TAG_common_block block in the current
12165              symbol scope.  */
12166           sym = new_symbol (child_die, NULL, cu);
12167           if (sym != NULL)
12168             {
12169               struct attribute *member_loc;
12170
12171               common_block->contents[common_block->n_entries++] = sym;
12172
12173               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12174                                         cu);
12175               if (member_loc)
12176                 {
12177                   /* GDB has handled this for a long time, but it is
12178                      not specified by DWARF.  It seems to have been
12179                      emitted by gfortran at least as recently as:
12180                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12181                   complaint (&symfile_complaints,
12182                              _("Variable in common block has "
12183                                "DW_AT_data_member_location "
12184                                "- DIE at 0x%x [in module %s]"),
12185                              child_die->offset.sect_off, cu->objfile->name);
12186
12187                   if (attr_form_is_section_offset (member_loc))
12188                     dwarf2_complex_location_expr_complaint ();
12189                   else if (attr_form_is_constant (member_loc)
12190                            || attr_form_is_block (member_loc))
12191                     {
12192                       if (attr)
12193                         mark_common_block_symbol_computed (sym, die, attr,
12194                                                            member_loc, cu);
12195                     }
12196                   else
12197                     dwarf2_complex_location_expr_complaint ();
12198                 }
12199             }
12200         }
12201
12202       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12203       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12204     }
12205 }
12206
12207 /* Create a type for a C++ namespace.  */
12208
12209 static struct type *
12210 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12211 {
12212   struct objfile *objfile = cu->objfile;
12213   const char *previous_prefix, *name;
12214   int is_anonymous;
12215   struct type *type;
12216
12217   /* For extensions, reuse the type of the original namespace.  */
12218   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12219     {
12220       struct die_info *ext_die;
12221       struct dwarf2_cu *ext_cu = cu;
12222
12223       ext_die = dwarf2_extension (die, &ext_cu);
12224       type = read_type_die (ext_die, ext_cu);
12225
12226       /* EXT_CU may not be the same as CU.
12227          Ensure TYPE is recorded with CU in die_type_hash.  */
12228       return set_die_type (die, type, cu);
12229     }
12230
12231   name = namespace_name (die, &is_anonymous, cu);
12232
12233   /* Now build the name of the current namespace.  */
12234
12235   previous_prefix = determine_prefix (die, cu);
12236   if (previous_prefix[0] != '\0')
12237     name = typename_concat (&objfile->objfile_obstack,
12238                             previous_prefix, name, 0, cu);
12239
12240   /* Create the type.  */
12241   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12242                     objfile);
12243   TYPE_NAME (type) = name;
12244   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12245
12246   return set_die_type (die, type, cu);
12247 }
12248
12249 /* Read a C++ namespace.  */
12250
12251 static void
12252 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12253 {
12254   struct objfile *objfile = cu->objfile;
12255   int is_anonymous;
12256
12257   /* Add a symbol associated to this if we haven't seen the namespace
12258      before.  Also, add a using directive if it's an anonymous
12259      namespace.  */
12260
12261   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12262     {
12263       struct type *type;
12264
12265       type = read_type_die (die, cu);
12266       new_symbol (die, type, cu);
12267
12268       namespace_name (die, &is_anonymous, cu);
12269       if (is_anonymous)
12270         {
12271           const char *previous_prefix = determine_prefix (die, cu);
12272
12273           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12274                                   NULL, NULL, 0, &objfile->objfile_obstack);
12275         }
12276     }
12277
12278   if (die->child != NULL)
12279     {
12280       struct die_info *child_die = die->child;
12281
12282       while (child_die && child_die->tag)
12283         {
12284           process_die (child_die, cu);
12285           child_die = sibling_die (child_die);
12286         }
12287     }
12288 }
12289
12290 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12291    imported module.  Still we need that type as local Fortran "use ... only"
12292    declaration imports depend on the created type in determine_prefix.  */
12293
12294 static struct type *
12295 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12296 {
12297   struct objfile *objfile = cu->objfile;
12298   const char *module_name;
12299   struct type *type;
12300
12301   module_name = dwarf2_name (die, cu);
12302   if (!module_name)
12303     complaint (&symfile_complaints,
12304                _("DW_TAG_module has no name, offset 0x%x"),
12305                die->offset.sect_off);
12306   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12307
12308   /* determine_prefix uses TYPE_TAG_NAME.  */
12309   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12310
12311   return set_die_type (die, type, cu);
12312 }
12313
12314 /* Read a Fortran module.  */
12315
12316 static void
12317 read_module (struct die_info *die, struct dwarf2_cu *cu)
12318 {
12319   struct die_info *child_die = die->child;
12320
12321   while (child_die && child_die->tag)
12322     {
12323       process_die (child_die, cu);
12324       child_die = sibling_die (child_die);
12325     }
12326 }
12327
12328 /* Return the name of the namespace represented by DIE.  Set
12329    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12330    namespace.  */
12331
12332 static const char *
12333 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12334 {
12335   struct die_info *current_die;
12336   const char *name = NULL;
12337
12338   /* Loop through the extensions until we find a name.  */
12339
12340   for (current_die = die;
12341        current_die != NULL;
12342        current_die = dwarf2_extension (die, &cu))
12343     {
12344       name = dwarf2_name (current_die, cu);
12345       if (name != NULL)
12346         break;
12347     }
12348
12349   /* Is it an anonymous namespace?  */
12350
12351   *is_anonymous = (name == NULL);
12352   if (*is_anonymous)
12353     name = CP_ANONYMOUS_NAMESPACE_STR;
12354
12355   return name;
12356 }
12357
12358 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12359    the user defined type vector.  */
12360
12361 static struct type *
12362 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12363 {
12364   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12365   struct comp_unit_head *cu_header = &cu->header;
12366   struct type *type;
12367   struct attribute *attr_byte_size;
12368   struct attribute *attr_address_class;
12369   int byte_size, addr_class;
12370   struct type *target_type;
12371
12372   target_type = die_type (die, cu);
12373
12374   /* The die_type call above may have already set the type for this DIE.  */
12375   type = get_die_type (die, cu);
12376   if (type)
12377     return type;
12378
12379   type = lookup_pointer_type (target_type);
12380
12381   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12382   if (attr_byte_size)
12383     byte_size = DW_UNSND (attr_byte_size);
12384   else
12385     byte_size = cu_header->addr_size;
12386
12387   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12388   if (attr_address_class)
12389     addr_class = DW_UNSND (attr_address_class);
12390   else
12391     addr_class = DW_ADDR_none;
12392
12393   /* If the pointer size or address class is different than the
12394      default, create a type variant marked as such and set the
12395      length accordingly.  */
12396   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12397     {
12398       if (gdbarch_address_class_type_flags_p (gdbarch))
12399         {
12400           int type_flags;
12401
12402           type_flags = gdbarch_address_class_type_flags
12403                          (gdbarch, byte_size, addr_class);
12404           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12405                       == 0);
12406           type = make_type_with_address_space (type, type_flags);
12407         }
12408       else if (TYPE_LENGTH (type) != byte_size)
12409         {
12410           complaint (&symfile_complaints,
12411                      _("invalid pointer size %d"), byte_size);
12412         }
12413       else
12414         {
12415           /* Should we also complain about unhandled address classes?  */
12416         }
12417     }
12418
12419   TYPE_LENGTH (type) = byte_size;
12420   return set_die_type (die, type, cu);
12421 }
12422
12423 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12424    the user defined type vector.  */
12425
12426 static struct type *
12427 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12428 {
12429   struct type *type;
12430   struct type *to_type;
12431   struct type *domain;
12432
12433   to_type = die_type (die, cu);
12434   domain = die_containing_type (die, cu);
12435
12436   /* The calls above may have already set the type for this DIE.  */
12437   type = get_die_type (die, cu);
12438   if (type)
12439     return type;
12440
12441   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12442     type = lookup_methodptr_type (to_type);
12443   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12444     {
12445       struct type *new_type = alloc_type (cu->objfile);
12446
12447       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12448                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12449                             TYPE_VARARGS (to_type));
12450       type = lookup_methodptr_type (new_type);
12451     }
12452   else
12453     type = lookup_memberptr_type (to_type, domain);
12454
12455   return set_die_type (die, type, cu);
12456 }
12457
12458 /* Extract all information from a DW_TAG_reference_type DIE and add to
12459    the user defined type vector.  */
12460
12461 static struct type *
12462 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12463 {
12464   struct comp_unit_head *cu_header = &cu->header;
12465   struct type *type, *target_type;
12466   struct attribute *attr;
12467
12468   target_type = die_type (die, cu);
12469
12470   /* The die_type call above may have already set the type for this DIE.  */
12471   type = get_die_type (die, cu);
12472   if (type)
12473     return type;
12474
12475   type = lookup_reference_type (target_type);
12476   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12477   if (attr)
12478     {
12479       TYPE_LENGTH (type) = DW_UNSND (attr);
12480     }
12481   else
12482     {
12483       TYPE_LENGTH (type) = cu_header->addr_size;
12484     }
12485   return set_die_type (die, type, cu);
12486 }
12487
12488 static struct type *
12489 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12490 {
12491   struct type *base_type, *cv_type;
12492
12493   base_type = die_type (die, cu);
12494
12495   /* The die_type call above may have already set the type for this DIE.  */
12496   cv_type = get_die_type (die, cu);
12497   if (cv_type)
12498     return cv_type;
12499
12500   /* In case the const qualifier is applied to an array type, the element type
12501      is so qualified, not the array type (section 6.7.3 of C99).  */
12502   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12503     {
12504       struct type *el_type, *inner_array;
12505
12506       base_type = copy_type (base_type);
12507       inner_array = base_type;
12508
12509       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12510         {
12511           TYPE_TARGET_TYPE (inner_array) =
12512             copy_type (TYPE_TARGET_TYPE (inner_array));
12513           inner_array = TYPE_TARGET_TYPE (inner_array);
12514         }
12515
12516       el_type = TYPE_TARGET_TYPE (inner_array);
12517       TYPE_TARGET_TYPE (inner_array) =
12518         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12519
12520       return set_die_type (die, base_type, cu);
12521     }
12522
12523   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12524   return set_die_type (die, cv_type, cu);
12525 }
12526
12527 static struct type *
12528 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12529 {
12530   struct type *base_type, *cv_type;
12531
12532   base_type = die_type (die, cu);
12533
12534   /* The die_type call above may have already set the type for this DIE.  */
12535   cv_type = get_die_type (die, cu);
12536   if (cv_type)
12537     return cv_type;
12538
12539   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12540   return set_die_type (die, cv_type, cu);
12541 }
12542
12543 /* Handle DW_TAG_restrict_type.  */
12544
12545 static struct type *
12546 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12547 {
12548   struct type *base_type, *cv_type;
12549
12550   base_type = die_type (die, cu);
12551
12552   /* The die_type call above may have already set the type for this DIE.  */
12553   cv_type = get_die_type (die, cu);
12554   if (cv_type)
12555     return cv_type;
12556
12557   cv_type = make_restrict_type (base_type);
12558   return set_die_type (die, cv_type, cu);
12559 }
12560
12561 /* Extract all information from a DW_TAG_string_type DIE and add to
12562    the user defined type vector.  It isn't really a user defined type,
12563    but it behaves like one, with other DIE's using an AT_user_def_type
12564    attribute to reference it.  */
12565
12566 static struct type *
12567 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12568 {
12569   struct objfile *objfile = cu->objfile;
12570   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12571   struct type *type, *range_type, *index_type, *char_type;
12572   struct attribute *attr;
12573   unsigned int length;
12574
12575   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12576   if (attr)
12577     {
12578       length = DW_UNSND (attr);
12579     }
12580   else
12581     {
12582       /* Check for the DW_AT_byte_size attribute.  */
12583       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12584       if (attr)
12585         {
12586           length = DW_UNSND (attr);
12587         }
12588       else
12589         {
12590           length = 1;
12591         }
12592     }
12593
12594   index_type = objfile_type (objfile)->builtin_int;
12595   range_type = create_range_type (NULL, index_type, 1, length);
12596   char_type = language_string_char_type (cu->language_defn, gdbarch);
12597   type = create_string_type (NULL, char_type, range_type);
12598
12599   return set_die_type (die, type, cu);
12600 }
12601
12602 /* Handle DIES due to C code like:
12603
12604    struct foo
12605    {
12606    int (*funcp)(int a, long l);
12607    int b;
12608    };
12609
12610    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12611
12612 static struct type *
12613 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12614 {
12615   struct objfile *objfile = cu->objfile;
12616   struct type *type;            /* Type that this function returns.  */
12617   struct type *ftype;           /* Function that returns above type.  */
12618   struct attribute *attr;
12619
12620   type = die_type (die, cu);
12621
12622   /* The die_type call above may have already set the type for this DIE.  */
12623   ftype = get_die_type (die, cu);
12624   if (ftype)
12625     return ftype;
12626
12627   ftype = lookup_function_type (type);
12628
12629   /* All functions in C++, Pascal and Java have prototypes.  */
12630   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12631   if ((attr && (DW_UNSND (attr) != 0))
12632       || cu->language == language_cplus
12633       || cu->language == language_java
12634       || cu->language == language_pascal)
12635     TYPE_PROTOTYPED (ftype) = 1;
12636   else if (producer_is_realview (cu->producer))
12637     /* RealView does not emit DW_AT_prototyped.  We can not
12638        distinguish prototyped and unprototyped functions; default to
12639        prototyped, since that is more common in modern code (and
12640        RealView warns about unprototyped functions).  */
12641     TYPE_PROTOTYPED (ftype) = 1;
12642
12643   /* Store the calling convention in the type if it's available in
12644      the subroutine die.  Otherwise set the calling convention to
12645      the default value DW_CC_normal.  */
12646   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12647   if (attr)
12648     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12649   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12650     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12651   else
12652     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12653
12654   /* We need to add the subroutine type to the die immediately so
12655      we don't infinitely recurse when dealing with parameters
12656      declared as the same subroutine type.  */
12657   set_die_type (die, ftype, cu);
12658
12659   if (die->child != NULL)
12660     {
12661       struct type *void_type = objfile_type (objfile)->builtin_void;
12662       struct die_info *child_die;
12663       int nparams, iparams;
12664
12665       /* Count the number of parameters.
12666          FIXME: GDB currently ignores vararg functions, but knows about
12667          vararg member functions.  */
12668       nparams = 0;
12669       child_die = die->child;
12670       while (child_die && child_die->tag)
12671         {
12672           if (child_die->tag == DW_TAG_formal_parameter)
12673             nparams++;
12674           else if (child_die->tag == DW_TAG_unspecified_parameters)
12675             TYPE_VARARGS (ftype) = 1;
12676           child_die = sibling_die (child_die);
12677         }
12678
12679       /* Allocate storage for parameters and fill them in.  */
12680       TYPE_NFIELDS (ftype) = nparams;
12681       TYPE_FIELDS (ftype) = (struct field *)
12682         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12683
12684       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12685          even if we error out during the parameters reading below.  */
12686       for (iparams = 0; iparams < nparams; iparams++)
12687         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12688
12689       iparams = 0;
12690       child_die = die->child;
12691       while (child_die && child_die->tag)
12692         {
12693           if (child_die->tag == DW_TAG_formal_parameter)
12694             {
12695               struct type *arg_type;
12696
12697               /* DWARF version 2 has no clean way to discern C++
12698                  static and non-static member functions.  G++ helps
12699                  GDB by marking the first parameter for non-static
12700                  member functions (which is the this pointer) as
12701                  artificial.  We pass this information to
12702                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12703
12704                  DWARF version 3 added DW_AT_object_pointer, which GCC
12705                  4.5 does not yet generate.  */
12706               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12707               if (attr)
12708                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12709               else
12710                 {
12711                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12712
12713                   /* GCC/43521: In java, the formal parameter
12714                      "this" is sometimes not marked with DW_AT_artificial.  */
12715                   if (cu->language == language_java)
12716                     {
12717                       const char *name = dwarf2_name (child_die, cu);
12718
12719                       if (name && !strcmp (name, "this"))
12720                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12721                     }
12722                 }
12723               arg_type = die_type (child_die, cu);
12724
12725               /* RealView does not mark THIS as const, which the testsuite
12726                  expects.  GCC marks THIS as const in method definitions,
12727                  but not in the class specifications (GCC PR 43053).  */
12728               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12729                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12730                 {
12731                   int is_this = 0;
12732                   struct dwarf2_cu *arg_cu = cu;
12733                   const char *name = dwarf2_name (child_die, cu);
12734
12735                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12736                   if (attr)
12737                     {
12738                       /* If the compiler emits this, use it.  */
12739                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12740                         is_this = 1;
12741                     }
12742                   else if (name && strcmp (name, "this") == 0)
12743                     /* Function definitions will have the argument names.  */
12744                     is_this = 1;
12745                   else if (name == NULL && iparams == 0)
12746                     /* Declarations may not have the names, so like
12747                        elsewhere in GDB, assume an artificial first
12748                        argument is "this".  */
12749                     is_this = 1;
12750
12751                   if (is_this)
12752                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12753                                              arg_type, 0);
12754                 }
12755
12756               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12757               iparams++;
12758             }
12759           child_die = sibling_die (child_die);
12760         }
12761     }
12762
12763   return ftype;
12764 }
12765
12766 static struct type *
12767 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12768 {
12769   struct objfile *objfile = cu->objfile;
12770   const char *name = NULL;
12771   struct type *this_type, *target_type;
12772
12773   name = dwarf2_full_name (NULL, die, cu);
12774   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12775                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12776   TYPE_NAME (this_type) = name;
12777   set_die_type (die, this_type, cu);
12778   target_type = die_type (die, cu);
12779   if (target_type != this_type)
12780     TYPE_TARGET_TYPE (this_type) = target_type;
12781   else
12782     {
12783       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12784          spec and cause infinite loops in GDB.  */
12785       complaint (&symfile_complaints,
12786                  _("Self-referential DW_TAG_typedef "
12787                    "- DIE at 0x%x [in module %s]"),
12788                  die->offset.sect_off, objfile->name);
12789       TYPE_TARGET_TYPE (this_type) = NULL;
12790     }
12791   return this_type;
12792 }
12793
12794 /* Find a representation of a given base type and install
12795    it in the TYPE field of the die.  */
12796
12797 static struct type *
12798 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12799 {
12800   struct objfile *objfile = cu->objfile;
12801   struct type *type;
12802   struct attribute *attr;
12803   int encoding = 0, size = 0;
12804   const char *name;
12805   enum type_code code = TYPE_CODE_INT;
12806   int type_flags = 0;
12807   struct type *target_type = NULL;
12808
12809   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12810   if (attr)
12811     {
12812       encoding = DW_UNSND (attr);
12813     }
12814   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12815   if (attr)
12816     {
12817       size = DW_UNSND (attr);
12818     }
12819   name = dwarf2_name (die, cu);
12820   if (!name)
12821     {
12822       complaint (&symfile_complaints,
12823                  _("DW_AT_name missing from DW_TAG_base_type"));
12824     }
12825
12826   switch (encoding)
12827     {
12828       case DW_ATE_address:
12829         /* Turn DW_ATE_address into a void * pointer.  */
12830         code = TYPE_CODE_PTR;
12831         type_flags |= TYPE_FLAG_UNSIGNED;
12832         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12833         break;
12834       case DW_ATE_boolean:
12835         code = TYPE_CODE_BOOL;
12836         type_flags |= TYPE_FLAG_UNSIGNED;
12837         break;
12838       case DW_ATE_complex_float:
12839         code = TYPE_CODE_COMPLEX;
12840         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12841         break;
12842       case DW_ATE_decimal_float:
12843         code = TYPE_CODE_DECFLOAT;
12844         break;
12845       case DW_ATE_float:
12846         code = TYPE_CODE_FLT;
12847         break;
12848       case DW_ATE_signed:
12849         break;
12850       case DW_ATE_unsigned:
12851         type_flags |= TYPE_FLAG_UNSIGNED;
12852         if (cu->language == language_fortran
12853             && name
12854             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12855           code = TYPE_CODE_CHAR;
12856         break;
12857       case DW_ATE_signed_char:
12858         if (cu->language == language_ada || cu->language == language_m2
12859             || cu->language == language_pascal
12860             || cu->language == language_fortran)
12861           code = TYPE_CODE_CHAR;
12862         break;
12863       case DW_ATE_unsigned_char:
12864         if (cu->language == language_ada || cu->language == language_m2
12865             || cu->language == language_pascal
12866             || cu->language == language_fortran)
12867           code = TYPE_CODE_CHAR;
12868         type_flags |= TYPE_FLAG_UNSIGNED;
12869         break;
12870       case DW_ATE_UTF:
12871         /* We just treat this as an integer and then recognize the
12872            type by name elsewhere.  */
12873         break;
12874
12875       default:
12876         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12877                    dwarf_type_encoding_name (encoding));
12878         break;
12879     }
12880
12881   type = init_type (code, size, type_flags, NULL, objfile);
12882   TYPE_NAME (type) = name;
12883   TYPE_TARGET_TYPE (type) = target_type;
12884
12885   if (name && strcmp (name, "char") == 0)
12886     TYPE_NOSIGN (type) = 1;
12887
12888   return set_die_type (die, type, cu);
12889 }
12890
12891 /* Read the given DW_AT_subrange DIE.  */
12892
12893 static struct type *
12894 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12895 {
12896   struct type *base_type, *orig_base_type;
12897   struct type *range_type;
12898   struct attribute *attr;
12899   LONGEST low, high;
12900   int low_default_is_valid;
12901   const char *name;
12902   LONGEST negative_mask;
12903
12904   orig_base_type = die_type (die, cu);
12905   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
12906      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
12907      creating the range type, but we use the result of check_typedef
12908      when examining properties of the type.  */
12909   base_type = check_typedef (orig_base_type);
12910
12911   /* The die_type call above may have already set the type for this DIE.  */
12912   range_type = get_die_type (die, cu);
12913   if (range_type)
12914     return range_type;
12915
12916   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12917      omitting DW_AT_lower_bound.  */
12918   switch (cu->language)
12919     {
12920     case language_c:
12921     case language_cplus:
12922       low = 0;
12923       low_default_is_valid = 1;
12924       break;
12925     case language_fortran:
12926       low = 1;
12927       low_default_is_valid = 1;
12928       break;
12929     case language_d:
12930     case language_java:
12931     case language_objc:
12932       low = 0;
12933       low_default_is_valid = (cu->header.version >= 4);
12934       break;
12935     case language_ada:
12936     case language_m2:
12937     case language_pascal:
12938       low = 1;
12939       low_default_is_valid = (cu->header.version >= 4);
12940       break;
12941     default:
12942       low = 0;
12943       low_default_is_valid = 0;
12944       break;
12945     }
12946
12947   /* FIXME: For variable sized arrays either of these could be
12948      a variable rather than a constant value.  We'll allow it,
12949      but we don't know how to handle it.  */
12950   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12951   if (attr)
12952     low = dwarf2_get_attr_constant_value (attr, low);
12953   else if (!low_default_is_valid)
12954     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12955                                       "- DIE at 0x%x [in module %s]"),
12956                die->offset.sect_off, cu->objfile->name);
12957
12958   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12959   if (attr)
12960     {
12961       if (attr_form_is_block (attr) || is_ref_attr (attr))
12962         {
12963           /* GCC encodes arrays with unspecified or dynamic length
12964              with a DW_FORM_block1 attribute or a reference attribute.
12965              FIXME: GDB does not yet know how to handle dynamic
12966              arrays properly, treat them as arrays with unspecified
12967              length for now.
12968
12969              FIXME: jimb/2003-09-22: GDB does not really know
12970              how to handle arrays of unspecified length
12971              either; we just represent them as zero-length
12972              arrays.  Choose an appropriate upper bound given
12973              the lower bound we've computed above.  */
12974           high = low - 1;
12975         }
12976       else
12977         high = dwarf2_get_attr_constant_value (attr, 1);
12978     }
12979   else
12980     {
12981       attr = dwarf2_attr (die, DW_AT_count, cu);
12982       if (attr)
12983         {
12984           int count = dwarf2_get_attr_constant_value (attr, 1);
12985           high = low + count - 1;
12986         }
12987       else
12988         {
12989           /* Unspecified array length.  */
12990           high = low - 1;
12991         }
12992     }
12993
12994   /* Dwarf-2 specifications explicitly allows to create subrange types
12995      without specifying a base type.
12996      In that case, the base type must be set to the type of
12997      the lower bound, upper bound or count, in that order, if any of these
12998      three attributes references an object that has a type.
12999      If no base type is found, the Dwarf-2 specifications say that
13000      a signed integer type of size equal to the size of an address should
13001      be used.
13002      For the following C code: `extern char gdb_int [];'
13003      GCC produces an empty range DIE.
13004      FIXME: muller/2010-05-28: Possible references to object for low bound,
13005      high bound or count are not yet handled by this code.  */
13006   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13007     {
13008       struct objfile *objfile = cu->objfile;
13009       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13010       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13011       struct type *int_type = objfile_type (objfile)->builtin_int;
13012
13013       /* Test "int", "long int", and "long long int" objfile types,
13014          and select the first one having a size above or equal to the
13015          architecture address size.  */
13016       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13017         base_type = int_type;
13018       else
13019         {
13020           int_type = objfile_type (objfile)->builtin_long;
13021           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13022             base_type = int_type;
13023           else
13024             {
13025               int_type = objfile_type (objfile)->builtin_long_long;
13026               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13027                 base_type = int_type;
13028             }
13029         }
13030     }
13031
13032   negative_mask =
13033     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13034   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13035     low |= negative_mask;
13036   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13037     high |= negative_mask;
13038
13039   range_type = create_range_type (NULL, orig_base_type, low, high);
13040
13041   /* Mark arrays with dynamic length at least as an array of unspecified
13042      length.  GDB could check the boundary but before it gets implemented at
13043      least allow accessing the array elements.  */
13044   if (attr && attr_form_is_block (attr))
13045     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13046
13047   /* Ada expects an empty array on no boundary attributes.  */
13048   if (attr == NULL && cu->language != language_ada)
13049     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13050
13051   name = dwarf2_name (die, cu);
13052   if (name)
13053     TYPE_NAME (range_type) = name;
13054
13055   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13056   if (attr)
13057     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13058
13059   set_die_type (die, range_type, cu);
13060
13061   /* set_die_type should be already done.  */
13062   set_descriptive_type (range_type, die, cu);
13063
13064   return range_type;
13065 }
13066
13067 static struct type *
13068 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13069 {
13070   struct type *type;
13071
13072   /* For now, we only support the C meaning of an unspecified type: void.  */
13073
13074   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13075   TYPE_NAME (type) = dwarf2_name (die, cu);
13076
13077   return set_die_type (die, type, cu);
13078 }
13079
13080 /* Read a single die and all its descendents.  Set the die's sibling
13081    field to NULL; set other fields in the die correctly, and set all
13082    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13083    location of the info_ptr after reading all of those dies.  PARENT
13084    is the parent of the die in question.  */
13085
13086 static struct die_info *
13087 read_die_and_children (const struct die_reader_specs *reader,
13088                        const gdb_byte *info_ptr,
13089                        const gdb_byte **new_info_ptr,
13090                        struct die_info *parent)
13091 {
13092   struct die_info *die;
13093   const gdb_byte *cur_ptr;
13094   int has_children;
13095
13096   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13097   if (die == NULL)
13098     {
13099       *new_info_ptr = cur_ptr;
13100       return NULL;
13101     }
13102   store_in_ref_table (die, reader->cu);
13103
13104   if (has_children)
13105     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13106   else
13107     {
13108       die->child = NULL;
13109       *new_info_ptr = cur_ptr;
13110     }
13111
13112   die->sibling = NULL;
13113   die->parent = parent;
13114   return die;
13115 }
13116
13117 /* Read a die, all of its descendents, and all of its siblings; set
13118    all of the fields of all of the dies correctly.  Arguments are as
13119    in read_die_and_children.  */
13120
13121 static struct die_info *
13122 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13123                          const gdb_byte *info_ptr,
13124                          const gdb_byte **new_info_ptr,
13125                          struct die_info *parent)
13126 {
13127   struct die_info *first_die, *last_sibling;
13128   const gdb_byte *cur_ptr;
13129
13130   cur_ptr = info_ptr;
13131   first_die = last_sibling = NULL;
13132
13133   while (1)
13134     {
13135       struct die_info *die
13136         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13137
13138       if (die == NULL)
13139         {
13140           *new_info_ptr = cur_ptr;
13141           return first_die;
13142         }
13143
13144       if (!first_die)
13145         first_die = die;
13146       else
13147         last_sibling->sibling = die;
13148
13149       last_sibling = die;
13150     }
13151 }
13152
13153 /* Read a die, all of its descendents, and all of its siblings; set
13154    all of the fields of all of the dies correctly.  Arguments are as
13155    in read_die_and_children.
13156    This the main entry point for reading a DIE and all its children.  */
13157
13158 static struct die_info *
13159 read_die_and_siblings (const struct die_reader_specs *reader,
13160                        const gdb_byte *info_ptr,
13161                        const gdb_byte **new_info_ptr,
13162                        struct die_info *parent)
13163 {
13164   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13165                                                   new_info_ptr, parent);
13166
13167   if (dwarf2_die_debug)
13168     {
13169       fprintf_unfiltered (gdb_stdlog,
13170                           "Read die from %s@0x%x of %s:\n",
13171                           bfd_section_name (reader->abfd,
13172                                             reader->die_section->asection),
13173                           (unsigned) (info_ptr - reader->die_section->buffer),
13174                           bfd_get_filename (reader->abfd));
13175       dump_die (die, dwarf2_die_debug);
13176     }
13177
13178   return die;
13179 }
13180
13181 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13182    attributes.
13183    The caller is responsible for filling in the extra attributes
13184    and updating (*DIEP)->num_attrs.
13185    Set DIEP to point to a newly allocated die with its information,
13186    except for its child, sibling, and parent fields.
13187    Set HAS_CHILDREN to tell whether the die has children or not.  */
13188
13189 static const gdb_byte *
13190 read_full_die_1 (const struct die_reader_specs *reader,
13191                  struct die_info **diep, const gdb_byte *info_ptr,
13192                  int *has_children, int num_extra_attrs)
13193 {
13194   unsigned int abbrev_number, bytes_read, i;
13195   sect_offset offset;
13196   struct abbrev_info *abbrev;
13197   struct die_info *die;
13198   struct dwarf2_cu *cu = reader->cu;
13199   bfd *abfd = reader->abfd;
13200
13201   offset.sect_off = info_ptr - reader->buffer;
13202   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13203   info_ptr += bytes_read;
13204   if (!abbrev_number)
13205     {
13206       *diep = NULL;
13207       *has_children = 0;
13208       return info_ptr;
13209     }
13210
13211   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13212   if (!abbrev)
13213     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13214            abbrev_number,
13215            bfd_get_filename (abfd));
13216
13217   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13218   die->offset = offset;
13219   die->tag = abbrev->tag;
13220   die->abbrev = abbrev_number;
13221
13222   /* Make the result usable.
13223      The caller needs to update num_attrs after adding the extra
13224      attributes.  */
13225   die->num_attrs = abbrev->num_attrs;
13226
13227   for (i = 0; i < abbrev->num_attrs; ++i)
13228     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13229                                info_ptr);
13230
13231   *diep = die;
13232   *has_children = abbrev->has_children;
13233   return info_ptr;
13234 }
13235
13236 /* Read a die and all its attributes.
13237    Set DIEP to point to a newly allocated die with its information,
13238    except for its child, sibling, and parent fields.
13239    Set HAS_CHILDREN to tell whether the die has children or not.  */
13240
13241 static const gdb_byte *
13242 read_full_die (const struct die_reader_specs *reader,
13243                struct die_info **diep, const gdb_byte *info_ptr,
13244                int *has_children)
13245 {
13246   const gdb_byte *result;
13247
13248   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13249
13250   if (dwarf2_die_debug)
13251     {
13252       fprintf_unfiltered (gdb_stdlog,
13253                           "Read die from %s@0x%x of %s:\n",
13254                           bfd_section_name (reader->abfd,
13255                                             reader->die_section->asection),
13256                           (unsigned) (info_ptr - reader->die_section->buffer),
13257                           bfd_get_filename (reader->abfd));
13258       dump_die (*diep, dwarf2_die_debug);
13259     }
13260
13261   return result;
13262 }
13263 \f
13264 /* Abbreviation tables.
13265
13266    In DWARF version 2, the description of the debugging information is
13267    stored in a separate .debug_abbrev section.  Before we read any
13268    dies from a section we read in all abbreviations and install them
13269    in a hash table.  */
13270
13271 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13272
13273 static struct abbrev_info *
13274 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13275 {
13276   struct abbrev_info *abbrev;
13277
13278   abbrev = (struct abbrev_info *)
13279     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13280   memset (abbrev, 0, sizeof (struct abbrev_info));
13281   return abbrev;
13282 }
13283
13284 /* Add an abbreviation to the table.  */
13285
13286 static void
13287 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13288                          unsigned int abbrev_number,
13289                          struct abbrev_info *abbrev)
13290 {
13291   unsigned int hash_number;
13292
13293   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13294   abbrev->next = abbrev_table->abbrevs[hash_number];
13295   abbrev_table->abbrevs[hash_number] = abbrev;
13296 }
13297
13298 /* Look up an abbrev in the table.
13299    Returns NULL if the abbrev is not found.  */
13300
13301 static struct abbrev_info *
13302 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13303                             unsigned int abbrev_number)
13304 {
13305   unsigned int hash_number;
13306   struct abbrev_info *abbrev;
13307
13308   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13309   abbrev = abbrev_table->abbrevs[hash_number];
13310
13311   while (abbrev)
13312     {
13313       if (abbrev->number == abbrev_number)
13314         return abbrev;
13315       abbrev = abbrev->next;
13316     }
13317   return NULL;
13318 }
13319
13320 /* Read in an abbrev table.  */
13321
13322 static struct abbrev_table *
13323 abbrev_table_read_table (struct dwarf2_section_info *section,
13324                          sect_offset offset)
13325 {
13326   struct objfile *objfile = dwarf2_per_objfile->objfile;
13327   bfd *abfd = section->asection->owner;
13328   struct abbrev_table *abbrev_table;
13329   const gdb_byte *abbrev_ptr;
13330   struct abbrev_info *cur_abbrev;
13331   unsigned int abbrev_number, bytes_read, abbrev_name;
13332   unsigned int abbrev_form;
13333   struct attr_abbrev *cur_attrs;
13334   unsigned int allocated_attrs;
13335
13336   abbrev_table = XMALLOC (struct abbrev_table);
13337   abbrev_table->offset = offset;
13338   obstack_init (&abbrev_table->abbrev_obstack);
13339   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13340                                          (ABBREV_HASH_SIZE
13341                                           * sizeof (struct abbrev_info *)));
13342   memset (abbrev_table->abbrevs, 0,
13343           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13344
13345   dwarf2_read_section (objfile, section);
13346   abbrev_ptr = section->buffer + offset.sect_off;
13347   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13348   abbrev_ptr += bytes_read;
13349
13350   allocated_attrs = ATTR_ALLOC_CHUNK;
13351   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13352
13353   /* Loop until we reach an abbrev number of 0.  */
13354   while (abbrev_number)
13355     {
13356       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13357
13358       /* read in abbrev header */
13359       cur_abbrev->number = abbrev_number;
13360       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13361       abbrev_ptr += bytes_read;
13362       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13363       abbrev_ptr += 1;
13364
13365       /* now read in declarations */
13366       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13367       abbrev_ptr += bytes_read;
13368       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13369       abbrev_ptr += bytes_read;
13370       while (abbrev_name)
13371         {
13372           if (cur_abbrev->num_attrs == allocated_attrs)
13373             {
13374               allocated_attrs += ATTR_ALLOC_CHUNK;
13375               cur_attrs
13376                 = xrealloc (cur_attrs, (allocated_attrs
13377                                         * sizeof (struct attr_abbrev)));
13378             }
13379
13380           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13381           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13382           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13383           abbrev_ptr += bytes_read;
13384           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13385           abbrev_ptr += bytes_read;
13386         }
13387
13388       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13389                                          (cur_abbrev->num_attrs
13390                                           * sizeof (struct attr_abbrev)));
13391       memcpy (cur_abbrev->attrs, cur_attrs,
13392               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13393
13394       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13395
13396       /* Get next abbreviation.
13397          Under Irix6 the abbreviations for a compilation unit are not
13398          always properly terminated with an abbrev number of 0.
13399          Exit loop if we encounter an abbreviation which we have
13400          already read (which means we are about to read the abbreviations
13401          for the next compile unit) or if the end of the abbreviation
13402          table is reached.  */
13403       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13404         break;
13405       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13406       abbrev_ptr += bytes_read;
13407       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13408         break;
13409     }
13410
13411   xfree (cur_attrs);
13412   return abbrev_table;
13413 }
13414
13415 /* Free the resources held by ABBREV_TABLE.  */
13416
13417 static void
13418 abbrev_table_free (struct abbrev_table *abbrev_table)
13419 {
13420   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13421   xfree (abbrev_table);
13422 }
13423
13424 /* Same as abbrev_table_free but as a cleanup.
13425    We pass in a pointer to the pointer to the table so that we can
13426    set the pointer to NULL when we're done.  It also simplifies
13427    build_type_unit_groups.  */
13428
13429 static void
13430 abbrev_table_free_cleanup (void *table_ptr)
13431 {
13432   struct abbrev_table **abbrev_table_ptr = table_ptr;
13433
13434   if (*abbrev_table_ptr != NULL)
13435     abbrev_table_free (*abbrev_table_ptr);
13436   *abbrev_table_ptr = NULL;
13437 }
13438
13439 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13440
13441 static void
13442 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13443                      struct dwarf2_section_info *abbrev_section)
13444 {
13445   cu->abbrev_table =
13446     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13447 }
13448
13449 /* Release the memory used by the abbrev table for a compilation unit.  */
13450
13451 static void
13452 dwarf2_free_abbrev_table (void *ptr_to_cu)
13453 {
13454   struct dwarf2_cu *cu = ptr_to_cu;
13455
13456   abbrev_table_free (cu->abbrev_table);
13457   /* Set this to NULL so that we SEGV if we try to read it later,
13458      and also because free_comp_unit verifies this is NULL.  */
13459   cu->abbrev_table = NULL;
13460 }
13461 \f
13462 /* Returns nonzero if TAG represents a type that we might generate a partial
13463    symbol for.  */
13464
13465 static int
13466 is_type_tag_for_partial (int tag)
13467 {
13468   switch (tag)
13469     {
13470 #if 0
13471     /* Some types that would be reasonable to generate partial symbols for,
13472        that we don't at present.  */
13473     case DW_TAG_array_type:
13474     case DW_TAG_file_type:
13475     case DW_TAG_ptr_to_member_type:
13476     case DW_TAG_set_type:
13477     case DW_TAG_string_type:
13478     case DW_TAG_subroutine_type:
13479 #endif
13480     case DW_TAG_base_type:
13481     case DW_TAG_class_type:
13482     case DW_TAG_interface_type:
13483     case DW_TAG_enumeration_type:
13484     case DW_TAG_structure_type:
13485     case DW_TAG_subrange_type:
13486     case DW_TAG_typedef:
13487     case DW_TAG_union_type:
13488       return 1;
13489     default:
13490       return 0;
13491     }
13492 }
13493
13494 /* Load all DIEs that are interesting for partial symbols into memory.  */
13495
13496 static struct partial_die_info *
13497 load_partial_dies (const struct die_reader_specs *reader,
13498                    const gdb_byte *info_ptr, int building_psymtab)
13499 {
13500   struct dwarf2_cu *cu = reader->cu;
13501   struct objfile *objfile = cu->objfile;
13502   struct partial_die_info *part_die;
13503   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13504   struct abbrev_info *abbrev;
13505   unsigned int bytes_read;
13506   unsigned int load_all = 0;
13507   int nesting_level = 1;
13508
13509   parent_die = NULL;
13510   last_die = NULL;
13511
13512   gdb_assert (cu->per_cu != NULL);
13513   if (cu->per_cu->load_all_dies)
13514     load_all = 1;
13515
13516   cu->partial_dies
13517     = htab_create_alloc_ex (cu->header.length / 12,
13518                             partial_die_hash,
13519                             partial_die_eq,
13520                             NULL,
13521                             &cu->comp_unit_obstack,
13522                             hashtab_obstack_allocate,
13523                             dummy_obstack_deallocate);
13524
13525   part_die = obstack_alloc (&cu->comp_unit_obstack,
13526                             sizeof (struct partial_die_info));
13527
13528   while (1)
13529     {
13530       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13531
13532       /* A NULL abbrev means the end of a series of children.  */
13533       if (abbrev == NULL)
13534         {
13535           if (--nesting_level == 0)
13536             {
13537               /* PART_DIE was probably the last thing allocated on the
13538                  comp_unit_obstack, so we could call obstack_free
13539                  here.  We don't do that because the waste is small,
13540                  and will be cleaned up when we're done with this
13541                  compilation unit.  This way, we're also more robust
13542                  against other users of the comp_unit_obstack.  */
13543               return first_die;
13544             }
13545           info_ptr += bytes_read;
13546           last_die = parent_die;
13547           parent_die = parent_die->die_parent;
13548           continue;
13549         }
13550
13551       /* Check for template arguments.  We never save these; if
13552          they're seen, we just mark the parent, and go on our way.  */
13553       if (parent_die != NULL
13554           && cu->language == language_cplus
13555           && (abbrev->tag == DW_TAG_template_type_param
13556               || abbrev->tag == DW_TAG_template_value_param))
13557         {
13558           parent_die->has_template_arguments = 1;
13559
13560           if (!load_all)
13561             {
13562               /* We don't need a partial DIE for the template argument.  */
13563               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13564               continue;
13565             }
13566         }
13567
13568       /* We only recurse into c++ subprograms looking for template arguments.
13569          Skip their other children.  */
13570       if (!load_all
13571           && cu->language == language_cplus
13572           && parent_die != NULL
13573           && parent_die->tag == DW_TAG_subprogram)
13574         {
13575           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13576           continue;
13577         }
13578
13579       /* Check whether this DIE is interesting enough to save.  Normally
13580          we would not be interested in members here, but there may be
13581          later variables referencing them via DW_AT_specification (for
13582          static members).  */
13583       if (!load_all
13584           && !is_type_tag_for_partial (abbrev->tag)
13585           && abbrev->tag != DW_TAG_constant
13586           && abbrev->tag != DW_TAG_enumerator
13587           && abbrev->tag != DW_TAG_subprogram
13588           && abbrev->tag != DW_TAG_lexical_block
13589           && abbrev->tag != DW_TAG_variable
13590           && abbrev->tag != DW_TAG_namespace
13591           && abbrev->tag != DW_TAG_module
13592           && abbrev->tag != DW_TAG_member
13593           && abbrev->tag != DW_TAG_imported_unit)
13594         {
13595           /* Otherwise we skip to the next sibling, if any.  */
13596           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13597           continue;
13598         }
13599
13600       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13601                                    info_ptr);
13602
13603       /* This two-pass algorithm for processing partial symbols has a
13604          high cost in cache pressure.  Thus, handle some simple cases
13605          here which cover the majority of C partial symbols.  DIEs
13606          which neither have specification tags in them, nor could have
13607          specification tags elsewhere pointing at them, can simply be
13608          processed and discarded.
13609
13610          This segment is also optional; scan_partial_symbols and
13611          add_partial_symbol will handle these DIEs if we chain
13612          them in normally.  When compilers which do not emit large
13613          quantities of duplicate debug information are more common,
13614          this code can probably be removed.  */
13615
13616       /* Any complete simple types at the top level (pretty much all
13617          of them, for a language without namespaces), can be processed
13618          directly.  */
13619       if (parent_die == NULL
13620           && part_die->has_specification == 0
13621           && part_die->is_declaration == 0
13622           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13623               || part_die->tag == DW_TAG_base_type
13624               || part_die->tag == DW_TAG_subrange_type))
13625         {
13626           if (building_psymtab && part_die->name != NULL)
13627             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13628                                  VAR_DOMAIN, LOC_TYPEDEF,
13629                                  &objfile->static_psymbols,
13630                                  0, (CORE_ADDR) 0, cu->language, objfile);
13631           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13632           continue;
13633         }
13634
13635       /* The exception for DW_TAG_typedef with has_children above is
13636          a workaround of GCC PR debug/47510.  In the case of this complaint
13637          type_name_no_tag_or_error will error on such types later.
13638
13639          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13640          it could not find the child DIEs referenced later, this is checked
13641          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13642
13643       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13644         complaint (&symfile_complaints,
13645                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13646                      "- DIE at 0x%x [in module %s]"),
13647                    part_die->offset.sect_off, objfile->name);
13648
13649       /* If we're at the second level, and we're an enumerator, and
13650          our parent has no specification (meaning possibly lives in a
13651          namespace elsewhere), then we can add the partial symbol now
13652          instead of queueing it.  */
13653       if (part_die->tag == DW_TAG_enumerator
13654           && parent_die != NULL
13655           && parent_die->die_parent == NULL
13656           && parent_die->tag == DW_TAG_enumeration_type
13657           && parent_die->has_specification == 0)
13658         {
13659           if (part_die->name == NULL)
13660             complaint (&symfile_complaints,
13661                        _("malformed enumerator DIE ignored"));
13662           else if (building_psymtab)
13663             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13664                                  VAR_DOMAIN, LOC_CONST,
13665                                  (cu->language == language_cplus
13666                                   || cu->language == language_java)
13667                                  ? &objfile->global_psymbols
13668                                  : &objfile->static_psymbols,
13669                                  0, (CORE_ADDR) 0, cu->language, objfile);
13670
13671           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13672           continue;
13673         }
13674
13675       /* We'll save this DIE so link it in.  */
13676       part_die->die_parent = parent_die;
13677       part_die->die_sibling = NULL;
13678       part_die->die_child = NULL;
13679
13680       if (last_die && last_die == parent_die)
13681         last_die->die_child = part_die;
13682       else if (last_die)
13683         last_die->die_sibling = part_die;
13684
13685       last_die = part_die;
13686
13687       if (first_die == NULL)
13688         first_die = part_die;
13689
13690       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13691          find interesting need to be in the hash table, because we
13692          also have the parent/sibling/child chains; only those that we
13693          might refer to by offset later during partial symbol reading.
13694
13695          For now this means things that might have be the target of a
13696          DW_AT_specification, DW_AT_abstract_origin, or
13697          DW_AT_extension.  DW_AT_extension will refer only to
13698          namespaces; DW_AT_abstract_origin refers to functions (and
13699          many things under the function DIE, but we do not recurse
13700          into function DIEs during partial symbol reading) and
13701          possibly variables as well; DW_AT_specification refers to
13702          declarations.  Declarations ought to have the DW_AT_declaration
13703          flag.  It happens that GCC forgets to put it in sometimes, but
13704          only for functions, not for types.
13705
13706          Adding more things than necessary to the hash table is harmless
13707          except for the performance cost.  Adding too few will result in
13708          wasted time in find_partial_die, when we reread the compilation
13709          unit with load_all_dies set.  */
13710
13711       if (load_all
13712           || abbrev->tag == DW_TAG_constant
13713           || abbrev->tag == DW_TAG_subprogram
13714           || abbrev->tag == DW_TAG_variable
13715           || abbrev->tag == DW_TAG_namespace
13716           || part_die->is_declaration)
13717         {
13718           void **slot;
13719
13720           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13721                                            part_die->offset.sect_off, INSERT);
13722           *slot = part_die;
13723         }
13724
13725       part_die = obstack_alloc (&cu->comp_unit_obstack,
13726                                 sizeof (struct partial_die_info));
13727
13728       /* For some DIEs we want to follow their children (if any).  For C
13729          we have no reason to follow the children of structures; for other
13730          languages we have to, so that we can get at method physnames
13731          to infer fully qualified class names, for DW_AT_specification,
13732          and for C++ template arguments.  For C++, we also look one level
13733          inside functions to find template arguments (if the name of the
13734          function does not already contain the template arguments).
13735
13736          For Ada, we need to scan the children of subprograms and lexical
13737          blocks as well because Ada allows the definition of nested
13738          entities that could be interesting for the debugger, such as
13739          nested subprograms for instance.  */
13740       if (last_die->has_children
13741           && (load_all
13742               || last_die->tag == DW_TAG_namespace
13743               || last_die->tag == DW_TAG_module
13744               || last_die->tag == DW_TAG_enumeration_type
13745               || (cu->language == language_cplus
13746                   && last_die->tag == DW_TAG_subprogram
13747                   && (last_die->name == NULL
13748                       || strchr (last_die->name, '<') == NULL))
13749               || (cu->language != language_c
13750                   && (last_die->tag == DW_TAG_class_type
13751                       || last_die->tag == DW_TAG_interface_type
13752                       || last_die->tag == DW_TAG_structure_type
13753                       || last_die->tag == DW_TAG_union_type))
13754               || (cu->language == language_ada
13755                   && (last_die->tag == DW_TAG_subprogram
13756                       || last_die->tag == DW_TAG_lexical_block))))
13757         {
13758           nesting_level++;
13759           parent_die = last_die;
13760           continue;
13761         }
13762
13763       /* Otherwise we skip to the next sibling, if any.  */
13764       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13765
13766       /* Back to the top, do it again.  */
13767     }
13768 }
13769
13770 /* Read a minimal amount of information into the minimal die structure.  */
13771
13772 static const gdb_byte *
13773 read_partial_die (const struct die_reader_specs *reader,
13774                   struct partial_die_info *part_die,
13775                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13776                   const gdb_byte *info_ptr)
13777 {
13778   struct dwarf2_cu *cu = reader->cu;
13779   struct objfile *objfile = cu->objfile;
13780   const gdb_byte *buffer = reader->buffer;
13781   unsigned int i;
13782   struct attribute attr;
13783   int has_low_pc_attr = 0;
13784   int has_high_pc_attr = 0;
13785   int high_pc_relative = 0;
13786
13787   memset (part_die, 0, sizeof (struct partial_die_info));
13788
13789   part_die->offset.sect_off = info_ptr - buffer;
13790
13791   info_ptr += abbrev_len;
13792
13793   if (abbrev == NULL)
13794     return info_ptr;
13795
13796   part_die->tag = abbrev->tag;
13797   part_die->has_children = abbrev->has_children;
13798
13799   for (i = 0; i < abbrev->num_attrs; ++i)
13800     {
13801       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13802
13803       /* Store the data if it is of an attribute we want to keep in a
13804          partial symbol table.  */
13805       switch (attr.name)
13806         {
13807         case DW_AT_name:
13808           switch (part_die->tag)
13809             {
13810             case DW_TAG_compile_unit:
13811             case DW_TAG_partial_unit:
13812             case DW_TAG_type_unit:
13813               /* Compilation units have a DW_AT_name that is a filename, not
13814                  a source language identifier.  */
13815             case DW_TAG_enumeration_type:
13816             case DW_TAG_enumerator:
13817               /* These tags always have simple identifiers already; no need
13818                  to canonicalize them.  */
13819               part_die->name = DW_STRING (&attr);
13820               break;
13821             default:
13822               part_die->name
13823                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13824                                             &objfile->objfile_obstack);
13825               break;
13826             }
13827           break;
13828         case DW_AT_linkage_name:
13829         case DW_AT_MIPS_linkage_name:
13830           /* Note that both forms of linkage name might appear.  We
13831              assume they will be the same, and we only store the last
13832              one we see.  */
13833           if (cu->language == language_ada)
13834             part_die->name = DW_STRING (&attr);
13835           part_die->linkage_name = DW_STRING (&attr);
13836           break;
13837         case DW_AT_low_pc:
13838           has_low_pc_attr = 1;
13839           part_die->lowpc = DW_ADDR (&attr);
13840           break;
13841         case DW_AT_high_pc:
13842           has_high_pc_attr = 1;
13843           if (attr.form == DW_FORM_addr
13844               || attr.form == DW_FORM_GNU_addr_index)
13845             part_die->highpc = DW_ADDR (&attr);
13846           else
13847             {
13848               high_pc_relative = 1;
13849               part_die->highpc = DW_UNSND (&attr);
13850             }
13851           break;
13852         case DW_AT_location:
13853           /* Support the .debug_loc offsets.  */
13854           if (attr_form_is_block (&attr))
13855             {
13856                part_die->d.locdesc = DW_BLOCK (&attr);
13857             }
13858           else if (attr_form_is_section_offset (&attr))
13859             {
13860               dwarf2_complex_location_expr_complaint ();
13861             }
13862           else
13863             {
13864               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13865                                                      "partial symbol information");
13866             }
13867           break;
13868         case DW_AT_external:
13869           part_die->is_external = DW_UNSND (&attr);
13870           break;
13871         case DW_AT_declaration:
13872           part_die->is_declaration = DW_UNSND (&attr);
13873           break;
13874         case DW_AT_type:
13875           part_die->has_type = 1;
13876           break;
13877         case DW_AT_abstract_origin:
13878         case DW_AT_specification:
13879         case DW_AT_extension:
13880           part_die->has_specification = 1;
13881           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13882           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13883                                    || cu->per_cu->is_dwz);
13884           break;
13885         case DW_AT_sibling:
13886           /* Ignore absolute siblings, they might point outside of
13887              the current compile unit.  */
13888           if (attr.form == DW_FORM_ref_addr)
13889             complaint (&symfile_complaints,
13890                        _("ignoring absolute DW_AT_sibling"));
13891           else
13892             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13893           break;
13894         case DW_AT_byte_size:
13895           part_die->has_byte_size = 1;
13896           break;
13897         case DW_AT_calling_convention:
13898           /* DWARF doesn't provide a way to identify a program's source-level
13899              entry point.  DW_AT_calling_convention attributes are only meant
13900              to describe functions' calling conventions.
13901
13902              However, because it's a necessary piece of information in
13903              Fortran, and because DW_CC_program is the only piece of debugging
13904              information whose definition refers to a 'main program' at all,
13905              several compilers have begun marking Fortran main programs with
13906              DW_CC_program --- even when those functions use the standard
13907              calling conventions.
13908
13909              So until DWARF specifies a way to provide this information and
13910              compilers pick up the new representation, we'll support this
13911              practice.  */
13912           if (DW_UNSND (&attr) == DW_CC_program
13913               && cu->language == language_fortran)
13914             {
13915               set_main_name (part_die->name);
13916
13917               /* As this DIE has a static linkage the name would be difficult
13918                  to look up later.  */
13919               language_of_main = language_fortran;
13920             }
13921           break;
13922         case DW_AT_inline:
13923           if (DW_UNSND (&attr) == DW_INL_inlined
13924               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13925             part_die->may_be_inlined = 1;
13926           break;
13927
13928         case DW_AT_import:
13929           if (part_die->tag == DW_TAG_imported_unit)
13930             {
13931               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13932               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13933                                   || cu->per_cu->is_dwz);
13934             }
13935           break;
13936
13937         default:
13938           break;
13939         }
13940     }
13941
13942   if (high_pc_relative)
13943     part_die->highpc += part_die->lowpc;
13944
13945   if (has_low_pc_attr && has_high_pc_attr)
13946     {
13947       /* When using the GNU linker, .gnu.linkonce. sections are used to
13948          eliminate duplicate copies of functions and vtables and such.
13949          The linker will arbitrarily choose one and discard the others.
13950          The AT_*_pc values for such functions refer to local labels in
13951          these sections.  If the section from that file was discarded, the
13952          labels are not in the output, so the relocs get a value of 0.
13953          If this is a discarded function, mark the pc bounds as invalid,
13954          so that GDB will ignore it.  */
13955       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13956         {
13957           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13958
13959           complaint (&symfile_complaints,
13960                      _("DW_AT_low_pc %s is zero "
13961                        "for DIE at 0x%x [in module %s]"),
13962                      paddress (gdbarch, part_die->lowpc),
13963                      part_die->offset.sect_off, objfile->name);
13964         }
13965       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13966       else if (part_die->lowpc >= part_die->highpc)
13967         {
13968           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13969
13970           complaint (&symfile_complaints,
13971                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13972                        "for DIE at 0x%x [in module %s]"),
13973                      paddress (gdbarch, part_die->lowpc),
13974                      paddress (gdbarch, part_die->highpc),
13975                      part_die->offset.sect_off, objfile->name);
13976         }
13977       else
13978         part_die->has_pc_info = 1;
13979     }
13980
13981   return info_ptr;
13982 }
13983
13984 /* Find a cached partial DIE at OFFSET in CU.  */
13985
13986 static struct partial_die_info *
13987 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13988 {
13989   struct partial_die_info *lookup_die = NULL;
13990   struct partial_die_info part_die;
13991
13992   part_die.offset = offset;
13993   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13994                                     offset.sect_off);
13995
13996   return lookup_die;
13997 }
13998
13999 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14000    except in the case of .debug_types DIEs which do not reference
14001    outside their CU (they do however referencing other types via
14002    DW_FORM_ref_sig8).  */
14003
14004 static struct partial_die_info *
14005 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14006 {
14007   struct objfile *objfile = cu->objfile;
14008   struct dwarf2_per_cu_data *per_cu = NULL;
14009   struct partial_die_info *pd = NULL;
14010
14011   if (offset_in_dwz == cu->per_cu->is_dwz
14012       && offset_in_cu_p (&cu->header, offset))
14013     {
14014       pd = find_partial_die_in_comp_unit (offset, cu);
14015       if (pd != NULL)
14016         return pd;
14017       /* We missed recording what we needed.
14018          Load all dies and try again.  */
14019       per_cu = cu->per_cu;
14020     }
14021   else
14022     {
14023       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14024       if (cu->per_cu->is_debug_types)
14025         {
14026           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14027                    " external reference to offset 0x%lx [in module %s].\n"),
14028                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14029                  bfd_get_filename (objfile->obfd));
14030         }
14031       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14032                                                  objfile);
14033
14034       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14035         load_partial_comp_unit (per_cu);
14036
14037       per_cu->cu->last_used = 0;
14038       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14039     }
14040
14041   /* If we didn't find it, and not all dies have been loaded,
14042      load them all and try again.  */
14043
14044   if (pd == NULL && per_cu->load_all_dies == 0)
14045     {
14046       per_cu->load_all_dies = 1;
14047
14048       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14049          THIS_CU->cu may already be in use.  So we can't just free it and
14050          replace its DIEs with the ones we read in.  Instead, we leave those
14051          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14052          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14053          set.  */
14054       load_partial_comp_unit (per_cu);
14055
14056       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14057     }
14058
14059   if (pd == NULL)
14060     internal_error (__FILE__, __LINE__,
14061                     _("could not find partial DIE 0x%x "
14062                       "in cache [from module %s]\n"),
14063                     offset.sect_off, bfd_get_filename (objfile->obfd));
14064   return pd;
14065 }
14066
14067 /* See if we can figure out if the class lives in a namespace.  We do
14068    this by looking for a member function; its demangled name will
14069    contain namespace info, if there is any.  */
14070
14071 static void
14072 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14073                                   struct dwarf2_cu *cu)
14074 {
14075   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14076      what template types look like, because the demangler
14077      frequently doesn't give the same name as the debug info.  We
14078      could fix this by only using the demangled name to get the
14079      prefix (but see comment in read_structure_type).  */
14080
14081   struct partial_die_info *real_pdi;
14082   struct partial_die_info *child_pdi;
14083
14084   /* If this DIE (this DIE's specification, if any) has a parent, then
14085      we should not do this.  We'll prepend the parent's fully qualified
14086      name when we create the partial symbol.  */
14087
14088   real_pdi = struct_pdi;
14089   while (real_pdi->has_specification)
14090     real_pdi = find_partial_die (real_pdi->spec_offset,
14091                                  real_pdi->spec_is_dwz, cu);
14092
14093   if (real_pdi->die_parent != NULL)
14094     return;
14095
14096   for (child_pdi = struct_pdi->die_child;
14097        child_pdi != NULL;
14098        child_pdi = child_pdi->die_sibling)
14099     {
14100       if (child_pdi->tag == DW_TAG_subprogram
14101           && child_pdi->linkage_name != NULL)
14102         {
14103           char *actual_class_name
14104             = language_class_name_from_physname (cu->language_defn,
14105                                                  child_pdi->linkage_name);
14106           if (actual_class_name != NULL)
14107             {
14108               struct_pdi->name
14109                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14110                                  actual_class_name,
14111                                  strlen (actual_class_name));
14112               xfree (actual_class_name);
14113             }
14114           break;
14115         }
14116     }
14117 }
14118
14119 /* Adjust PART_DIE before generating a symbol for it.  This function
14120    may set the is_external flag or change the DIE's name.  */
14121
14122 static void
14123 fixup_partial_die (struct partial_die_info *part_die,
14124                    struct dwarf2_cu *cu)
14125 {
14126   /* Once we've fixed up a die, there's no point in doing so again.
14127      This also avoids a memory leak if we were to call
14128      guess_partial_die_structure_name multiple times.  */
14129   if (part_die->fixup_called)
14130     return;
14131
14132   /* If we found a reference attribute and the DIE has no name, try
14133      to find a name in the referred to DIE.  */
14134
14135   if (part_die->name == NULL && part_die->has_specification)
14136     {
14137       struct partial_die_info *spec_die;
14138
14139       spec_die = find_partial_die (part_die->spec_offset,
14140                                    part_die->spec_is_dwz, cu);
14141
14142       fixup_partial_die (spec_die, cu);
14143
14144       if (spec_die->name)
14145         {
14146           part_die->name = spec_die->name;
14147
14148           /* Copy DW_AT_external attribute if it is set.  */
14149           if (spec_die->is_external)
14150             part_die->is_external = spec_die->is_external;
14151         }
14152     }
14153
14154   /* Set default names for some unnamed DIEs.  */
14155
14156   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14157     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14158
14159   /* If there is no parent die to provide a namespace, and there are
14160      children, see if we can determine the namespace from their linkage
14161      name.  */
14162   if (cu->language == language_cplus
14163       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14164       && part_die->die_parent == NULL
14165       && part_die->has_children
14166       && (part_die->tag == DW_TAG_class_type
14167           || part_die->tag == DW_TAG_structure_type
14168           || part_die->tag == DW_TAG_union_type))
14169     guess_partial_die_structure_name (part_die, cu);
14170
14171   /* GCC might emit a nameless struct or union that has a linkage
14172      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14173   if (part_die->name == NULL
14174       && (part_die->tag == DW_TAG_class_type
14175           || part_die->tag == DW_TAG_interface_type
14176           || part_die->tag == DW_TAG_structure_type
14177           || part_die->tag == DW_TAG_union_type)
14178       && part_die->linkage_name != NULL)
14179     {
14180       char *demangled;
14181
14182       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14183       if (demangled)
14184         {
14185           const char *base;
14186
14187           /* Strip any leading namespaces/classes, keep only the base name.
14188              DW_AT_name for named DIEs does not contain the prefixes.  */
14189           base = strrchr (demangled, ':');
14190           if (base && base > demangled && base[-1] == ':')
14191             base++;
14192           else
14193             base = demangled;
14194
14195           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14196                                           base, strlen (base));
14197           xfree (demangled);
14198         }
14199     }
14200
14201   part_die->fixup_called = 1;
14202 }
14203
14204 /* Read an attribute value described by an attribute form.  */
14205
14206 static const gdb_byte *
14207 read_attribute_value (const struct die_reader_specs *reader,
14208                       struct attribute *attr, unsigned form,
14209                       const gdb_byte *info_ptr)
14210 {
14211   struct dwarf2_cu *cu = reader->cu;
14212   bfd *abfd = reader->abfd;
14213   struct comp_unit_head *cu_header = &cu->header;
14214   unsigned int bytes_read;
14215   struct dwarf_block *blk;
14216
14217   attr->form = form;
14218   switch (form)
14219     {
14220     case DW_FORM_ref_addr:
14221       if (cu->header.version == 2)
14222         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14223       else
14224         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14225                                        &cu->header, &bytes_read);
14226       info_ptr += bytes_read;
14227       break;
14228     case DW_FORM_GNU_ref_alt:
14229       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14230       info_ptr += bytes_read;
14231       break;
14232     case DW_FORM_addr:
14233       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14234       info_ptr += bytes_read;
14235       break;
14236     case DW_FORM_block2:
14237       blk = dwarf_alloc_block (cu);
14238       blk->size = read_2_bytes (abfd, info_ptr);
14239       info_ptr += 2;
14240       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14241       info_ptr += blk->size;
14242       DW_BLOCK (attr) = blk;
14243       break;
14244     case DW_FORM_block4:
14245       blk = dwarf_alloc_block (cu);
14246       blk->size = read_4_bytes (abfd, info_ptr);
14247       info_ptr += 4;
14248       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14249       info_ptr += blk->size;
14250       DW_BLOCK (attr) = blk;
14251       break;
14252     case DW_FORM_data2:
14253       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14254       info_ptr += 2;
14255       break;
14256     case DW_FORM_data4:
14257       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14258       info_ptr += 4;
14259       break;
14260     case DW_FORM_data8:
14261       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14262       info_ptr += 8;
14263       break;
14264     case DW_FORM_sec_offset:
14265       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14266       info_ptr += bytes_read;
14267       break;
14268     case DW_FORM_string:
14269       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14270       DW_STRING_IS_CANONICAL (attr) = 0;
14271       info_ptr += bytes_read;
14272       break;
14273     case DW_FORM_strp:
14274       if (!cu->per_cu->is_dwz)
14275         {
14276           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14277                                                    &bytes_read);
14278           DW_STRING_IS_CANONICAL (attr) = 0;
14279           info_ptr += bytes_read;
14280           break;
14281         }
14282       /* FALLTHROUGH */
14283     case DW_FORM_GNU_strp_alt:
14284       {
14285         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14286         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14287                                           &bytes_read);
14288
14289         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14290         DW_STRING_IS_CANONICAL (attr) = 0;
14291         info_ptr += bytes_read;
14292       }
14293       break;
14294     case DW_FORM_exprloc:
14295     case DW_FORM_block:
14296       blk = dwarf_alloc_block (cu);
14297       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14298       info_ptr += bytes_read;
14299       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14300       info_ptr += blk->size;
14301       DW_BLOCK (attr) = blk;
14302       break;
14303     case DW_FORM_block1:
14304       blk = dwarf_alloc_block (cu);
14305       blk->size = read_1_byte (abfd, info_ptr);
14306       info_ptr += 1;
14307       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14308       info_ptr += blk->size;
14309       DW_BLOCK (attr) = blk;
14310       break;
14311     case DW_FORM_data1:
14312       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14313       info_ptr += 1;
14314       break;
14315     case DW_FORM_flag:
14316       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14317       info_ptr += 1;
14318       break;
14319     case DW_FORM_flag_present:
14320       DW_UNSND (attr) = 1;
14321       break;
14322     case DW_FORM_sdata:
14323       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14324       info_ptr += bytes_read;
14325       break;
14326     case DW_FORM_udata:
14327       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14328       info_ptr += bytes_read;
14329       break;
14330     case DW_FORM_ref1:
14331       DW_UNSND (attr) = (cu->header.offset.sect_off
14332                          + read_1_byte (abfd, info_ptr));
14333       info_ptr += 1;
14334       break;
14335     case DW_FORM_ref2:
14336       DW_UNSND (attr) = (cu->header.offset.sect_off
14337                          + read_2_bytes (abfd, info_ptr));
14338       info_ptr += 2;
14339       break;
14340     case DW_FORM_ref4:
14341       DW_UNSND (attr) = (cu->header.offset.sect_off
14342                          + read_4_bytes (abfd, info_ptr));
14343       info_ptr += 4;
14344       break;
14345     case DW_FORM_ref8:
14346       DW_UNSND (attr) = (cu->header.offset.sect_off
14347                          + read_8_bytes (abfd, info_ptr));
14348       info_ptr += 8;
14349       break;
14350     case DW_FORM_ref_sig8:
14351       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14352       info_ptr += 8;
14353       break;
14354     case DW_FORM_ref_udata:
14355       DW_UNSND (attr) = (cu->header.offset.sect_off
14356                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14357       info_ptr += bytes_read;
14358       break;
14359     case DW_FORM_indirect:
14360       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14361       info_ptr += bytes_read;
14362       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14363       break;
14364     case DW_FORM_GNU_addr_index:
14365       if (reader->dwo_file == NULL)
14366         {
14367           /* For now flag a hard error.
14368              Later we can turn this into a complaint.  */
14369           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14370                  dwarf_form_name (form),
14371                  bfd_get_filename (abfd));
14372         }
14373       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14374       info_ptr += bytes_read;
14375       break;
14376     case DW_FORM_GNU_str_index:
14377       if (reader->dwo_file == NULL)
14378         {
14379           /* For now flag a hard error.
14380              Later we can turn this into a complaint if warranted.  */
14381           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14382                  dwarf_form_name (form),
14383                  bfd_get_filename (abfd));
14384         }
14385       {
14386         ULONGEST str_index =
14387           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14388
14389         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14390         DW_STRING_IS_CANONICAL (attr) = 0;
14391         info_ptr += bytes_read;
14392       }
14393       break;
14394     default:
14395       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14396              dwarf_form_name (form),
14397              bfd_get_filename (abfd));
14398     }
14399
14400   /* Super hack.  */
14401   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14402     attr->form = DW_FORM_GNU_ref_alt;
14403
14404   /* We have seen instances where the compiler tried to emit a byte
14405      size attribute of -1 which ended up being encoded as an unsigned
14406      0xffffffff.  Although 0xffffffff is technically a valid size value,
14407      an object of this size seems pretty unlikely so we can relatively
14408      safely treat these cases as if the size attribute was invalid and
14409      treat them as zero by default.  */
14410   if (attr->name == DW_AT_byte_size
14411       && form == DW_FORM_data4
14412       && DW_UNSND (attr) >= 0xffffffff)
14413     {
14414       complaint
14415         (&symfile_complaints,
14416          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14417          hex_string (DW_UNSND (attr)));
14418       DW_UNSND (attr) = 0;
14419     }
14420
14421   return info_ptr;
14422 }
14423
14424 /* Read an attribute described by an abbreviated attribute.  */
14425
14426 static const gdb_byte *
14427 read_attribute (const struct die_reader_specs *reader,
14428                 struct attribute *attr, struct attr_abbrev *abbrev,
14429                 const gdb_byte *info_ptr)
14430 {
14431   attr->name = abbrev->name;
14432   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14433 }
14434
14435 /* Read dwarf information from a buffer.  */
14436
14437 static unsigned int
14438 read_1_byte (bfd *abfd, const gdb_byte *buf)
14439 {
14440   return bfd_get_8 (abfd, buf);
14441 }
14442
14443 static int
14444 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14445 {
14446   return bfd_get_signed_8 (abfd, buf);
14447 }
14448
14449 static unsigned int
14450 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14451 {
14452   return bfd_get_16 (abfd, buf);
14453 }
14454
14455 static int
14456 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14457 {
14458   return bfd_get_signed_16 (abfd, buf);
14459 }
14460
14461 static unsigned int
14462 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14463 {
14464   return bfd_get_32 (abfd, buf);
14465 }
14466
14467 static int
14468 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14469 {
14470   return bfd_get_signed_32 (abfd, buf);
14471 }
14472
14473 static ULONGEST
14474 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14475 {
14476   return bfd_get_64 (abfd, buf);
14477 }
14478
14479 static CORE_ADDR
14480 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14481               unsigned int *bytes_read)
14482 {
14483   struct comp_unit_head *cu_header = &cu->header;
14484   CORE_ADDR retval = 0;
14485
14486   if (cu_header->signed_addr_p)
14487     {
14488       switch (cu_header->addr_size)
14489         {
14490         case 2:
14491           retval = bfd_get_signed_16 (abfd, buf);
14492           break;
14493         case 4:
14494           retval = bfd_get_signed_32 (abfd, buf);
14495           break;
14496         case 8:
14497           retval = bfd_get_signed_64 (abfd, buf);
14498           break;
14499         default:
14500           internal_error (__FILE__, __LINE__,
14501                           _("read_address: bad switch, signed [in module %s]"),
14502                           bfd_get_filename (abfd));
14503         }
14504     }
14505   else
14506     {
14507       switch (cu_header->addr_size)
14508         {
14509         case 2:
14510           retval = bfd_get_16 (abfd, buf);
14511           break;
14512         case 4:
14513           retval = bfd_get_32 (abfd, buf);
14514           break;
14515         case 8:
14516           retval = bfd_get_64 (abfd, buf);
14517           break;
14518         default:
14519           internal_error (__FILE__, __LINE__,
14520                           _("read_address: bad switch, "
14521                             "unsigned [in module %s]"),
14522                           bfd_get_filename (abfd));
14523         }
14524     }
14525
14526   *bytes_read = cu_header->addr_size;
14527   return retval;
14528 }
14529
14530 /* Read the initial length from a section.  The (draft) DWARF 3
14531    specification allows the initial length to take up either 4 bytes
14532    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14533    bytes describe the length and all offsets will be 8 bytes in length
14534    instead of 4.
14535
14536    An older, non-standard 64-bit format is also handled by this
14537    function.  The older format in question stores the initial length
14538    as an 8-byte quantity without an escape value.  Lengths greater
14539    than 2^32 aren't very common which means that the initial 4 bytes
14540    is almost always zero.  Since a length value of zero doesn't make
14541    sense for the 32-bit format, this initial zero can be considered to
14542    be an escape value which indicates the presence of the older 64-bit
14543    format.  As written, the code can't detect (old format) lengths
14544    greater than 4GB.  If it becomes necessary to handle lengths
14545    somewhat larger than 4GB, we could allow other small values (such
14546    as the non-sensical values of 1, 2, and 3) to also be used as
14547    escape values indicating the presence of the old format.
14548
14549    The value returned via bytes_read should be used to increment the
14550    relevant pointer after calling read_initial_length().
14551
14552    [ Note:  read_initial_length() and read_offset() are based on the
14553      document entitled "DWARF Debugging Information Format", revision
14554      3, draft 8, dated November 19, 2001.  This document was obtained
14555      from:
14556
14557         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14558
14559      This document is only a draft and is subject to change.  (So beware.)
14560
14561      Details regarding the older, non-standard 64-bit format were
14562      determined empirically by examining 64-bit ELF files produced by
14563      the SGI toolchain on an IRIX 6.5 machine.
14564
14565      - Kevin, July 16, 2002
14566    ] */
14567
14568 static LONGEST
14569 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
14570 {
14571   LONGEST length = bfd_get_32 (abfd, buf);
14572
14573   if (length == 0xffffffff)
14574     {
14575       length = bfd_get_64 (abfd, buf + 4);
14576       *bytes_read = 12;
14577     }
14578   else if (length == 0)
14579     {
14580       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14581       length = bfd_get_64 (abfd, buf);
14582       *bytes_read = 8;
14583     }
14584   else
14585     {
14586       *bytes_read = 4;
14587     }
14588
14589   return length;
14590 }
14591
14592 /* Cover function for read_initial_length.
14593    Returns the length of the object at BUF, and stores the size of the
14594    initial length in *BYTES_READ and stores the size that offsets will be in
14595    *OFFSET_SIZE.
14596    If the initial length size is not equivalent to that specified in
14597    CU_HEADER then issue a complaint.
14598    This is useful when reading non-comp-unit headers.  */
14599
14600 static LONGEST
14601 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
14602                                         const struct comp_unit_head *cu_header,
14603                                         unsigned int *bytes_read,
14604                                         unsigned int *offset_size)
14605 {
14606   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14607
14608   gdb_assert (cu_header->initial_length_size == 4
14609               || cu_header->initial_length_size == 8
14610               || cu_header->initial_length_size == 12);
14611
14612   if (cu_header->initial_length_size != *bytes_read)
14613     complaint (&symfile_complaints,
14614                _("intermixed 32-bit and 64-bit DWARF sections"));
14615
14616   *offset_size = (*bytes_read == 4) ? 4 : 8;
14617   return length;
14618 }
14619
14620 /* Read an offset from the data stream.  The size of the offset is
14621    given by cu_header->offset_size.  */
14622
14623 static LONGEST
14624 read_offset (bfd *abfd, const gdb_byte *buf,
14625              const struct comp_unit_head *cu_header,
14626              unsigned int *bytes_read)
14627 {
14628   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14629
14630   *bytes_read = cu_header->offset_size;
14631   return offset;
14632 }
14633
14634 /* Read an offset from the data stream.  */
14635
14636 static LONGEST
14637 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
14638 {
14639   LONGEST retval = 0;
14640
14641   switch (offset_size)
14642     {
14643     case 4:
14644       retval = bfd_get_32 (abfd, buf);
14645       break;
14646     case 8:
14647       retval = bfd_get_64 (abfd, buf);
14648       break;
14649     default:
14650       internal_error (__FILE__, __LINE__,
14651                       _("read_offset_1: bad switch [in module %s]"),
14652                       bfd_get_filename (abfd));
14653     }
14654
14655   return retval;
14656 }
14657
14658 static const gdb_byte *
14659 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
14660 {
14661   /* If the size of a host char is 8 bits, we can return a pointer
14662      to the buffer, otherwise we have to copy the data to a buffer
14663      allocated on the temporary obstack.  */
14664   gdb_assert (HOST_CHAR_BIT == 8);
14665   return buf;
14666 }
14667
14668 static const char *
14669 read_direct_string (bfd *abfd, const gdb_byte *buf,
14670                     unsigned int *bytes_read_ptr)
14671 {
14672   /* If the size of a host char is 8 bits, we can return a pointer
14673      to the string, otherwise we have to copy the string to a buffer
14674      allocated on the temporary obstack.  */
14675   gdb_assert (HOST_CHAR_BIT == 8);
14676   if (*buf == '\0')
14677     {
14678       *bytes_read_ptr = 1;
14679       return NULL;
14680     }
14681   *bytes_read_ptr = strlen ((const char *) buf) + 1;
14682   return (const char *) buf;
14683 }
14684
14685 static const char *
14686 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14687 {
14688   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14689   if (dwarf2_per_objfile->str.buffer == NULL)
14690     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14691            bfd_get_filename (abfd));
14692   if (str_offset >= dwarf2_per_objfile->str.size)
14693     error (_("DW_FORM_strp pointing outside of "
14694              ".debug_str section [in module %s]"),
14695            bfd_get_filename (abfd));
14696   gdb_assert (HOST_CHAR_BIT == 8);
14697   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14698     return NULL;
14699   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
14700 }
14701
14702 /* Read a string at offset STR_OFFSET in the .debug_str section from
14703    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14704    the string consists of a single NUL byte, return NULL; otherwise
14705    return a pointer to the string.  */
14706
14707 static const char *
14708 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14709 {
14710   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14711
14712   if (dwz->str.buffer == NULL)
14713     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14714              "section [in module %s]"),
14715            bfd_get_filename (dwz->dwz_bfd));
14716   if (str_offset >= dwz->str.size)
14717     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14718              ".debug_str section [in module %s]"),
14719            bfd_get_filename (dwz->dwz_bfd));
14720   gdb_assert (HOST_CHAR_BIT == 8);
14721   if (dwz->str.buffer[str_offset] == '\0')
14722     return NULL;
14723   return (const char *) (dwz->str.buffer + str_offset);
14724 }
14725
14726 static const char *
14727 read_indirect_string (bfd *abfd, const gdb_byte *buf,
14728                       const struct comp_unit_head *cu_header,
14729                       unsigned int *bytes_read_ptr)
14730 {
14731   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14732
14733   return read_indirect_string_at_offset (abfd, str_offset);
14734 }
14735
14736 static ULONGEST
14737 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
14738                       unsigned int *bytes_read_ptr)
14739 {
14740   ULONGEST result;
14741   unsigned int num_read;
14742   int i, shift;
14743   unsigned char byte;
14744
14745   result = 0;
14746   shift = 0;
14747   num_read = 0;
14748   i = 0;
14749   while (1)
14750     {
14751       byte = bfd_get_8 (abfd, buf);
14752       buf++;
14753       num_read++;
14754       result |= ((ULONGEST) (byte & 127) << shift);
14755       if ((byte & 128) == 0)
14756         {
14757           break;
14758         }
14759       shift += 7;
14760     }
14761   *bytes_read_ptr = num_read;
14762   return result;
14763 }
14764
14765 static LONGEST
14766 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
14767                     unsigned int *bytes_read_ptr)
14768 {
14769   LONGEST result;
14770   int i, shift, num_read;
14771   unsigned char byte;
14772
14773   result = 0;
14774   shift = 0;
14775   num_read = 0;
14776   i = 0;
14777   while (1)
14778     {
14779       byte = bfd_get_8 (abfd, buf);
14780       buf++;
14781       num_read++;
14782       result |= ((LONGEST) (byte & 127) << shift);
14783       shift += 7;
14784       if ((byte & 128) == 0)
14785         {
14786           break;
14787         }
14788     }
14789   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14790     result |= -(((LONGEST) 1) << shift);
14791   *bytes_read_ptr = num_read;
14792   return result;
14793 }
14794
14795 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14796    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14797    ADDR_SIZE is the size of addresses from the CU header.  */
14798
14799 static CORE_ADDR
14800 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14801 {
14802   struct objfile *objfile = dwarf2_per_objfile->objfile;
14803   bfd *abfd = objfile->obfd;
14804   const gdb_byte *info_ptr;
14805
14806   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14807   if (dwarf2_per_objfile->addr.buffer == NULL)
14808     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14809            objfile->name);
14810   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14811     error (_("DW_FORM_addr_index pointing outside of "
14812              ".debug_addr section [in module %s]"),
14813            objfile->name);
14814   info_ptr = (dwarf2_per_objfile->addr.buffer
14815               + addr_base + addr_index * addr_size);
14816   if (addr_size == 4)
14817     return bfd_get_32 (abfd, info_ptr);
14818   else
14819     return bfd_get_64 (abfd, info_ptr);
14820 }
14821
14822 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14823
14824 static CORE_ADDR
14825 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14826 {
14827   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14828 }
14829
14830 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14831
14832 static CORE_ADDR
14833 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
14834                              unsigned int *bytes_read)
14835 {
14836   bfd *abfd = cu->objfile->obfd;
14837   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14838
14839   return read_addr_index (cu, addr_index);
14840 }
14841
14842 /* Data structure to pass results from dwarf2_read_addr_index_reader
14843    back to dwarf2_read_addr_index.  */
14844
14845 struct dwarf2_read_addr_index_data
14846 {
14847   ULONGEST addr_base;
14848   int addr_size;
14849 };
14850
14851 /* die_reader_func for dwarf2_read_addr_index.  */
14852
14853 static void
14854 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14855                                const gdb_byte *info_ptr,
14856                                struct die_info *comp_unit_die,
14857                                int has_children,
14858                                void *data)
14859 {
14860   struct dwarf2_cu *cu = reader->cu;
14861   struct dwarf2_read_addr_index_data *aidata =
14862     (struct dwarf2_read_addr_index_data *) data;
14863
14864   aidata->addr_base = cu->addr_base;
14865   aidata->addr_size = cu->header.addr_size;
14866 }
14867
14868 /* Given an index in .debug_addr, fetch the value.
14869    NOTE: This can be called during dwarf expression evaluation,
14870    long after the debug information has been read, and thus per_cu->cu
14871    may no longer exist.  */
14872
14873 CORE_ADDR
14874 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14875                         unsigned int addr_index)
14876 {
14877   struct objfile *objfile = per_cu->objfile;
14878   struct dwarf2_cu *cu = per_cu->cu;
14879   ULONGEST addr_base;
14880   int addr_size;
14881
14882   /* This is intended to be called from outside this file.  */
14883   dw2_setup (objfile);
14884
14885   /* We need addr_base and addr_size.
14886      If we don't have PER_CU->cu, we have to get it.
14887      Nasty, but the alternative is storing the needed info in PER_CU,
14888      which at this point doesn't seem justified: it's not clear how frequently
14889      it would get used and it would increase the size of every PER_CU.
14890      Entry points like dwarf2_per_cu_addr_size do a similar thing
14891      so we're not in uncharted territory here.
14892      Alas we need to be a bit more complicated as addr_base is contained
14893      in the DIE.
14894
14895      We don't need to read the entire CU(/TU).
14896      We just need the header and top level die.
14897
14898      IWBN to use the aging mechanism to let us lazily later discard the CU.
14899      For now we skip this optimization.  */
14900
14901   if (cu != NULL)
14902     {
14903       addr_base = cu->addr_base;
14904       addr_size = cu->header.addr_size;
14905     }
14906   else
14907     {
14908       struct dwarf2_read_addr_index_data aidata;
14909
14910       /* Note: We can't use init_cutu_and_read_dies_simple here,
14911          we need addr_base.  */
14912       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14913                                dwarf2_read_addr_index_reader, &aidata);
14914       addr_base = aidata.addr_base;
14915       addr_size = aidata.addr_size;
14916     }
14917
14918   return read_addr_index_1 (addr_index, addr_base, addr_size);
14919 }
14920
14921 /* Given a DW_AT_str_index, fetch the string.  */
14922
14923 static const char *
14924 read_str_index (const struct die_reader_specs *reader,
14925                 struct dwarf2_cu *cu, ULONGEST str_index)
14926 {
14927   struct objfile *objfile = dwarf2_per_objfile->objfile;
14928   const char *dwo_name = objfile->name;
14929   bfd *abfd = objfile->obfd;
14930   struct dwo_sections *sections = &reader->dwo_file->sections;
14931   const gdb_byte *info_ptr;
14932   ULONGEST str_offset;
14933
14934   dwarf2_read_section (objfile, &sections->str);
14935   dwarf2_read_section (objfile, &sections->str_offsets);
14936   if (sections->str.buffer == NULL)
14937     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14938              " in CU at offset 0x%lx [in module %s]"),
14939            (long) cu->header.offset.sect_off, dwo_name);
14940   if (sections->str_offsets.buffer == NULL)
14941     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14942              " in CU at offset 0x%lx [in module %s]"),
14943            (long) cu->header.offset.sect_off, dwo_name);
14944   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14945     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14946              " section in CU at offset 0x%lx [in module %s]"),
14947            (long) cu->header.offset.sect_off, dwo_name);
14948   info_ptr = (sections->str_offsets.buffer
14949               + str_index * cu->header.offset_size);
14950   if (cu->header.offset_size == 4)
14951     str_offset = bfd_get_32 (abfd, info_ptr);
14952   else
14953     str_offset = bfd_get_64 (abfd, info_ptr);
14954   if (str_offset >= sections->str.size)
14955     error (_("Offset from DW_FORM_str_index pointing outside of"
14956              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14957            (long) cu->header.offset.sect_off, dwo_name);
14958   return (const char *) (sections->str.buffer + str_offset);
14959 }
14960
14961 /* Return the length of an LEB128 number in BUF.  */
14962
14963 static int
14964 leb128_size (const gdb_byte *buf)
14965 {
14966   const gdb_byte *begin = buf;
14967   gdb_byte byte;
14968
14969   while (1)
14970     {
14971       byte = *buf++;
14972       if ((byte & 128) == 0)
14973         return buf - begin;
14974     }
14975 }
14976
14977 static void
14978 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14979 {
14980   switch (lang)
14981     {
14982     case DW_LANG_C89:
14983     case DW_LANG_C99:
14984     case DW_LANG_C:
14985       cu->language = language_c;
14986       break;
14987     case DW_LANG_C_plus_plus:
14988       cu->language = language_cplus;
14989       break;
14990     case DW_LANG_D:
14991       cu->language = language_d;
14992       break;
14993     case DW_LANG_Fortran77:
14994     case DW_LANG_Fortran90:
14995     case DW_LANG_Fortran95:
14996       cu->language = language_fortran;
14997       break;
14998     case DW_LANG_Go:
14999       cu->language = language_go;
15000       break;
15001     case DW_LANG_Mips_Assembler:
15002       cu->language = language_asm;
15003       break;
15004     case DW_LANG_Java:
15005       cu->language = language_java;
15006       break;
15007     case DW_LANG_Ada83:
15008     case DW_LANG_Ada95:
15009       cu->language = language_ada;
15010       break;
15011     case DW_LANG_Modula2:
15012       cu->language = language_m2;
15013       break;
15014     case DW_LANG_Pascal83:
15015       cu->language = language_pascal;
15016       break;
15017     case DW_LANG_ObjC:
15018       cu->language = language_objc;
15019       break;
15020     case DW_LANG_Cobol74:
15021     case DW_LANG_Cobol85:
15022     default:
15023       cu->language = language_minimal;
15024       break;
15025     }
15026   cu->language_defn = language_def (cu->language);
15027 }
15028
15029 /* Return the named attribute or NULL if not there.  */
15030
15031 static struct attribute *
15032 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15033 {
15034   for (;;)
15035     {
15036       unsigned int i;
15037       struct attribute *spec = NULL;
15038
15039       for (i = 0; i < die->num_attrs; ++i)
15040         {
15041           if (die->attrs[i].name == name)
15042             return &die->attrs[i];
15043           if (die->attrs[i].name == DW_AT_specification
15044               || die->attrs[i].name == DW_AT_abstract_origin)
15045             spec = &die->attrs[i];
15046         }
15047
15048       if (!spec)
15049         break;
15050
15051       die = follow_die_ref (die, spec, &cu);
15052     }
15053
15054   return NULL;
15055 }
15056
15057 /* Return the named attribute or NULL if not there,
15058    but do not follow DW_AT_specification, etc.
15059    This is for use in contexts where we're reading .debug_types dies.
15060    Following DW_AT_specification, DW_AT_abstract_origin will take us
15061    back up the chain, and we want to go down.  */
15062
15063 static struct attribute *
15064 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15065 {
15066   unsigned int i;
15067
15068   for (i = 0; i < die->num_attrs; ++i)
15069     if (die->attrs[i].name == name)
15070       return &die->attrs[i];
15071
15072   return NULL;
15073 }
15074
15075 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15076    and holds a non-zero value.  This function should only be used for
15077    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15078
15079 static int
15080 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15081 {
15082   struct attribute *attr = dwarf2_attr (die, name, cu);
15083
15084   return (attr && DW_UNSND (attr));
15085 }
15086
15087 static int
15088 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15089 {
15090   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15091      which value is non-zero.  However, we have to be careful with
15092      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15093      (via dwarf2_flag_true_p) follows this attribute.  So we may
15094      end up accidently finding a declaration attribute that belongs
15095      to a different DIE referenced by the specification attribute,
15096      even though the given DIE does not have a declaration attribute.  */
15097   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15098           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15099 }
15100
15101 /* Return the die giving the specification for DIE, if there is
15102    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15103    containing the return value on output.  If there is no
15104    specification, but there is an abstract origin, that is
15105    returned.  */
15106
15107 static struct die_info *
15108 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15109 {
15110   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15111                                              *spec_cu);
15112
15113   if (spec_attr == NULL)
15114     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15115
15116   if (spec_attr == NULL)
15117     return NULL;
15118   else
15119     return follow_die_ref (die, spec_attr, spec_cu);
15120 }
15121
15122 /* Free the line_header structure *LH, and any arrays and strings it
15123    refers to.
15124    NOTE: This is also used as a "cleanup" function.  */
15125
15126 static void
15127 free_line_header (struct line_header *lh)
15128 {
15129   if (lh->standard_opcode_lengths)
15130     xfree (lh->standard_opcode_lengths);
15131
15132   /* Remember that all the lh->file_names[i].name pointers are
15133      pointers into debug_line_buffer, and don't need to be freed.  */
15134   if (lh->file_names)
15135     xfree (lh->file_names);
15136
15137   /* Similarly for the include directory names.  */
15138   if (lh->include_dirs)
15139     xfree (lh->include_dirs);
15140
15141   xfree (lh);
15142 }
15143
15144 /* Add an entry to LH's include directory table.  */
15145
15146 static void
15147 add_include_dir (struct line_header *lh, const char *include_dir)
15148 {
15149   /* Grow the array if necessary.  */
15150   if (lh->include_dirs_size == 0)
15151     {
15152       lh->include_dirs_size = 1; /* for testing */
15153       lh->include_dirs = xmalloc (lh->include_dirs_size
15154                                   * sizeof (*lh->include_dirs));
15155     }
15156   else if (lh->num_include_dirs >= lh->include_dirs_size)
15157     {
15158       lh->include_dirs_size *= 2;
15159       lh->include_dirs = xrealloc (lh->include_dirs,
15160                                    (lh->include_dirs_size
15161                                     * sizeof (*lh->include_dirs)));
15162     }
15163
15164   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15165 }
15166
15167 /* Add an entry to LH's file name table.  */
15168
15169 static void
15170 add_file_name (struct line_header *lh,
15171                const char *name,
15172                unsigned int dir_index,
15173                unsigned int mod_time,
15174                unsigned int length)
15175 {
15176   struct file_entry *fe;
15177
15178   /* Grow the array if necessary.  */
15179   if (lh->file_names_size == 0)
15180     {
15181       lh->file_names_size = 1; /* for testing */
15182       lh->file_names = xmalloc (lh->file_names_size
15183                                 * sizeof (*lh->file_names));
15184     }
15185   else if (lh->num_file_names >= lh->file_names_size)
15186     {
15187       lh->file_names_size *= 2;
15188       lh->file_names = xrealloc (lh->file_names,
15189                                  (lh->file_names_size
15190                                   * sizeof (*lh->file_names)));
15191     }
15192
15193   fe = &lh->file_names[lh->num_file_names++];
15194   fe->name = name;
15195   fe->dir_index = dir_index;
15196   fe->mod_time = mod_time;
15197   fe->length = length;
15198   fe->included_p = 0;
15199   fe->symtab = NULL;
15200 }
15201
15202 /* A convenience function to find the proper .debug_line section for a
15203    CU.  */
15204
15205 static struct dwarf2_section_info *
15206 get_debug_line_section (struct dwarf2_cu *cu)
15207 {
15208   struct dwarf2_section_info *section;
15209
15210   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15211      DWO file.  */
15212   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15213     section = &cu->dwo_unit->dwo_file->sections.line;
15214   else if (cu->per_cu->is_dwz)
15215     {
15216       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15217
15218       section = &dwz->line;
15219     }
15220   else
15221     section = &dwarf2_per_objfile->line;
15222
15223   return section;
15224 }
15225
15226 /* Read the statement program header starting at OFFSET in
15227    .debug_line, or .debug_line.dwo.  Return a pointer
15228    to a struct line_header, allocated using xmalloc.
15229
15230    NOTE: the strings in the include directory and file name tables of
15231    the returned object point into the dwarf line section buffer,
15232    and must not be freed.  */
15233
15234 static struct line_header *
15235 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15236 {
15237   struct cleanup *back_to;
15238   struct line_header *lh;
15239   const gdb_byte *line_ptr;
15240   unsigned int bytes_read, offset_size;
15241   int i;
15242   const char *cur_dir, *cur_file;
15243   struct dwarf2_section_info *section;
15244   bfd *abfd;
15245
15246   section = get_debug_line_section (cu);
15247   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15248   if (section->buffer == NULL)
15249     {
15250       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15251         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15252       else
15253         complaint (&symfile_complaints, _("missing .debug_line section"));
15254       return 0;
15255     }
15256
15257   /* We can't do this until we know the section is non-empty.
15258      Only then do we know we have such a section.  */
15259   abfd = section->asection->owner;
15260
15261   /* Make sure that at least there's room for the total_length field.
15262      That could be 12 bytes long, but we're just going to fudge that.  */
15263   if (offset + 4 >= section->size)
15264     {
15265       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15266       return 0;
15267     }
15268
15269   lh = xmalloc (sizeof (*lh));
15270   memset (lh, 0, sizeof (*lh));
15271   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15272                           (void *) lh);
15273
15274   line_ptr = section->buffer + offset;
15275
15276   /* Read in the header.  */
15277   lh->total_length =
15278     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15279                                             &bytes_read, &offset_size);
15280   line_ptr += bytes_read;
15281   if (line_ptr + lh->total_length > (section->buffer + section->size))
15282     {
15283       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15284       return 0;
15285     }
15286   lh->statement_program_end = line_ptr + lh->total_length;
15287   lh->version = read_2_bytes (abfd, line_ptr);
15288   line_ptr += 2;
15289   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15290   line_ptr += offset_size;
15291   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15292   line_ptr += 1;
15293   if (lh->version >= 4)
15294     {
15295       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15296       line_ptr += 1;
15297     }
15298   else
15299     lh->maximum_ops_per_instruction = 1;
15300
15301   if (lh->maximum_ops_per_instruction == 0)
15302     {
15303       lh->maximum_ops_per_instruction = 1;
15304       complaint (&symfile_complaints,
15305                  _("invalid maximum_ops_per_instruction "
15306                    "in `.debug_line' section"));
15307     }
15308
15309   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15310   line_ptr += 1;
15311   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15312   line_ptr += 1;
15313   lh->line_range = read_1_byte (abfd, line_ptr);
15314   line_ptr += 1;
15315   lh->opcode_base = read_1_byte (abfd, line_ptr);
15316   line_ptr += 1;
15317   lh->standard_opcode_lengths
15318     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15319
15320   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15321   for (i = 1; i < lh->opcode_base; ++i)
15322     {
15323       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15324       line_ptr += 1;
15325     }
15326
15327   /* Read directory table.  */
15328   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15329     {
15330       line_ptr += bytes_read;
15331       add_include_dir (lh, cur_dir);
15332     }
15333   line_ptr += bytes_read;
15334
15335   /* Read file name table.  */
15336   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15337     {
15338       unsigned int dir_index, mod_time, length;
15339
15340       line_ptr += bytes_read;
15341       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15342       line_ptr += bytes_read;
15343       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15344       line_ptr += bytes_read;
15345       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15346       line_ptr += bytes_read;
15347
15348       add_file_name (lh, cur_file, dir_index, mod_time, length);
15349     }
15350   line_ptr += bytes_read;
15351   lh->statement_program_start = line_ptr;
15352
15353   if (line_ptr > (section->buffer + section->size))
15354     complaint (&symfile_complaints,
15355                _("line number info header doesn't "
15356                  "fit in `.debug_line' section"));
15357
15358   discard_cleanups (back_to);
15359   return lh;
15360 }
15361
15362 /* Subroutine of dwarf_decode_lines to simplify it.
15363    Return the file name of the psymtab for included file FILE_INDEX
15364    in line header LH of PST.
15365    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15366    If space for the result is malloc'd, it will be freed by a cleanup.
15367    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15368
15369    The function creates dangling cleanup registration.  */
15370
15371 static const char *
15372 psymtab_include_file_name (const struct line_header *lh, int file_index,
15373                            const struct partial_symtab *pst,
15374                            const char *comp_dir)
15375 {
15376   const struct file_entry fe = lh->file_names [file_index];
15377   const char *include_name = fe.name;
15378   const char *include_name_to_compare = include_name;
15379   const char *dir_name = NULL;
15380   const char *pst_filename;
15381   char *copied_name = NULL;
15382   int file_is_pst;
15383
15384   if (fe.dir_index)
15385     dir_name = lh->include_dirs[fe.dir_index - 1];
15386
15387   if (!IS_ABSOLUTE_PATH (include_name)
15388       && (dir_name != NULL || comp_dir != NULL))
15389     {
15390       /* Avoid creating a duplicate psymtab for PST.
15391          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15392          Before we do the comparison, however, we need to account
15393          for DIR_NAME and COMP_DIR.
15394          First prepend dir_name (if non-NULL).  If we still don't
15395          have an absolute path prepend comp_dir (if non-NULL).
15396          However, the directory we record in the include-file's
15397          psymtab does not contain COMP_DIR (to match the
15398          corresponding symtab(s)).
15399
15400          Example:
15401
15402          bash$ cd /tmp
15403          bash$ gcc -g ./hello.c
15404          include_name = "hello.c"
15405          dir_name = "."
15406          DW_AT_comp_dir = comp_dir = "/tmp"
15407          DW_AT_name = "./hello.c"  */
15408
15409       if (dir_name != NULL)
15410         {
15411           char *tem = concat (dir_name, SLASH_STRING,
15412                               include_name, (char *)NULL);
15413
15414           make_cleanup (xfree, tem);
15415           include_name = tem;
15416           include_name_to_compare = include_name;
15417         }
15418       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15419         {
15420           char *tem = concat (comp_dir, SLASH_STRING,
15421                               include_name, (char *)NULL);
15422
15423           make_cleanup (xfree, tem);
15424           include_name_to_compare = tem;
15425         }
15426     }
15427
15428   pst_filename = pst->filename;
15429   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15430     {
15431       copied_name = concat (pst->dirname, SLASH_STRING,
15432                             pst_filename, (char *)NULL);
15433       pst_filename = copied_name;
15434     }
15435
15436   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15437
15438   if (copied_name != NULL)
15439     xfree (copied_name);
15440
15441   if (file_is_pst)
15442     return NULL;
15443   return include_name;
15444 }
15445
15446 /* Ignore this record_line request.  */
15447
15448 static void
15449 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15450 {
15451   return;
15452 }
15453
15454 /* Subroutine of dwarf_decode_lines to simplify it.
15455    Process the line number information in LH.  */
15456
15457 static void
15458 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15459                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15460 {
15461   const gdb_byte *line_ptr, *extended_end;
15462   const gdb_byte *line_end;
15463   unsigned int bytes_read, extended_len;
15464   unsigned char op_code, extended_op, adj_opcode;
15465   CORE_ADDR baseaddr;
15466   struct objfile *objfile = cu->objfile;
15467   bfd *abfd = objfile->obfd;
15468   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15469   const int decode_for_pst_p = (pst != NULL);
15470   struct subfile *last_subfile = NULL;
15471   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15472     = record_line;
15473
15474   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15475
15476   line_ptr = lh->statement_program_start;
15477   line_end = lh->statement_program_end;
15478
15479   /* Read the statement sequences until there's nothing left.  */
15480   while (line_ptr < line_end)
15481     {
15482       /* state machine registers  */
15483       CORE_ADDR address = 0;
15484       unsigned int file = 1;
15485       unsigned int line = 1;
15486       unsigned int column = 0;
15487       int is_stmt = lh->default_is_stmt;
15488       int basic_block = 0;
15489       int end_sequence = 0;
15490       CORE_ADDR addr;
15491       unsigned char op_index = 0;
15492
15493       if (!decode_for_pst_p && lh->num_file_names >= file)
15494         {
15495           /* Start a subfile for the current file of the state machine.  */
15496           /* lh->include_dirs and lh->file_names are 0-based, but the
15497              directory and file name numbers in the statement program
15498              are 1-based.  */
15499           struct file_entry *fe = &lh->file_names[file - 1];
15500           const char *dir = NULL;
15501
15502           if (fe->dir_index)
15503             dir = lh->include_dirs[fe->dir_index - 1];
15504
15505           dwarf2_start_subfile (fe->name, dir, comp_dir);
15506         }
15507
15508       /* Decode the table.  */
15509       while (!end_sequence)
15510         {
15511           op_code = read_1_byte (abfd, line_ptr);
15512           line_ptr += 1;
15513           if (line_ptr > line_end)
15514             {
15515               dwarf2_debug_line_missing_end_sequence_complaint ();
15516               break;
15517             }
15518
15519           if (op_code >= lh->opcode_base)
15520             {
15521               /* Special operand.  */
15522               adj_opcode = op_code - lh->opcode_base;
15523               address += (((op_index + (adj_opcode / lh->line_range))
15524                            / lh->maximum_ops_per_instruction)
15525                           * lh->minimum_instruction_length);
15526               op_index = ((op_index + (adj_opcode / lh->line_range))
15527                           % lh->maximum_ops_per_instruction);
15528               line += lh->line_base + (adj_opcode % lh->line_range);
15529               if (lh->num_file_names < file || file == 0)
15530                 dwarf2_debug_line_missing_file_complaint ();
15531               /* For now we ignore lines not starting on an
15532                  instruction boundary.  */
15533               else if (op_index == 0)
15534                 {
15535                   lh->file_names[file - 1].included_p = 1;
15536                   if (!decode_for_pst_p && is_stmt)
15537                     {
15538                       if (last_subfile != current_subfile)
15539                         {
15540                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15541                           if (last_subfile)
15542                             (*p_record_line) (last_subfile, 0, addr);
15543                           last_subfile = current_subfile;
15544                         }
15545                       /* Append row to matrix using current values.  */
15546                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15547                       (*p_record_line) (current_subfile, line, addr);
15548                     }
15549                 }
15550               basic_block = 0;
15551             }
15552           else switch (op_code)
15553             {
15554             case DW_LNS_extended_op:
15555               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15556                                                    &bytes_read);
15557               line_ptr += bytes_read;
15558               extended_end = line_ptr + extended_len;
15559               extended_op = read_1_byte (abfd, line_ptr);
15560               line_ptr += 1;
15561               switch (extended_op)
15562                 {
15563                 case DW_LNE_end_sequence:
15564                   p_record_line = record_line;
15565                   end_sequence = 1;
15566                   break;
15567                 case DW_LNE_set_address:
15568                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15569
15570                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15571                     {
15572                       /* This line table is for a function which has been
15573                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15574
15575                       long line_offset
15576                         = line_ptr - get_debug_line_section (cu)->buffer;
15577
15578                       complaint (&symfile_complaints,
15579                                  _(".debug_line address at offset 0x%lx is 0 "
15580                                    "[in module %s]"),
15581                                  line_offset, objfile->name);
15582                       p_record_line = noop_record_line;
15583                     }
15584
15585                   op_index = 0;
15586                   line_ptr += bytes_read;
15587                   address += baseaddr;
15588                   break;
15589                 case DW_LNE_define_file:
15590                   {
15591                     const char *cur_file;
15592                     unsigned int dir_index, mod_time, length;
15593
15594                     cur_file = read_direct_string (abfd, line_ptr,
15595                                                    &bytes_read);
15596                     line_ptr += bytes_read;
15597                     dir_index =
15598                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15599                     line_ptr += bytes_read;
15600                     mod_time =
15601                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15602                     line_ptr += bytes_read;
15603                     length =
15604                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15605                     line_ptr += bytes_read;
15606                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15607                   }
15608                   break;
15609                 case DW_LNE_set_discriminator:
15610                   /* The discriminator is not interesting to the debugger;
15611                      just ignore it.  */
15612                   line_ptr = extended_end;
15613                   break;
15614                 default:
15615                   complaint (&symfile_complaints,
15616                              _("mangled .debug_line section"));
15617                   return;
15618                 }
15619               /* Make sure that we parsed the extended op correctly.  If e.g.
15620                  we expected a different address size than the producer used,
15621                  we may have read the wrong number of bytes.  */
15622               if (line_ptr != extended_end)
15623                 {
15624                   complaint (&symfile_complaints,
15625                              _("mangled .debug_line section"));
15626                   return;
15627                 }
15628               break;
15629             case DW_LNS_copy:
15630               if (lh->num_file_names < file || file == 0)
15631                 dwarf2_debug_line_missing_file_complaint ();
15632               else
15633                 {
15634                   lh->file_names[file - 1].included_p = 1;
15635                   if (!decode_for_pst_p && is_stmt)
15636                     {
15637                       if (last_subfile != current_subfile)
15638                         {
15639                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15640                           if (last_subfile)
15641                             (*p_record_line) (last_subfile, 0, addr);
15642                           last_subfile = current_subfile;
15643                         }
15644                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15645                       (*p_record_line) (current_subfile, line, addr);
15646                     }
15647                 }
15648               basic_block = 0;
15649               break;
15650             case DW_LNS_advance_pc:
15651               {
15652                 CORE_ADDR adjust
15653                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15654
15655                 address += (((op_index + adjust)
15656                              / lh->maximum_ops_per_instruction)
15657                             * lh->minimum_instruction_length);
15658                 op_index = ((op_index + adjust)
15659                             % lh->maximum_ops_per_instruction);
15660                 line_ptr += bytes_read;
15661               }
15662               break;
15663             case DW_LNS_advance_line:
15664               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15665               line_ptr += bytes_read;
15666               break;
15667             case DW_LNS_set_file:
15668               {
15669                 /* The arrays lh->include_dirs and lh->file_names are
15670                    0-based, but the directory and file name numbers in
15671                    the statement program are 1-based.  */
15672                 struct file_entry *fe;
15673                 const char *dir = NULL;
15674
15675                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15676                 line_ptr += bytes_read;
15677                 if (lh->num_file_names < file || file == 0)
15678                   dwarf2_debug_line_missing_file_complaint ();
15679                 else
15680                   {
15681                     fe = &lh->file_names[file - 1];
15682                     if (fe->dir_index)
15683                       dir = lh->include_dirs[fe->dir_index - 1];
15684                     if (!decode_for_pst_p)
15685                       {
15686                         last_subfile = current_subfile;
15687                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15688                       }
15689                   }
15690               }
15691               break;
15692             case DW_LNS_set_column:
15693               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15694               line_ptr += bytes_read;
15695               break;
15696             case DW_LNS_negate_stmt:
15697               is_stmt = (!is_stmt);
15698               break;
15699             case DW_LNS_set_basic_block:
15700               basic_block = 1;
15701               break;
15702             /* Add to the address register of the state machine the
15703                address increment value corresponding to special opcode
15704                255.  I.e., this value is scaled by the minimum
15705                instruction length since special opcode 255 would have
15706                scaled the increment.  */
15707             case DW_LNS_const_add_pc:
15708               {
15709                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15710
15711                 address += (((op_index + adjust)
15712                              / lh->maximum_ops_per_instruction)
15713                             * lh->minimum_instruction_length);
15714                 op_index = ((op_index + adjust)
15715                             % lh->maximum_ops_per_instruction);
15716               }
15717               break;
15718             case DW_LNS_fixed_advance_pc:
15719               address += read_2_bytes (abfd, line_ptr);
15720               op_index = 0;
15721               line_ptr += 2;
15722               break;
15723             default:
15724               {
15725                 /* Unknown standard opcode, ignore it.  */
15726                 int i;
15727
15728                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15729                   {
15730                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15731                     line_ptr += bytes_read;
15732                   }
15733               }
15734             }
15735         }
15736       if (lh->num_file_names < file || file == 0)
15737         dwarf2_debug_line_missing_file_complaint ();
15738       else
15739         {
15740           lh->file_names[file - 1].included_p = 1;
15741           if (!decode_for_pst_p)
15742             {
15743               addr = gdbarch_addr_bits_remove (gdbarch, address);
15744               (*p_record_line) (current_subfile, 0, addr);
15745             }
15746         }
15747     }
15748 }
15749
15750 /* Decode the Line Number Program (LNP) for the given line_header
15751    structure and CU.  The actual information extracted and the type
15752    of structures created from the LNP depends on the value of PST.
15753
15754    1. If PST is NULL, then this procedure uses the data from the program
15755       to create all necessary symbol tables, and their linetables.
15756
15757    2. If PST is not NULL, this procedure reads the program to determine
15758       the list of files included by the unit represented by PST, and
15759       builds all the associated partial symbol tables.
15760
15761    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15762    It is used for relative paths in the line table.
15763    NOTE: When processing partial symtabs (pst != NULL),
15764    comp_dir == pst->dirname.
15765
15766    NOTE: It is important that psymtabs have the same file name (via strcmp)
15767    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15768    symtab we don't use it in the name of the psymtabs we create.
15769    E.g. expand_line_sal requires this when finding psymtabs to expand.
15770    A good testcase for this is mb-inline.exp.  */
15771
15772 static void
15773 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15774                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15775                     int want_line_info)
15776 {
15777   struct objfile *objfile = cu->objfile;
15778   const int decode_for_pst_p = (pst != NULL);
15779   struct subfile *first_subfile = current_subfile;
15780
15781   if (want_line_info)
15782     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15783
15784   if (decode_for_pst_p)
15785     {
15786       int file_index;
15787
15788       /* Now that we're done scanning the Line Header Program, we can
15789          create the psymtab of each included file.  */
15790       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15791         if (lh->file_names[file_index].included_p == 1)
15792           {
15793             const char *include_name =
15794               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15795             if (include_name != NULL)
15796               dwarf2_create_include_psymtab (include_name, pst, objfile);
15797           }
15798     }
15799   else
15800     {
15801       /* Make sure a symtab is created for every file, even files
15802          which contain only variables (i.e. no code with associated
15803          line numbers).  */
15804       int i;
15805
15806       for (i = 0; i < lh->num_file_names; i++)
15807         {
15808           const char *dir = NULL;
15809           struct file_entry *fe;
15810
15811           fe = &lh->file_names[i];
15812           if (fe->dir_index)
15813             dir = lh->include_dirs[fe->dir_index - 1];
15814           dwarf2_start_subfile (fe->name, dir, comp_dir);
15815
15816           /* Skip the main file; we don't need it, and it must be
15817              allocated last, so that it will show up before the
15818              non-primary symtabs in the objfile's symtab list.  */
15819           if (current_subfile == first_subfile)
15820             continue;
15821
15822           if (current_subfile->symtab == NULL)
15823             current_subfile->symtab = allocate_symtab (current_subfile->name,
15824                                                        objfile);
15825           fe->symtab = current_subfile->symtab;
15826         }
15827     }
15828 }
15829
15830 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15831    DIRNAME the name of the source directory which contains FILENAME
15832    or NULL if not known.  COMP_DIR is the compilation directory for the
15833    linetable's compilation unit or NULL if not known.
15834    This routine tries to keep line numbers from identical absolute and
15835    relative file names in a common subfile.
15836
15837    Using the `list' example from the GDB testsuite, which resides in
15838    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15839    of /srcdir/list0.c yields the following debugging information for list0.c:
15840
15841    DW_AT_name:          /srcdir/list0.c
15842    DW_AT_comp_dir:              /compdir
15843    files.files[0].name: list0.h
15844    files.files[0].dir:  /srcdir
15845    files.files[1].name: list0.c
15846    files.files[1].dir:  /srcdir
15847
15848    The line number information for list0.c has to end up in a single
15849    subfile, so that `break /srcdir/list0.c:1' works as expected.
15850    start_subfile will ensure that this happens provided that we pass the
15851    concatenation of files.files[1].dir and files.files[1].name as the
15852    subfile's name.  */
15853
15854 static void
15855 dwarf2_start_subfile (const char *filename, const char *dirname,
15856                       const char *comp_dir)
15857 {
15858   char *copy = NULL;
15859
15860   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15861      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15862      second argument to start_subfile.  To be consistent, we do the
15863      same here.  In order not to lose the line information directory,
15864      we concatenate it to the filename when it makes sense.
15865      Note that the Dwarf3 standard says (speaking of filenames in line
15866      information): ``The directory index is ignored for file names
15867      that represent full path names''.  Thus ignoring dirname in the
15868      `else' branch below isn't an issue.  */
15869
15870   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15871     {
15872       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15873       filename = copy;
15874     }
15875
15876   start_subfile (filename, comp_dir);
15877
15878   if (copy != NULL)
15879     xfree (copy);
15880 }
15881
15882 /* Start a symtab for DWARF.
15883    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15884
15885 static void
15886 dwarf2_start_symtab (struct dwarf2_cu *cu,
15887                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15888 {
15889   start_symtab (name, comp_dir, low_pc);
15890   record_debugformat ("DWARF 2");
15891   record_producer (cu->producer);
15892
15893   /* We assume that we're processing GCC output.  */
15894   processing_gcc_compilation = 2;
15895
15896   cu->processing_has_namespace_info = 0;
15897 }
15898
15899 static void
15900 var_decode_location (struct attribute *attr, struct symbol *sym,
15901                      struct dwarf2_cu *cu)
15902 {
15903   struct objfile *objfile = cu->objfile;
15904   struct comp_unit_head *cu_header = &cu->header;
15905
15906   /* NOTE drow/2003-01-30: There used to be a comment and some special
15907      code here to turn a symbol with DW_AT_external and a
15908      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15909      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15910      with some versions of binutils) where shared libraries could have
15911      relocations against symbols in their debug information - the
15912      minimal symbol would have the right address, but the debug info
15913      would not.  It's no longer necessary, because we will explicitly
15914      apply relocations when we read in the debug information now.  */
15915
15916   /* A DW_AT_location attribute with no contents indicates that a
15917      variable has been optimized away.  */
15918   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15919     {
15920       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15921       return;
15922     }
15923
15924   /* Handle one degenerate form of location expression specially, to
15925      preserve GDB's previous behavior when section offsets are
15926      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15927      then mark this symbol as LOC_STATIC.  */
15928
15929   if (attr_form_is_block (attr)
15930       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15931            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15932           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15933               && (DW_BLOCK (attr)->size
15934                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15935     {
15936       unsigned int dummy;
15937
15938       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15939         SYMBOL_VALUE_ADDRESS (sym) =
15940           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15941       else
15942         SYMBOL_VALUE_ADDRESS (sym) =
15943           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15944       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
15945       fixup_symbol_section (sym, objfile);
15946       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15947                                               SYMBOL_SECTION (sym));
15948       return;
15949     }
15950
15951   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15952      expression evaluator, and use LOC_COMPUTED only when necessary
15953      (i.e. when the value of a register or memory location is
15954      referenced, or a thread-local block, etc.).  Then again, it might
15955      not be worthwhile.  I'm assuming that it isn't unless performance
15956      or memory numbers show me otherwise.  */
15957
15958   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
15959
15960   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
15961     cu->has_loclist = 1;
15962 }
15963
15964 /* Given a pointer to a DWARF information entry, figure out if we need
15965    to make a symbol table entry for it, and if so, create a new entry
15966    and return a pointer to it.
15967    If TYPE is NULL, determine symbol type from the die, otherwise
15968    used the passed type.
15969    If SPACE is not NULL, use it to hold the new symbol.  If it is
15970    NULL, allocate a new symbol on the objfile's obstack.  */
15971
15972 static struct symbol *
15973 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15974                  struct symbol *space)
15975 {
15976   struct objfile *objfile = cu->objfile;
15977   struct symbol *sym = NULL;
15978   const char *name;
15979   struct attribute *attr = NULL;
15980   struct attribute *attr2 = NULL;
15981   CORE_ADDR baseaddr;
15982   struct pending **list_to_add = NULL;
15983
15984   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15985
15986   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15987
15988   name = dwarf2_name (die, cu);
15989   if (name)
15990     {
15991       const char *linkagename;
15992       int suppress_add = 0;
15993
15994       if (space)
15995         sym = space;
15996       else
15997         sym = allocate_symbol (objfile);
15998       OBJSTAT (objfile, n_syms++);
15999
16000       /* Cache this symbol's name and the name's demangled form (if any).  */
16001       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16002       linkagename = dwarf2_physname (name, die, cu);
16003       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16004
16005       /* Fortran does not have mangling standard and the mangling does differ
16006          between gfortran, iFort etc.  */
16007       if (cu->language == language_fortran
16008           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16009         symbol_set_demangled_name (&(sym->ginfo),
16010                                    dwarf2_full_name (name, die, cu),
16011                                    NULL);
16012
16013       /* Default assumptions.
16014          Use the passed type or decode it from the die.  */
16015       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16016       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16017       if (type != NULL)
16018         SYMBOL_TYPE (sym) = type;
16019       else
16020         SYMBOL_TYPE (sym) = die_type (die, cu);
16021       attr = dwarf2_attr (die,
16022                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16023                           cu);
16024       if (attr)
16025         {
16026           SYMBOL_LINE (sym) = DW_UNSND (attr);
16027         }
16028
16029       attr = dwarf2_attr (die,
16030                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16031                           cu);
16032       if (attr)
16033         {
16034           int file_index = DW_UNSND (attr);
16035
16036           if (cu->line_header == NULL
16037               || file_index > cu->line_header->num_file_names)
16038             complaint (&symfile_complaints,
16039                        _("file index out of range"));
16040           else if (file_index > 0)
16041             {
16042               struct file_entry *fe;
16043
16044               fe = &cu->line_header->file_names[file_index - 1];
16045               SYMBOL_SYMTAB (sym) = fe->symtab;
16046             }
16047         }
16048
16049       switch (die->tag)
16050         {
16051         case DW_TAG_label:
16052           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16053           if (attr)
16054             {
16055               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16056             }
16057           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16058           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16059           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16060           add_symbol_to_list (sym, cu->list_in_scope);
16061           break;
16062         case DW_TAG_subprogram:
16063           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16064              finish_block.  */
16065           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16066           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16067           if ((attr2 && (DW_UNSND (attr2) != 0))
16068               || cu->language == language_ada)
16069             {
16070               /* Subprograms marked external are stored as a global symbol.
16071                  Ada subprograms, whether marked external or not, are always
16072                  stored as a global symbol, because we want to be able to
16073                  access them globally.  For instance, we want to be able
16074                  to break on a nested subprogram without having to
16075                  specify the context.  */
16076               list_to_add = &global_symbols;
16077             }
16078           else
16079             {
16080               list_to_add = cu->list_in_scope;
16081             }
16082           break;
16083         case DW_TAG_inlined_subroutine:
16084           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16085              finish_block.  */
16086           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16087           SYMBOL_INLINED (sym) = 1;
16088           list_to_add = cu->list_in_scope;
16089           break;
16090         case DW_TAG_template_value_param:
16091           suppress_add = 1;
16092           /* Fall through.  */
16093         case DW_TAG_constant:
16094         case DW_TAG_variable:
16095         case DW_TAG_member:
16096           /* Compilation with minimal debug info may result in
16097              variables with missing type entries.  Change the
16098              misleading `void' type to something sensible.  */
16099           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16100             SYMBOL_TYPE (sym)
16101               = objfile_type (objfile)->nodebug_data_symbol;
16102
16103           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16104           /* In the case of DW_TAG_member, we should only be called for
16105              static const members.  */
16106           if (die->tag == DW_TAG_member)
16107             {
16108               /* dwarf2_add_field uses die_is_declaration,
16109                  so we do the same.  */
16110               gdb_assert (die_is_declaration (die, cu));
16111               gdb_assert (attr);
16112             }
16113           if (attr)
16114             {
16115               dwarf2_const_value (attr, sym, cu);
16116               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16117               if (!suppress_add)
16118                 {
16119                   if (attr2 && (DW_UNSND (attr2) != 0))
16120                     list_to_add = &global_symbols;
16121                   else
16122                     list_to_add = cu->list_in_scope;
16123                 }
16124               break;
16125             }
16126           attr = dwarf2_attr (die, DW_AT_location, cu);
16127           if (attr)
16128             {
16129               var_decode_location (attr, sym, cu);
16130               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16131
16132               /* Fortran explicitly imports any global symbols to the local
16133                  scope by DW_TAG_common_block.  */
16134               if (cu->language == language_fortran && die->parent
16135                   && die->parent->tag == DW_TAG_common_block)
16136                 attr2 = NULL;
16137
16138               if (SYMBOL_CLASS (sym) == LOC_STATIC
16139                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16140                   && !dwarf2_per_objfile->has_section_at_zero)
16141                 {
16142                   /* When a static variable is eliminated by the linker,
16143                      the corresponding debug information is not stripped
16144                      out, but the variable address is set to null;
16145                      do not add such variables into symbol table.  */
16146                 }
16147               else if (attr2 && (DW_UNSND (attr2) != 0))
16148                 {
16149                   /* Workaround gfortran PR debug/40040 - it uses
16150                      DW_AT_location for variables in -fPIC libraries which may
16151                      get overriden by other libraries/executable and get
16152                      a different address.  Resolve it by the minimal symbol
16153                      which may come from inferior's executable using copy
16154                      relocation.  Make this workaround only for gfortran as for
16155                      other compilers GDB cannot guess the minimal symbol
16156                      Fortran mangling kind.  */
16157                   if (cu->language == language_fortran && die->parent
16158                       && die->parent->tag == DW_TAG_module
16159                       && cu->producer
16160                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16161                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16162
16163                   /* A variable with DW_AT_external is never static,
16164                      but it may be block-scoped.  */
16165                   list_to_add = (cu->list_in_scope == &file_symbols
16166                                  ? &global_symbols : cu->list_in_scope);
16167                 }
16168               else
16169                 list_to_add = cu->list_in_scope;
16170             }
16171           else
16172             {
16173               /* We do not know the address of this symbol.
16174                  If it is an external symbol and we have type information
16175                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16176                  The address of the variable will then be determined from
16177                  the minimal symbol table whenever the variable is
16178                  referenced.  */
16179               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16180
16181               /* Fortran explicitly imports any global symbols to the local
16182                  scope by DW_TAG_common_block.  */
16183               if (cu->language == language_fortran && die->parent
16184                   && die->parent->tag == DW_TAG_common_block)
16185                 {
16186                   /* SYMBOL_CLASS doesn't matter here because
16187                      read_common_block is going to reset it.  */
16188                   if (!suppress_add)
16189                     list_to_add = cu->list_in_scope;
16190                 }
16191               else if (attr2 && (DW_UNSND (attr2) != 0)
16192                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16193                 {
16194                   /* A variable with DW_AT_external is never static, but it
16195                      may be block-scoped.  */
16196                   list_to_add = (cu->list_in_scope == &file_symbols
16197                                  ? &global_symbols : cu->list_in_scope);
16198
16199                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16200                 }
16201               else if (!die_is_declaration (die, cu))
16202                 {
16203                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16204                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16205                   if (!suppress_add)
16206                     list_to_add = cu->list_in_scope;
16207                 }
16208             }
16209           break;
16210         case DW_TAG_formal_parameter:
16211           /* If we are inside a function, mark this as an argument.  If
16212              not, we might be looking at an argument to an inlined function
16213              when we do not have enough information to show inlined frames;
16214              pretend it's a local variable in that case so that the user can
16215              still see it.  */
16216           if (context_stack_depth > 0
16217               && context_stack[context_stack_depth - 1].name != NULL)
16218             SYMBOL_IS_ARGUMENT (sym) = 1;
16219           attr = dwarf2_attr (die, DW_AT_location, cu);
16220           if (attr)
16221             {
16222               var_decode_location (attr, sym, cu);
16223             }
16224           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16225           if (attr)
16226             {
16227               dwarf2_const_value (attr, sym, cu);
16228             }
16229
16230           list_to_add = cu->list_in_scope;
16231           break;
16232         case DW_TAG_unspecified_parameters:
16233           /* From varargs functions; gdb doesn't seem to have any
16234              interest in this information, so just ignore it for now.
16235              (FIXME?) */
16236           break;
16237         case DW_TAG_template_type_param:
16238           suppress_add = 1;
16239           /* Fall through.  */
16240         case DW_TAG_class_type:
16241         case DW_TAG_interface_type:
16242         case DW_TAG_structure_type:
16243         case DW_TAG_union_type:
16244         case DW_TAG_set_type:
16245         case DW_TAG_enumeration_type:
16246           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16247           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16248
16249           {
16250             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16251                really ever be static objects: otherwise, if you try
16252                to, say, break of a class's method and you're in a file
16253                which doesn't mention that class, it won't work unless
16254                the check for all static symbols in lookup_symbol_aux
16255                saves you.  See the OtherFileClass tests in
16256                gdb.c++/namespace.exp.  */
16257
16258             if (!suppress_add)
16259               {
16260                 list_to_add = (cu->list_in_scope == &file_symbols
16261                                && (cu->language == language_cplus
16262                                    || cu->language == language_java)
16263                                ? &global_symbols : cu->list_in_scope);
16264
16265                 /* The semantics of C++ state that "struct foo {
16266                    ... }" also defines a typedef for "foo".  A Java
16267                    class declaration also defines a typedef for the
16268                    class.  */
16269                 if (cu->language == language_cplus
16270                     || cu->language == language_java
16271                     || cu->language == language_ada)
16272                   {
16273                     /* The symbol's name is already allocated along
16274                        with this objfile, so we don't need to
16275                        duplicate it for the type.  */
16276                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16277                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16278                   }
16279               }
16280           }
16281           break;
16282         case DW_TAG_typedef:
16283           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16284           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16285           list_to_add = cu->list_in_scope;
16286           break;
16287         case DW_TAG_base_type:
16288         case DW_TAG_subrange_type:
16289           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16290           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16291           list_to_add = cu->list_in_scope;
16292           break;
16293         case DW_TAG_enumerator:
16294           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16295           if (attr)
16296             {
16297               dwarf2_const_value (attr, sym, cu);
16298             }
16299           {
16300             /* NOTE: carlton/2003-11-10: See comment above in the
16301                DW_TAG_class_type, etc. block.  */
16302
16303             list_to_add = (cu->list_in_scope == &file_symbols
16304                            && (cu->language == language_cplus
16305                                || cu->language == language_java)
16306                            ? &global_symbols : cu->list_in_scope);
16307           }
16308           break;
16309         case DW_TAG_namespace:
16310           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16311           list_to_add = &global_symbols;
16312           break;
16313         case DW_TAG_common_block:
16314           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16315           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16316           add_symbol_to_list (sym, cu->list_in_scope);
16317           break;
16318         default:
16319           /* Not a tag we recognize.  Hopefully we aren't processing
16320              trash data, but since we must specifically ignore things
16321              we don't recognize, there is nothing else we should do at
16322              this point.  */
16323           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16324                      dwarf_tag_name (die->tag));
16325           break;
16326         }
16327
16328       if (suppress_add)
16329         {
16330           sym->hash_next = objfile->template_symbols;
16331           objfile->template_symbols = sym;
16332           list_to_add = NULL;
16333         }
16334
16335       if (list_to_add != NULL)
16336         add_symbol_to_list (sym, list_to_add);
16337
16338       /* For the benefit of old versions of GCC, check for anonymous
16339          namespaces based on the demangled name.  */
16340       if (!cu->processing_has_namespace_info
16341           && cu->language == language_cplus)
16342         cp_scan_for_anonymous_namespaces (sym, objfile);
16343     }
16344   return (sym);
16345 }
16346
16347 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16348
16349 static struct symbol *
16350 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16351 {
16352   return new_symbol_full (die, type, cu, NULL);
16353 }
16354
16355 /* Given an attr with a DW_FORM_dataN value in host byte order,
16356    zero-extend it as appropriate for the symbol's type.  The DWARF
16357    standard (v4) is not entirely clear about the meaning of using
16358    DW_FORM_dataN for a constant with a signed type, where the type is
16359    wider than the data.  The conclusion of a discussion on the DWARF
16360    list was that this is unspecified.  We choose to always zero-extend
16361    because that is the interpretation long in use by GCC.  */
16362
16363 static gdb_byte *
16364 dwarf2_const_value_data (struct attribute *attr, struct obstack *obstack,
16365                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16366 {
16367   struct objfile *objfile = cu->objfile;
16368   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16369                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16370   LONGEST l = DW_UNSND (attr);
16371
16372   if (bits < sizeof (*value) * 8)
16373     {
16374       l &= ((LONGEST) 1 << bits) - 1;
16375       *value = l;
16376     }
16377   else if (bits == sizeof (*value) * 8)
16378     *value = l;
16379   else
16380     {
16381       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16382       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16383       return bytes;
16384     }
16385
16386   return NULL;
16387 }
16388
16389 /* Read a constant value from an attribute.  Either set *VALUE, or if
16390    the value does not fit in *VALUE, set *BYTES - either already
16391    allocated on the objfile obstack, or newly allocated on OBSTACK,
16392    or, set *BATON, if we translated the constant to a location
16393    expression.  */
16394
16395 static void
16396 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16397                          const char *name, struct obstack *obstack,
16398                          struct dwarf2_cu *cu,
16399                          LONGEST *value, const gdb_byte **bytes,
16400                          struct dwarf2_locexpr_baton **baton)
16401 {
16402   struct objfile *objfile = cu->objfile;
16403   struct comp_unit_head *cu_header = &cu->header;
16404   struct dwarf_block *blk;
16405   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16406                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16407
16408   *value = 0;
16409   *bytes = NULL;
16410   *baton = NULL;
16411
16412   switch (attr->form)
16413     {
16414     case DW_FORM_addr:
16415     case DW_FORM_GNU_addr_index:
16416       {
16417         gdb_byte *data;
16418
16419         if (TYPE_LENGTH (type) != cu_header->addr_size)
16420           dwarf2_const_value_length_mismatch_complaint (name,
16421                                                         cu_header->addr_size,
16422                                                         TYPE_LENGTH (type));
16423         /* Symbols of this form are reasonably rare, so we just
16424            piggyback on the existing location code rather than writing
16425            a new implementation of symbol_computed_ops.  */
16426         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16427         (*baton)->per_cu = cu->per_cu;
16428         gdb_assert ((*baton)->per_cu);
16429
16430         (*baton)->size = 2 + cu_header->addr_size;
16431         data = obstack_alloc (obstack, (*baton)->size);
16432         (*baton)->data = data;
16433
16434         data[0] = DW_OP_addr;
16435         store_unsigned_integer (&data[1], cu_header->addr_size,
16436                                 byte_order, DW_ADDR (attr));
16437         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16438       }
16439       break;
16440     case DW_FORM_string:
16441     case DW_FORM_strp:
16442     case DW_FORM_GNU_str_index:
16443     case DW_FORM_GNU_strp_alt:
16444       /* DW_STRING is already allocated on the objfile obstack, point
16445          directly to it.  */
16446       *bytes = (const gdb_byte *) DW_STRING (attr);
16447       break;
16448     case DW_FORM_block1:
16449     case DW_FORM_block2:
16450     case DW_FORM_block4:
16451     case DW_FORM_block:
16452     case DW_FORM_exprloc:
16453       blk = DW_BLOCK (attr);
16454       if (TYPE_LENGTH (type) != blk->size)
16455         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16456                                                       TYPE_LENGTH (type));
16457       *bytes = blk->data;
16458       break;
16459
16460       /* The DW_AT_const_value attributes are supposed to carry the
16461          symbol's value "represented as it would be on the target
16462          architecture."  By the time we get here, it's already been
16463          converted to host endianness, so we just need to sign- or
16464          zero-extend it as appropriate.  */
16465     case DW_FORM_data1:
16466       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16467       break;
16468     case DW_FORM_data2:
16469       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16470       break;
16471     case DW_FORM_data4:
16472       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16473       break;
16474     case DW_FORM_data8:
16475       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16476       break;
16477
16478     case DW_FORM_sdata:
16479       *value = DW_SND (attr);
16480       break;
16481
16482     case DW_FORM_udata:
16483       *value = DW_UNSND (attr);
16484       break;
16485
16486     default:
16487       complaint (&symfile_complaints,
16488                  _("unsupported const value attribute form: '%s'"),
16489                  dwarf_form_name (attr->form));
16490       *value = 0;
16491       break;
16492     }
16493 }
16494
16495
16496 /* Copy constant value from an attribute to a symbol.  */
16497
16498 static void
16499 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16500                     struct dwarf2_cu *cu)
16501 {
16502   struct objfile *objfile = cu->objfile;
16503   struct comp_unit_head *cu_header = &cu->header;
16504   LONGEST value;
16505   const gdb_byte *bytes;
16506   struct dwarf2_locexpr_baton *baton;
16507
16508   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16509                            SYMBOL_PRINT_NAME (sym),
16510                            &objfile->objfile_obstack, cu,
16511                            &value, &bytes, &baton);
16512
16513   if (baton != NULL)
16514     {
16515       SYMBOL_LOCATION_BATON (sym) = baton;
16516       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16517     }
16518   else if (bytes != NULL)
16519      {
16520       SYMBOL_VALUE_BYTES (sym) = bytes;
16521       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16522     }
16523   else
16524     {
16525       SYMBOL_VALUE (sym) = value;
16526       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16527     }
16528 }
16529
16530 /* Return the type of the die in question using its DW_AT_type attribute.  */
16531
16532 static struct type *
16533 die_type (struct die_info *die, struct dwarf2_cu *cu)
16534 {
16535   struct attribute *type_attr;
16536
16537   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16538   if (!type_attr)
16539     {
16540       /* A missing DW_AT_type represents a void type.  */
16541       return objfile_type (cu->objfile)->builtin_void;
16542     }
16543
16544   return lookup_die_type (die, type_attr, cu);
16545 }
16546
16547 /* True iff CU's producer generates GNAT Ada auxiliary information
16548    that allows to find parallel types through that information instead
16549    of having to do expensive parallel lookups by type name.  */
16550
16551 static int
16552 need_gnat_info (struct dwarf2_cu *cu)
16553 {
16554   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16555      of GNAT produces this auxiliary information, without any indication
16556      that it is produced.  Part of enhancing the FSF version of GNAT
16557      to produce that information will be to put in place an indicator
16558      that we can use in order to determine whether the descriptive type
16559      info is available or not.  One suggestion that has been made is
16560      to use a new attribute, attached to the CU die.  For now, assume
16561      that the descriptive type info is not available.  */
16562   return 0;
16563 }
16564
16565 /* Return the auxiliary type of the die in question using its
16566    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16567    attribute is not present.  */
16568
16569 static struct type *
16570 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16571 {
16572   struct attribute *type_attr;
16573
16574   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16575   if (!type_attr)
16576     return NULL;
16577
16578   return lookup_die_type (die, type_attr, cu);
16579 }
16580
16581 /* If DIE has a descriptive_type attribute, then set the TYPE's
16582    descriptive type accordingly.  */
16583
16584 static void
16585 set_descriptive_type (struct type *type, struct die_info *die,
16586                       struct dwarf2_cu *cu)
16587 {
16588   struct type *descriptive_type = die_descriptive_type (die, cu);
16589
16590   if (descriptive_type)
16591     {
16592       ALLOCATE_GNAT_AUX_TYPE (type);
16593       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16594     }
16595 }
16596
16597 /* Return the containing type of the die in question using its
16598    DW_AT_containing_type attribute.  */
16599
16600 static struct type *
16601 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16602 {
16603   struct attribute *type_attr;
16604
16605   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16606   if (!type_attr)
16607     error (_("Dwarf Error: Problem turning containing type into gdb type "
16608              "[in module %s]"), cu->objfile->name);
16609
16610   return lookup_die_type (die, type_attr, cu);
16611 }
16612
16613 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
16614
16615 static struct type *
16616 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
16617 {
16618   struct objfile *objfile = dwarf2_per_objfile->objfile;
16619   char *message, *saved;
16620
16621   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16622                         objfile->name,
16623                         cu->header.offset.sect_off,
16624                         die->offset.sect_off);
16625   saved = obstack_copy0 (&objfile->objfile_obstack,
16626                          message, strlen (message));
16627   xfree (message);
16628
16629   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16630 }
16631
16632 /* Look up the type of DIE in CU using its type attribute ATTR.
16633    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
16634    DW_AT_containing_type.
16635    If there is no type substitute an error marker.  */
16636
16637 static struct type *
16638 lookup_die_type (struct die_info *die, struct attribute *attr,
16639                  struct dwarf2_cu *cu)
16640 {
16641   struct objfile *objfile = cu->objfile;
16642   struct type *this_type;
16643
16644   gdb_assert (attr->name == DW_AT_type
16645               || attr->name == DW_AT_GNAT_descriptive_type
16646               || attr->name == DW_AT_containing_type);
16647
16648   /* First see if we have it cached.  */
16649
16650   if (attr->form == DW_FORM_GNU_ref_alt)
16651     {
16652       struct dwarf2_per_cu_data *per_cu;
16653       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16654
16655       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16656       this_type = get_die_type_at_offset (offset, per_cu);
16657     }
16658   else if (is_ref_attr (attr))
16659     {
16660       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16661
16662       this_type = get_die_type_at_offset (offset, cu->per_cu);
16663     }
16664   else if (attr->form == DW_FORM_ref_sig8)
16665     {
16666       ULONGEST signature = DW_SIGNATURE (attr);
16667
16668       return get_signatured_type (die, signature, cu);
16669     }
16670   else
16671     {
16672       complaint (&symfile_complaints,
16673                  _("Dwarf Error: Bad type attribute %s in DIE"
16674                    " at 0x%x [in module %s]"),
16675                  dwarf_attr_name (attr->name), die->offset.sect_off,
16676                  objfile->name);
16677       return build_error_marker_type (cu, die);
16678     }
16679
16680   /* If not cached we need to read it in.  */
16681
16682   if (this_type == NULL)
16683     {
16684       struct die_info *type_die = NULL;
16685       struct dwarf2_cu *type_cu = cu;
16686
16687       if (is_ref_attr (attr))
16688         type_die = follow_die_ref (die, attr, &type_cu);
16689       if (type_die == NULL)
16690         return build_error_marker_type (cu, die);
16691       /* If we find the type now, it's probably because the type came
16692          from an inter-CU reference and the type's CU got expanded before
16693          ours.  */
16694       this_type = read_type_die (type_die, type_cu);
16695     }
16696
16697   /* If we still don't have a type use an error marker.  */
16698
16699   if (this_type == NULL)
16700     return build_error_marker_type (cu, die);
16701
16702   return this_type;
16703 }
16704
16705 /* Return the type in DIE, CU.
16706    Returns NULL for invalid types.
16707
16708    This first does a lookup in die_type_hash,
16709    and only reads the die in if necessary.
16710
16711    NOTE: This can be called when reading in partial or full symbols.  */
16712
16713 static struct type *
16714 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16715 {
16716   struct type *this_type;
16717
16718   this_type = get_die_type (die, cu);
16719   if (this_type)
16720     return this_type;
16721
16722   return read_type_die_1 (die, cu);
16723 }
16724
16725 /* Read the type in DIE, CU.
16726    Returns NULL for invalid types.  */
16727
16728 static struct type *
16729 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16730 {
16731   struct type *this_type = NULL;
16732
16733   switch (die->tag)
16734     {
16735     case DW_TAG_class_type:
16736     case DW_TAG_interface_type:
16737     case DW_TAG_structure_type:
16738     case DW_TAG_union_type:
16739       this_type = read_structure_type (die, cu);
16740       break;
16741     case DW_TAG_enumeration_type:
16742       this_type = read_enumeration_type (die, cu);
16743       break;
16744     case DW_TAG_subprogram:
16745     case DW_TAG_subroutine_type:
16746     case DW_TAG_inlined_subroutine:
16747       this_type = read_subroutine_type (die, cu);
16748       break;
16749     case DW_TAG_array_type:
16750       this_type = read_array_type (die, cu);
16751       break;
16752     case DW_TAG_set_type:
16753       this_type = read_set_type (die, cu);
16754       break;
16755     case DW_TAG_pointer_type:
16756       this_type = read_tag_pointer_type (die, cu);
16757       break;
16758     case DW_TAG_ptr_to_member_type:
16759       this_type = read_tag_ptr_to_member_type (die, cu);
16760       break;
16761     case DW_TAG_reference_type:
16762       this_type = read_tag_reference_type (die, cu);
16763       break;
16764     case DW_TAG_const_type:
16765       this_type = read_tag_const_type (die, cu);
16766       break;
16767     case DW_TAG_volatile_type:
16768       this_type = read_tag_volatile_type (die, cu);
16769       break;
16770     case DW_TAG_restrict_type:
16771       this_type = read_tag_restrict_type (die, cu);
16772       break;
16773     case DW_TAG_string_type:
16774       this_type = read_tag_string_type (die, cu);
16775       break;
16776     case DW_TAG_typedef:
16777       this_type = read_typedef (die, cu);
16778       break;
16779     case DW_TAG_subrange_type:
16780       this_type = read_subrange_type (die, cu);
16781       break;
16782     case DW_TAG_base_type:
16783       this_type = read_base_type (die, cu);
16784       break;
16785     case DW_TAG_unspecified_type:
16786       this_type = read_unspecified_type (die, cu);
16787       break;
16788     case DW_TAG_namespace:
16789       this_type = read_namespace_type (die, cu);
16790       break;
16791     case DW_TAG_module:
16792       this_type = read_module_type (die, cu);
16793       break;
16794     default:
16795       complaint (&symfile_complaints,
16796                  _("unexpected tag in read_type_die: '%s'"),
16797                  dwarf_tag_name (die->tag));
16798       break;
16799     }
16800
16801   return this_type;
16802 }
16803
16804 /* See if we can figure out if the class lives in a namespace.  We do
16805    this by looking for a member function; its demangled name will
16806    contain namespace info, if there is any.
16807    Return the computed name or NULL.
16808    Space for the result is allocated on the objfile's obstack.
16809    This is the full-die version of guess_partial_die_structure_name.
16810    In this case we know DIE has no useful parent.  */
16811
16812 static char *
16813 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16814 {
16815   struct die_info *spec_die;
16816   struct dwarf2_cu *spec_cu;
16817   struct die_info *child;
16818
16819   spec_cu = cu;
16820   spec_die = die_specification (die, &spec_cu);
16821   if (spec_die != NULL)
16822     {
16823       die = spec_die;
16824       cu = spec_cu;
16825     }
16826
16827   for (child = die->child;
16828        child != NULL;
16829        child = child->sibling)
16830     {
16831       if (child->tag == DW_TAG_subprogram)
16832         {
16833           struct attribute *attr;
16834
16835           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16836           if (attr == NULL)
16837             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16838           if (attr != NULL)
16839             {
16840               char *actual_name
16841                 = language_class_name_from_physname (cu->language_defn,
16842                                                      DW_STRING (attr));
16843               char *name = NULL;
16844
16845               if (actual_name != NULL)
16846                 {
16847                   const char *die_name = dwarf2_name (die, cu);
16848
16849                   if (die_name != NULL
16850                       && strcmp (die_name, actual_name) != 0)
16851                     {
16852                       /* Strip off the class name from the full name.
16853                          We want the prefix.  */
16854                       int die_name_len = strlen (die_name);
16855                       int actual_name_len = strlen (actual_name);
16856
16857                       /* Test for '::' as a sanity check.  */
16858                       if (actual_name_len > die_name_len + 2
16859                           && actual_name[actual_name_len
16860                                          - die_name_len - 1] == ':')
16861                         name =
16862                           obstack_copy0 (&cu->objfile->objfile_obstack,
16863                                          actual_name,
16864                                          actual_name_len - die_name_len - 2);
16865                     }
16866                 }
16867               xfree (actual_name);
16868               return name;
16869             }
16870         }
16871     }
16872
16873   return NULL;
16874 }
16875
16876 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16877    prefix part in such case.  See
16878    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16879
16880 static char *
16881 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16882 {
16883   struct attribute *attr;
16884   char *base;
16885
16886   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16887       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16888     return NULL;
16889
16890   attr = dwarf2_attr (die, DW_AT_name, cu);
16891   if (attr != NULL && DW_STRING (attr) != NULL)
16892     return NULL;
16893
16894   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16895   if (attr == NULL)
16896     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16897   if (attr == NULL || DW_STRING (attr) == NULL)
16898     return NULL;
16899
16900   /* dwarf2_name had to be already called.  */
16901   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16902
16903   /* Strip the base name, keep any leading namespaces/classes.  */
16904   base = strrchr (DW_STRING (attr), ':');
16905   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16906     return "";
16907
16908   return obstack_copy0 (&cu->objfile->objfile_obstack,
16909                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16910 }
16911
16912 /* Return the name of the namespace/class that DIE is defined within,
16913    or "" if we can't tell.  The caller should not xfree the result.
16914
16915    For example, if we're within the method foo() in the following
16916    code:
16917
16918    namespace N {
16919      class C {
16920        void foo () {
16921        }
16922      };
16923    }
16924
16925    then determine_prefix on foo's die will return "N::C".  */
16926
16927 static const char *
16928 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16929 {
16930   struct die_info *parent, *spec_die;
16931   struct dwarf2_cu *spec_cu;
16932   struct type *parent_type;
16933   char *retval;
16934
16935   if (cu->language != language_cplus && cu->language != language_java
16936       && cu->language != language_fortran)
16937     return "";
16938
16939   retval = anonymous_struct_prefix (die, cu);
16940   if (retval)
16941     return retval;
16942
16943   /* We have to be careful in the presence of DW_AT_specification.
16944      For example, with GCC 3.4, given the code
16945
16946      namespace N {
16947        void foo() {
16948          // Definition of N::foo.
16949        }
16950      }
16951
16952      then we'll have a tree of DIEs like this:
16953
16954      1: DW_TAG_compile_unit
16955        2: DW_TAG_namespace        // N
16956          3: DW_TAG_subprogram     // declaration of N::foo
16957        4: DW_TAG_subprogram       // definition of N::foo
16958             DW_AT_specification   // refers to die #3
16959
16960      Thus, when processing die #4, we have to pretend that we're in
16961      the context of its DW_AT_specification, namely the contex of die
16962      #3.  */
16963   spec_cu = cu;
16964   spec_die = die_specification (die, &spec_cu);
16965   if (spec_die == NULL)
16966     parent = die->parent;
16967   else
16968     {
16969       parent = spec_die->parent;
16970       cu = spec_cu;
16971     }
16972
16973   if (parent == NULL)
16974     return "";
16975   else if (parent->building_fullname)
16976     {
16977       const char *name;
16978       const char *parent_name;
16979
16980       /* It has been seen on RealView 2.2 built binaries,
16981          DW_TAG_template_type_param types actually _defined_ as
16982          children of the parent class:
16983
16984          enum E {};
16985          template class <class Enum> Class{};
16986          Class<enum E> class_e;
16987
16988          1: DW_TAG_class_type (Class)
16989            2: DW_TAG_enumeration_type (E)
16990              3: DW_TAG_enumerator (enum1:0)
16991              3: DW_TAG_enumerator (enum2:1)
16992              ...
16993            2: DW_TAG_template_type_param
16994               DW_AT_type  DW_FORM_ref_udata (E)
16995
16996          Besides being broken debug info, it can put GDB into an
16997          infinite loop.  Consider:
16998
16999          When we're building the full name for Class<E>, we'll start
17000          at Class, and go look over its template type parameters,
17001          finding E.  We'll then try to build the full name of E, and
17002          reach here.  We're now trying to build the full name of E,
17003          and look over the parent DIE for containing scope.  In the
17004          broken case, if we followed the parent DIE of E, we'd again
17005          find Class, and once again go look at its template type
17006          arguments, etc., etc.  Simply don't consider such parent die
17007          as source-level parent of this die (it can't be, the language
17008          doesn't allow it), and break the loop here.  */
17009       name = dwarf2_name (die, cu);
17010       parent_name = dwarf2_name (parent, cu);
17011       complaint (&symfile_complaints,
17012                  _("template param type '%s' defined within parent '%s'"),
17013                  name ? name : "<unknown>",
17014                  parent_name ? parent_name : "<unknown>");
17015       return "";
17016     }
17017   else
17018     switch (parent->tag)
17019       {
17020       case DW_TAG_namespace:
17021         parent_type = read_type_die (parent, cu);
17022         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17023            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17024            Work around this problem here.  */
17025         if (cu->language == language_cplus
17026             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17027           return "";
17028         /* We give a name to even anonymous namespaces.  */
17029         return TYPE_TAG_NAME (parent_type);
17030       case DW_TAG_class_type:
17031       case DW_TAG_interface_type:
17032       case DW_TAG_structure_type:
17033       case DW_TAG_union_type:
17034       case DW_TAG_module:
17035         parent_type = read_type_die (parent, cu);
17036         if (TYPE_TAG_NAME (parent_type) != NULL)
17037           return TYPE_TAG_NAME (parent_type);
17038         else
17039           /* An anonymous structure is only allowed non-static data
17040              members; no typedefs, no member functions, et cetera.
17041              So it does not need a prefix.  */
17042           return "";
17043       case DW_TAG_compile_unit:
17044       case DW_TAG_partial_unit:
17045         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17046         if (cu->language == language_cplus
17047             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17048             && die->child != NULL
17049             && (die->tag == DW_TAG_class_type
17050                 || die->tag == DW_TAG_structure_type
17051                 || die->tag == DW_TAG_union_type))
17052           {
17053             char *name = guess_full_die_structure_name (die, cu);
17054             if (name != NULL)
17055               return name;
17056           }
17057         return "";
17058       default:
17059         return determine_prefix (parent, cu);
17060       }
17061 }
17062
17063 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17064    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17065    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17066    an obconcat, otherwise allocate storage for the result.  The CU argument is
17067    used to determine the language and hence, the appropriate separator.  */
17068
17069 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17070
17071 static char *
17072 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17073                  int physname, struct dwarf2_cu *cu)
17074 {
17075   const char *lead = "";
17076   const char *sep;
17077
17078   if (suffix == NULL || suffix[0] == '\0'
17079       || prefix == NULL || prefix[0] == '\0')
17080     sep = "";
17081   else if (cu->language == language_java)
17082     sep = ".";
17083   else if (cu->language == language_fortran && physname)
17084     {
17085       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17086          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17087
17088       lead = "__";
17089       sep = "_MOD_";
17090     }
17091   else
17092     sep = "::";
17093
17094   if (prefix == NULL)
17095     prefix = "";
17096   if (suffix == NULL)
17097     suffix = "";
17098
17099   if (obs == NULL)
17100     {
17101       char *retval
17102         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17103
17104       strcpy (retval, lead);
17105       strcat (retval, prefix);
17106       strcat (retval, sep);
17107       strcat (retval, suffix);
17108       return retval;
17109     }
17110   else
17111     {
17112       /* We have an obstack.  */
17113       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17114     }
17115 }
17116
17117 /* Return sibling of die, NULL if no sibling.  */
17118
17119 static struct die_info *
17120 sibling_die (struct die_info *die)
17121 {
17122   return die->sibling;
17123 }
17124
17125 /* Get name of a die, return NULL if not found.  */
17126
17127 static const char *
17128 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17129                           struct obstack *obstack)
17130 {
17131   if (name && cu->language == language_cplus)
17132     {
17133       char *canon_name = cp_canonicalize_string (name);
17134
17135       if (canon_name != NULL)
17136         {
17137           if (strcmp (canon_name, name) != 0)
17138             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17139           xfree (canon_name);
17140         }
17141     }
17142
17143   return name;
17144 }
17145
17146 /* Get name of a die, return NULL if not found.  */
17147
17148 static const char *
17149 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17150 {
17151   struct attribute *attr;
17152
17153   attr = dwarf2_attr (die, DW_AT_name, cu);
17154   if ((!attr || !DW_STRING (attr))
17155       && die->tag != DW_TAG_class_type
17156       && die->tag != DW_TAG_interface_type
17157       && die->tag != DW_TAG_structure_type
17158       && die->tag != DW_TAG_union_type)
17159     return NULL;
17160
17161   switch (die->tag)
17162     {
17163     case DW_TAG_compile_unit:
17164     case DW_TAG_partial_unit:
17165       /* Compilation units have a DW_AT_name that is a filename, not
17166          a source language identifier.  */
17167     case DW_TAG_enumeration_type:
17168     case DW_TAG_enumerator:
17169       /* These tags always have simple identifiers already; no need
17170          to canonicalize them.  */
17171       return DW_STRING (attr);
17172
17173     case DW_TAG_subprogram:
17174       /* Java constructors will all be named "<init>", so return
17175          the class name when we see this special case.  */
17176       if (cu->language == language_java
17177           && DW_STRING (attr) != NULL
17178           && strcmp (DW_STRING (attr), "<init>") == 0)
17179         {
17180           struct dwarf2_cu *spec_cu = cu;
17181           struct die_info *spec_die;
17182
17183           /* GCJ will output '<init>' for Java constructor names.
17184              For this special case, return the name of the parent class.  */
17185
17186           /* GCJ may output suprogram DIEs with AT_specification set.
17187              If so, use the name of the specified DIE.  */
17188           spec_die = die_specification (die, &spec_cu);
17189           if (spec_die != NULL)
17190             return dwarf2_name (spec_die, spec_cu);
17191
17192           do
17193             {
17194               die = die->parent;
17195               if (die->tag == DW_TAG_class_type)
17196                 return dwarf2_name (die, cu);
17197             }
17198           while (die->tag != DW_TAG_compile_unit
17199                  && die->tag != DW_TAG_partial_unit);
17200         }
17201       break;
17202
17203     case DW_TAG_class_type:
17204     case DW_TAG_interface_type:
17205     case DW_TAG_structure_type:
17206     case DW_TAG_union_type:
17207       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17208          structures or unions.  These were of the form "._%d" in GCC 4.1,
17209          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17210          and GCC 4.4.  We work around this problem by ignoring these.  */
17211       if (attr && DW_STRING (attr)
17212           && (strncmp (DW_STRING (attr), "._", 2) == 0
17213               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17214         return NULL;
17215
17216       /* GCC might emit a nameless typedef that has a linkage name.  See
17217          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17218       if (!attr || DW_STRING (attr) == NULL)
17219         {
17220           char *demangled = NULL;
17221
17222           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17223           if (attr == NULL)
17224             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17225
17226           if (attr == NULL || DW_STRING (attr) == NULL)
17227             return NULL;
17228
17229           /* Avoid demangling DW_STRING (attr) the second time on a second
17230              call for the same DIE.  */
17231           if (!DW_STRING_IS_CANONICAL (attr))
17232             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17233
17234           if (demangled)
17235             {
17236               char *base;
17237
17238               /* FIXME: we already did this for the partial symbol... */
17239               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17240                                                 demangled, strlen (demangled));
17241               DW_STRING_IS_CANONICAL (attr) = 1;
17242               xfree (demangled);
17243
17244               /* Strip any leading namespaces/classes, keep only the base name.
17245                  DW_AT_name for named DIEs does not contain the prefixes.  */
17246               base = strrchr (DW_STRING (attr), ':');
17247               if (base && base > DW_STRING (attr) && base[-1] == ':')
17248                 return &base[1];
17249               else
17250                 return DW_STRING (attr);
17251             }
17252         }
17253       break;
17254
17255     default:
17256       break;
17257     }
17258
17259   if (!DW_STRING_IS_CANONICAL (attr))
17260     {
17261       DW_STRING (attr)
17262         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17263                                     &cu->objfile->objfile_obstack);
17264       DW_STRING_IS_CANONICAL (attr) = 1;
17265     }
17266   return DW_STRING (attr);
17267 }
17268
17269 /* Return the die that this die in an extension of, or NULL if there
17270    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17271    containing the return value on output.  */
17272
17273 static struct die_info *
17274 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17275 {
17276   struct attribute *attr;
17277
17278   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17279   if (attr == NULL)
17280     return NULL;
17281
17282   return follow_die_ref (die, attr, ext_cu);
17283 }
17284
17285 /* Convert a DIE tag into its string name.  */
17286
17287 static const char *
17288 dwarf_tag_name (unsigned tag)
17289 {
17290   const char *name = get_DW_TAG_name (tag);
17291
17292   if (name == NULL)
17293     return "DW_TAG_<unknown>";
17294
17295   return name;
17296 }
17297
17298 /* Convert a DWARF attribute code into its string name.  */
17299
17300 static const char *
17301 dwarf_attr_name (unsigned attr)
17302 {
17303   const char *name;
17304
17305 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17306   if (attr == DW_AT_MIPS_fde)
17307     return "DW_AT_MIPS_fde";
17308 #else
17309   if (attr == DW_AT_HP_block_index)
17310     return "DW_AT_HP_block_index";
17311 #endif
17312
17313   name = get_DW_AT_name (attr);
17314
17315   if (name == NULL)
17316     return "DW_AT_<unknown>";
17317
17318   return name;
17319 }
17320
17321 /* Convert a DWARF value form code into its string name.  */
17322
17323 static const char *
17324 dwarf_form_name (unsigned form)
17325 {
17326   const char *name = get_DW_FORM_name (form);
17327
17328   if (name == NULL)
17329     return "DW_FORM_<unknown>";
17330
17331   return name;
17332 }
17333
17334 static char *
17335 dwarf_bool_name (unsigned mybool)
17336 {
17337   if (mybool)
17338     return "TRUE";
17339   else
17340     return "FALSE";
17341 }
17342
17343 /* Convert a DWARF type code into its string name.  */
17344
17345 static const char *
17346 dwarf_type_encoding_name (unsigned enc)
17347 {
17348   const char *name = get_DW_ATE_name (enc);
17349
17350   if (name == NULL)
17351     return "DW_ATE_<unknown>";
17352
17353   return name;
17354 }
17355
17356 static void
17357 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17358 {
17359   unsigned int i;
17360
17361   print_spaces (indent, f);
17362   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17363            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17364
17365   if (die->parent != NULL)
17366     {
17367       print_spaces (indent, f);
17368       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17369                           die->parent->offset.sect_off);
17370     }
17371
17372   print_spaces (indent, f);
17373   fprintf_unfiltered (f, "  has children: %s\n",
17374            dwarf_bool_name (die->child != NULL));
17375
17376   print_spaces (indent, f);
17377   fprintf_unfiltered (f, "  attributes:\n");
17378
17379   for (i = 0; i < die->num_attrs; ++i)
17380     {
17381       print_spaces (indent, f);
17382       fprintf_unfiltered (f, "    %s (%s) ",
17383                dwarf_attr_name (die->attrs[i].name),
17384                dwarf_form_name (die->attrs[i].form));
17385
17386       switch (die->attrs[i].form)
17387         {
17388         case DW_FORM_addr:
17389         case DW_FORM_GNU_addr_index:
17390           fprintf_unfiltered (f, "address: ");
17391           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17392           break;
17393         case DW_FORM_block2:
17394         case DW_FORM_block4:
17395         case DW_FORM_block:
17396         case DW_FORM_block1:
17397           fprintf_unfiltered (f, "block: size %s",
17398                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17399           break;
17400         case DW_FORM_exprloc:
17401           fprintf_unfiltered (f, "expression: size %s",
17402                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17403           break;
17404         case DW_FORM_ref_addr:
17405           fprintf_unfiltered (f, "ref address: ");
17406           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17407           break;
17408         case DW_FORM_GNU_ref_alt:
17409           fprintf_unfiltered (f, "alt ref address: ");
17410           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17411           break;
17412         case DW_FORM_ref1:
17413         case DW_FORM_ref2:
17414         case DW_FORM_ref4:
17415         case DW_FORM_ref8:
17416         case DW_FORM_ref_udata:
17417           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17418                               (long) (DW_UNSND (&die->attrs[i])));
17419           break;
17420         case DW_FORM_data1:
17421         case DW_FORM_data2:
17422         case DW_FORM_data4:
17423         case DW_FORM_data8:
17424         case DW_FORM_udata:
17425         case DW_FORM_sdata:
17426           fprintf_unfiltered (f, "constant: %s",
17427                               pulongest (DW_UNSND (&die->attrs[i])));
17428           break;
17429         case DW_FORM_sec_offset:
17430           fprintf_unfiltered (f, "section offset: %s",
17431                               pulongest (DW_UNSND (&die->attrs[i])));
17432           break;
17433         case DW_FORM_ref_sig8:
17434           fprintf_unfiltered (f, "signature: %s",
17435                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17436           break;
17437         case DW_FORM_string:
17438         case DW_FORM_strp:
17439         case DW_FORM_GNU_str_index:
17440         case DW_FORM_GNU_strp_alt:
17441           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17442                    DW_STRING (&die->attrs[i])
17443                    ? DW_STRING (&die->attrs[i]) : "",
17444                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17445           break;
17446         case DW_FORM_flag:
17447           if (DW_UNSND (&die->attrs[i]))
17448             fprintf_unfiltered (f, "flag: TRUE");
17449           else
17450             fprintf_unfiltered (f, "flag: FALSE");
17451           break;
17452         case DW_FORM_flag_present:
17453           fprintf_unfiltered (f, "flag: TRUE");
17454           break;
17455         case DW_FORM_indirect:
17456           /* The reader will have reduced the indirect form to
17457              the "base form" so this form should not occur.  */
17458           fprintf_unfiltered (f, 
17459                               "unexpected attribute form: DW_FORM_indirect");
17460           break;
17461         default:
17462           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17463                    die->attrs[i].form);
17464           break;
17465         }
17466       fprintf_unfiltered (f, "\n");
17467     }
17468 }
17469
17470 static void
17471 dump_die_for_error (struct die_info *die)
17472 {
17473   dump_die_shallow (gdb_stderr, 0, die);
17474 }
17475
17476 static void
17477 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17478 {
17479   int indent = level * 4;
17480
17481   gdb_assert (die != NULL);
17482
17483   if (level >= max_level)
17484     return;
17485
17486   dump_die_shallow (f, indent, die);
17487
17488   if (die->child != NULL)
17489     {
17490       print_spaces (indent, f);
17491       fprintf_unfiltered (f, "  Children:");
17492       if (level + 1 < max_level)
17493         {
17494           fprintf_unfiltered (f, "\n");
17495           dump_die_1 (f, level + 1, max_level, die->child);
17496         }
17497       else
17498         {
17499           fprintf_unfiltered (f,
17500                               " [not printed, max nesting level reached]\n");
17501         }
17502     }
17503
17504   if (die->sibling != NULL && level > 0)
17505     {
17506       dump_die_1 (f, level, max_level, die->sibling);
17507     }
17508 }
17509
17510 /* This is called from the pdie macro in gdbinit.in.
17511    It's not static so gcc will keep a copy callable from gdb.  */
17512
17513 void
17514 dump_die (struct die_info *die, int max_level)
17515 {
17516   dump_die_1 (gdb_stdlog, 0, max_level, die);
17517 }
17518
17519 static void
17520 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17521 {
17522   void **slot;
17523
17524   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17525                                    INSERT);
17526
17527   *slot = die;
17528 }
17529
17530 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17531    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17532
17533 static int
17534 is_ref_attr (struct attribute *attr)
17535 {
17536   switch (attr->form)
17537     {
17538     case DW_FORM_ref_addr:
17539     case DW_FORM_ref1:
17540     case DW_FORM_ref2:
17541     case DW_FORM_ref4:
17542     case DW_FORM_ref8:
17543     case DW_FORM_ref_udata:
17544     case DW_FORM_GNU_ref_alt:
17545       return 1;
17546     default:
17547       return 0;
17548     }
17549 }
17550
17551 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17552    required kind.  */
17553
17554 static sect_offset
17555 dwarf2_get_ref_die_offset (struct attribute *attr)
17556 {
17557   sect_offset retval = { DW_UNSND (attr) };
17558
17559   if (is_ref_attr (attr))
17560     return retval;
17561
17562   retval.sect_off = 0;
17563   complaint (&symfile_complaints,
17564              _("unsupported die ref attribute form: '%s'"),
17565              dwarf_form_name (attr->form));
17566   return retval;
17567 }
17568
17569 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17570  * the value held by the attribute is not constant.  */
17571
17572 static LONGEST
17573 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17574 {
17575   if (attr->form == DW_FORM_sdata)
17576     return DW_SND (attr);
17577   else if (attr->form == DW_FORM_udata
17578            || attr->form == DW_FORM_data1
17579            || attr->form == DW_FORM_data2
17580            || attr->form == DW_FORM_data4
17581            || attr->form == DW_FORM_data8)
17582     return DW_UNSND (attr);
17583   else
17584     {
17585       complaint (&symfile_complaints,
17586                  _("Attribute value is not a constant (%s)"),
17587                  dwarf_form_name (attr->form));
17588       return default_value;
17589     }
17590 }
17591
17592 /* Follow reference or signature attribute ATTR of SRC_DIE.
17593    On entry *REF_CU is the CU of SRC_DIE.
17594    On exit *REF_CU is the CU of the result.  */
17595
17596 static struct die_info *
17597 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17598                        struct dwarf2_cu **ref_cu)
17599 {
17600   struct die_info *die;
17601
17602   if (is_ref_attr (attr))
17603     die = follow_die_ref (src_die, attr, ref_cu);
17604   else if (attr->form == DW_FORM_ref_sig8)
17605     die = follow_die_sig (src_die, attr, ref_cu);
17606   else
17607     {
17608       dump_die_for_error (src_die);
17609       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17610              (*ref_cu)->objfile->name);
17611     }
17612
17613   return die;
17614 }
17615
17616 /* Follow reference OFFSET.
17617    On entry *REF_CU is the CU of the source die referencing OFFSET.
17618    On exit *REF_CU is the CU of the result.
17619    Returns NULL if OFFSET is invalid.  */
17620
17621 static struct die_info *
17622 follow_die_offset (sect_offset offset, int offset_in_dwz,
17623                    struct dwarf2_cu **ref_cu)
17624 {
17625   struct die_info temp_die;
17626   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17627
17628   gdb_assert (cu->per_cu != NULL);
17629
17630   target_cu = cu;
17631
17632   if (cu->per_cu->is_debug_types)
17633     {
17634       /* .debug_types CUs cannot reference anything outside their CU.
17635          If they need to, they have to reference a signatured type via
17636          DW_FORM_ref_sig8.  */
17637       if (! offset_in_cu_p (&cu->header, offset))
17638         return NULL;
17639     }
17640   else if (offset_in_dwz != cu->per_cu->is_dwz
17641            || ! offset_in_cu_p (&cu->header, offset))
17642     {
17643       struct dwarf2_per_cu_data *per_cu;
17644
17645       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17646                                                  cu->objfile);
17647
17648       /* If necessary, add it to the queue and load its DIEs.  */
17649       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17650         load_full_comp_unit (per_cu, cu->language);
17651
17652       target_cu = per_cu->cu;
17653     }
17654   else if (cu->dies == NULL)
17655     {
17656       /* We're loading full DIEs during partial symbol reading.  */
17657       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17658       load_full_comp_unit (cu->per_cu, language_minimal);
17659     }
17660
17661   *ref_cu = target_cu;
17662   temp_die.offset = offset;
17663   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17664 }
17665
17666 /* Follow reference attribute ATTR of SRC_DIE.
17667    On entry *REF_CU is the CU of SRC_DIE.
17668    On exit *REF_CU is the CU of the result.  */
17669
17670 static struct die_info *
17671 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17672                 struct dwarf2_cu **ref_cu)
17673 {
17674   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17675   struct dwarf2_cu *cu = *ref_cu;
17676   struct die_info *die;
17677
17678   die = follow_die_offset (offset,
17679                            (attr->form == DW_FORM_GNU_ref_alt
17680                             || cu->per_cu->is_dwz),
17681                            ref_cu);
17682   if (!die)
17683     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17684            "at 0x%x [in module %s]"),
17685            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17686
17687   return die;
17688 }
17689
17690 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17691    Returned value is intended for DW_OP_call*.  Returned
17692    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17693
17694 struct dwarf2_locexpr_baton
17695 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17696                                struct dwarf2_per_cu_data *per_cu,
17697                                CORE_ADDR (*get_frame_pc) (void *baton),
17698                                void *baton)
17699 {
17700   struct dwarf2_cu *cu;
17701   struct die_info *die;
17702   struct attribute *attr;
17703   struct dwarf2_locexpr_baton retval;
17704
17705   dw2_setup (per_cu->objfile);
17706
17707   if (per_cu->cu == NULL)
17708     load_cu (per_cu);
17709   cu = per_cu->cu;
17710
17711   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17712   if (!die)
17713     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17714            offset.sect_off, per_cu->objfile->name);
17715
17716   attr = dwarf2_attr (die, DW_AT_location, cu);
17717   if (!attr)
17718     {
17719       /* DWARF: "If there is no such attribute, then there is no effect.".
17720          DATA is ignored if SIZE is 0.  */
17721
17722       retval.data = NULL;
17723       retval.size = 0;
17724     }
17725   else if (attr_form_is_section_offset (attr))
17726     {
17727       struct dwarf2_loclist_baton loclist_baton;
17728       CORE_ADDR pc = (*get_frame_pc) (baton);
17729       size_t size;
17730
17731       fill_in_loclist_baton (cu, &loclist_baton, attr);
17732
17733       retval.data = dwarf2_find_location_expression (&loclist_baton,
17734                                                      &size, pc);
17735       retval.size = size;
17736     }
17737   else
17738     {
17739       if (!attr_form_is_block (attr))
17740         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17741                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17742                offset.sect_off, per_cu->objfile->name);
17743
17744       retval.data = DW_BLOCK (attr)->data;
17745       retval.size = DW_BLOCK (attr)->size;
17746     }
17747   retval.per_cu = cu->per_cu;
17748
17749   age_cached_comp_units ();
17750
17751   return retval;
17752 }
17753
17754 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17755    offset.  */
17756
17757 struct dwarf2_locexpr_baton
17758 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17759                              struct dwarf2_per_cu_data *per_cu,
17760                              CORE_ADDR (*get_frame_pc) (void *baton),
17761                              void *baton)
17762 {
17763   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17764
17765   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17766 }
17767
17768 /* Write a constant of a given type as target-ordered bytes into
17769    OBSTACK.  */
17770
17771 static const gdb_byte *
17772 write_constant_as_bytes (struct obstack *obstack,
17773                          enum bfd_endian byte_order,
17774                          struct type *type,
17775                          ULONGEST value,
17776                          LONGEST *len)
17777 {
17778   gdb_byte *result;
17779
17780   *len = TYPE_LENGTH (type);
17781   result = obstack_alloc (obstack, *len);
17782   store_unsigned_integer (result, *len, byte_order, value);
17783
17784   return result;
17785 }
17786
17787 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
17788    pointer to the constant bytes and set LEN to the length of the
17789    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
17790    does not have a DW_AT_const_value, return NULL.  */
17791
17792 const gdb_byte *
17793 dwarf2_fetch_constant_bytes (sect_offset offset,
17794                              struct dwarf2_per_cu_data *per_cu,
17795                              struct obstack *obstack,
17796                              LONGEST *len)
17797 {
17798   struct dwarf2_cu *cu;
17799   struct die_info *die;
17800   struct attribute *attr;
17801   const gdb_byte *result = NULL;
17802   struct type *type;
17803   LONGEST value;
17804   enum bfd_endian byte_order;
17805
17806   dw2_setup (per_cu->objfile);
17807
17808   if (per_cu->cu == NULL)
17809     load_cu (per_cu);
17810   cu = per_cu->cu;
17811
17812   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17813   if (!die)
17814     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17815            offset.sect_off, per_cu->objfile->name);
17816
17817
17818   attr = dwarf2_attr (die, DW_AT_const_value, cu);
17819   if (attr == NULL)
17820     return NULL;
17821
17822   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
17823                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
17824
17825   switch (attr->form)
17826     {
17827     case DW_FORM_addr:
17828     case DW_FORM_GNU_addr_index:
17829       {
17830         gdb_byte *tem;
17831
17832         *len = cu->header.addr_size;
17833         tem = obstack_alloc (obstack, *len);
17834         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
17835         result = tem;
17836       }
17837       break;
17838     case DW_FORM_string:
17839     case DW_FORM_strp:
17840     case DW_FORM_GNU_str_index:
17841     case DW_FORM_GNU_strp_alt:
17842       /* DW_STRING is already allocated on the objfile obstack, point
17843          directly to it.  */
17844       result = (const gdb_byte *) DW_STRING (attr);
17845       *len = strlen (DW_STRING (attr));
17846       break;
17847     case DW_FORM_block1:
17848     case DW_FORM_block2:
17849     case DW_FORM_block4:
17850     case DW_FORM_block:
17851     case DW_FORM_exprloc:
17852       result = DW_BLOCK (attr)->data;
17853       *len = DW_BLOCK (attr)->size;
17854       break;
17855
17856       /* The DW_AT_const_value attributes are supposed to carry the
17857          symbol's value "represented as it would be on the target
17858          architecture."  By the time we get here, it's already been
17859          converted to host endianness, so we just need to sign- or
17860          zero-extend it as appropriate.  */
17861     case DW_FORM_data1:
17862       type = die_type (die, cu);
17863       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
17864       if (result == NULL)
17865         result = write_constant_as_bytes (obstack, byte_order,
17866                                           type, value, len);
17867       break;
17868     case DW_FORM_data2:
17869       type = die_type (die, cu);
17870       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
17871       if (result == NULL)
17872         result = write_constant_as_bytes (obstack, byte_order,
17873                                           type, value, len);
17874       break;
17875     case DW_FORM_data4:
17876       type = die_type (die, cu);
17877       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
17878       if (result == NULL)
17879         result = write_constant_as_bytes (obstack, byte_order,
17880                                           type, value, len);
17881       break;
17882     case DW_FORM_data8:
17883       type = die_type (die, cu);
17884       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
17885       if (result == NULL)
17886         result = write_constant_as_bytes (obstack, byte_order,
17887                                           type, value, len);
17888       break;
17889
17890     case DW_FORM_sdata:
17891       type = die_type (die, cu);
17892       result = write_constant_as_bytes (obstack, byte_order,
17893                                         type, DW_SND (attr), len);
17894       break;
17895
17896     case DW_FORM_udata:
17897       type = die_type (die, cu);
17898       result = write_constant_as_bytes (obstack, byte_order,
17899                                         type, DW_UNSND (attr), len);
17900       break;
17901
17902     default:
17903       complaint (&symfile_complaints,
17904                  _("unsupported const value attribute form: '%s'"),
17905                  dwarf_form_name (attr->form));
17906       break;
17907     }
17908
17909   return result;
17910 }
17911
17912 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17913    PER_CU.  */
17914
17915 struct type *
17916 dwarf2_get_die_type (cu_offset die_offset,
17917                      struct dwarf2_per_cu_data *per_cu)
17918 {
17919   sect_offset die_offset_sect;
17920
17921   dw2_setup (per_cu->objfile);
17922
17923   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17924   return get_die_type_at_offset (die_offset_sect, per_cu);
17925 }
17926
17927 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
17928    On entry *REF_CU is the CU of SRC_DIE.
17929    On exit *REF_CU is the CU of the result.
17930    Returns NULL if the referenced DIE isn't found.  */
17931
17932 static struct die_info *
17933 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
17934                   struct dwarf2_cu **ref_cu)
17935 {
17936   struct objfile *objfile = (*ref_cu)->objfile;
17937   struct die_info temp_die;
17938   struct dwarf2_cu *sig_cu;
17939   struct die_info *die;
17940
17941   /* While it might be nice to assert sig_type->type == NULL here,
17942      we can get here for DW_AT_imported_declaration where we need
17943      the DIE not the type.  */
17944
17945   /* If necessary, add it to the queue and load its DIEs.  */
17946
17947   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17948     read_signatured_type (sig_type);
17949
17950   gdb_assert (sig_type->per_cu.cu != NULL);
17951
17952   sig_cu = sig_type->per_cu.cu;
17953   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17954   temp_die.offset = sig_type->type_offset_in_section;
17955   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17956                              temp_die.offset.sect_off);
17957   if (die)
17958     {
17959       /* For .gdb_index version 7 keep track of included TUs.
17960          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17961       if (dwarf2_per_objfile->index_table != NULL
17962           && dwarf2_per_objfile->index_table->version <= 7)
17963         {
17964           VEC_safe_push (dwarf2_per_cu_ptr,
17965                          (*ref_cu)->per_cu->imported_symtabs,
17966                          sig_cu->per_cu);
17967         }
17968
17969       *ref_cu = sig_cu;
17970       return die;
17971     }
17972
17973   return NULL;
17974 }
17975
17976 /* Follow signatured type referenced by ATTR in SRC_DIE.
17977    On entry *REF_CU is the CU of SRC_DIE.
17978    On exit *REF_CU is the CU of the result.
17979    The result is the DIE of the type.
17980    If the referenced type cannot be found an error is thrown.  */
17981
17982 static struct die_info *
17983 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17984                 struct dwarf2_cu **ref_cu)
17985 {
17986   ULONGEST signature = DW_SIGNATURE (attr);
17987   struct signatured_type *sig_type;
17988   struct die_info *die;
17989
17990   gdb_assert (attr->form == DW_FORM_ref_sig8);
17991
17992   sig_type = lookup_signatured_type (signature);
17993   /* sig_type will be NULL if the signatured type is missing from
17994      the debug info.  */
17995   if (sig_type == NULL)
17996     {
17997       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
17998                " from DIE at 0x%x [in module %s]"),
17999              hex_string (signature), src_die->offset.sect_off,
18000              (*ref_cu)->objfile->name);
18001     }
18002
18003   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18004   if (die == NULL)
18005     {
18006       dump_die_for_error (src_die);
18007       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18008                " from DIE at 0x%x [in module %s]"),
18009              hex_string (signature), src_die->offset.sect_off,
18010              (*ref_cu)->objfile->name);
18011     }
18012
18013   return die;
18014 }
18015
18016 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18017    reading in and processing the type unit if necessary.  */
18018
18019 static struct type *
18020 get_signatured_type (struct die_info *die, ULONGEST signature,
18021                      struct dwarf2_cu *cu)
18022 {
18023   struct signatured_type *sig_type;
18024   struct dwarf2_cu *type_cu;
18025   struct die_info *type_die;
18026   struct type *type;
18027
18028   sig_type = lookup_signatured_type (signature);
18029   /* sig_type will be NULL if the signatured type is missing from
18030      the debug info.  */
18031   if (sig_type == NULL)
18032     {
18033       complaint (&symfile_complaints,
18034                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18035                    " from DIE at 0x%x [in module %s]"),
18036                  hex_string (signature), die->offset.sect_off,
18037                  dwarf2_per_objfile->objfile->name);
18038       return build_error_marker_type (cu, die);
18039     }
18040
18041   /* If we already know the type we're done.  */
18042   if (sig_type->type != NULL)
18043     return sig_type->type;
18044
18045   type_cu = cu;
18046   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18047   if (type_die != NULL)
18048     {
18049       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18050          is created.  This is important, for example, because for c++ classes
18051          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18052       type = read_type_die (type_die, type_cu);
18053       if (type == NULL)
18054         {
18055           complaint (&symfile_complaints,
18056                      _("Dwarf Error: Cannot build signatured type %s"
18057                        " referenced from DIE at 0x%x [in module %s]"),
18058                      hex_string (signature), die->offset.sect_off,
18059                      dwarf2_per_objfile->objfile->name);
18060           type = build_error_marker_type (cu, die);
18061         }
18062     }
18063   else
18064     {
18065       complaint (&symfile_complaints,
18066                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18067                    " from DIE at 0x%x [in module %s]"),
18068                  hex_string (signature), die->offset.sect_off,
18069                  dwarf2_per_objfile->objfile->name);
18070       type = build_error_marker_type (cu, die);
18071     }
18072   sig_type->type = type;
18073
18074   return type;
18075 }
18076
18077 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18078    reading in and processing the type unit if necessary.  */
18079
18080 static struct type *
18081 get_DW_AT_signature_type (struct die_info *die, struct attribute *attr,
18082                           struct dwarf2_cu *cu) /* ARI: editCase function */
18083 {
18084   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18085   if (is_ref_attr (attr))
18086     {
18087       struct dwarf2_cu *type_cu = cu;
18088       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18089
18090       return read_type_die (type_die, type_cu);
18091     }
18092   else if (attr->form == DW_FORM_ref_sig8)
18093     {
18094       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18095     }
18096   else
18097     {
18098       complaint (&symfile_complaints,
18099                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18100                    " at 0x%x [in module %s]"),
18101                  dwarf_form_name (attr->form), die->offset.sect_off,
18102                  dwarf2_per_objfile->objfile->name);
18103       return build_error_marker_type (cu, die);
18104     }
18105 }
18106
18107 /* Load the DIEs associated with type unit PER_CU into memory.  */
18108
18109 static void
18110 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18111 {
18112   struct signatured_type *sig_type;
18113
18114   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18115   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18116
18117   /* We have the per_cu, but we need the signatured_type.
18118      Fortunately this is an easy translation.  */
18119   gdb_assert (per_cu->is_debug_types);
18120   sig_type = (struct signatured_type *) per_cu;
18121
18122   gdb_assert (per_cu->cu == NULL);
18123
18124   read_signatured_type (sig_type);
18125
18126   gdb_assert (per_cu->cu != NULL);
18127 }
18128
18129 /* die_reader_func for read_signatured_type.
18130    This is identical to load_full_comp_unit_reader,
18131    but is kept separate for now.  */
18132
18133 static void
18134 read_signatured_type_reader (const struct die_reader_specs *reader,
18135                              const gdb_byte *info_ptr,
18136                              struct die_info *comp_unit_die,
18137                              int has_children,
18138                              void *data)
18139 {
18140   struct dwarf2_cu *cu = reader->cu;
18141
18142   gdb_assert (cu->die_hash == NULL);
18143   cu->die_hash =
18144     htab_create_alloc_ex (cu->header.length / 12,
18145                           die_hash,
18146                           die_eq,
18147                           NULL,
18148                           &cu->comp_unit_obstack,
18149                           hashtab_obstack_allocate,
18150                           dummy_obstack_deallocate);
18151
18152   if (has_children)
18153     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18154                                                   &info_ptr, comp_unit_die);
18155   cu->dies = comp_unit_die;
18156   /* comp_unit_die is not stored in die_hash, no need.  */
18157
18158   /* We try not to read any attributes in this function, because not
18159      all CUs needed for references have been loaded yet, and symbol
18160      table processing isn't initialized.  But we have to set the CU language,
18161      or we won't be able to build types correctly.
18162      Similarly, if we do not read the producer, we can not apply
18163      producer-specific interpretation.  */
18164   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18165 }
18166
18167 /* Read in a signatured type and build its CU and DIEs.
18168    If the type is a stub for the real type in a DWO file,
18169    read in the real type from the DWO file as well.  */
18170
18171 static void
18172 read_signatured_type (struct signatured_type *sig_type)
18173 {
18174   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18175
18176   gdb_assert (per_cu->is_debug_types);
18177   gdb_assert (per_cu->cu == NULL);
18178
18179   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18180                            read_signatured_type_reader, NULL);
18181 }
18182
18183 /* Decode simple location descriptions.
18184    Given a pointer to a dwarf block that defines a location, compute
18185    the location and return the value.
18186
18187    NOTE drow/2003-11-18: This function is called in two situations
18188    now: for the address of static or global variables (partial symbols
18189    only) and for offsets into structures which are expected to be
18190    (more or less) constant.  The partial symbol case should go away,
18191    and only the constant case should remain.  That will let this
18192    function complain more accurately.  A few special modes are allowed
18193    without complaint for global variables (for instance, global
18194    register values and thread-local values).
18195
18196    A location description containing no operations indicates that the
18197    object is optimized out.  The return value is 0 for that case.
18198    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18199    callers will only want a very basic result and this can become a
18200    complaint.
18201
18202    Note that stack[0] is unused except as a default error return.  */
18203
18204 static CORE_ADDR
18205 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18206 {
18207   struct objfile *objfile = cu->objfile;
18208   size_t i;
18209   size_t size = blk->size;
18210   const gdb_byte *data = blk->data;
18211   CORE_ADDR stack[64];
18212   int stacki;
18213   unsigned int bytes_read, unsnd;
18214   gdb_byte op;
18215
18216   i = 0;
18217   stacki = 0;
18218   stack[stacki] = 0;
18219   stack[++stacki] = 0;
18220
18221   while (i < size)
18222     {
18223       op = data[i++];
18224       switch (op)
18225         {
18226         case DW_OP_lit0:
18227         case DW_OP_lit1:
18228         case DW_OP_lit2:
18229         case DW_OP_lit3:
18230         case DW_OP_lit4:
18231         case DW_OP_lit5:
18232         case DW_OP_lit6:
18233         case DW_OP_lit7:
18234         case DW_OP_lit8:
18235         case DW_OP_lit9:
18236         case DW_OP_lit10:
18237         case DW_OP_lit11:
18238         case DW_OP_lit12:
18239         case DW_OP_lit13:
18240         case DW_OP_lit14:
18241         case DW_OP_lit15:
18242         case DW_OP_lit16:
18243         case DW_OP_lit17:
18244         case DW_OP_lit18:
18245         case DW_OP_lit19:
18246         case DW_OP_lit20:
18247         case DW_OP_lit21:
18248         case DW_OP_lit22:
18249         case DW_OP_lit23:
18250         case DW_OP_lit24:
18251         case DW_OP_lit25:
18252         case DW_OP_lit26:
18253         case DW_OP_lit27:
18254         case DW_OP_lit28:
18255         case DW_OP_lit29:
18256         case DW_OP_lit30:
18257         case DW_OP_lit31:
18258           stack[++stacki] = op - DW_OP_lit0;
18259           break;
18260
18261         case DW_OP_reg0:
18262         case DW_OP_reg1:
18263         case DW_OP_reg2:
18264         case DW_OP_reg3:
18265         case DW_OP_reg4:
18266         case DW_OP_reg5:
18267         case DW_OP_reg6:
18268         case DW_OP_reg7:
18269         case DW_OP_reg8:
18270         case DW_OP_reg9:
18271         case DW_OP_reg10:
18272         case DW_OP_reg11:
18273         case DW_OP_reg12:
18274         case DW_OP_reg13:
18275         case DW_OP_reg14:
18276         case DW_OP_reg15:
18277         case DW_OP_reg16:
18278         case DW_OP_reg17:
18279         case DW_OP_reg18:
18280         case DW_OP_reg19:
18281         case DW_OP_reg20:
18282         case DW_OP_reg21:
18283         case DW_OP_reg22:
18284         case DW_OP_reg23:
18285         case DW_OP_reg24:
18286         case DW_OP_reg25:
18287         case DW_OP_reg26:
18288         case DW_OP_reg27:
18289         case DW_OP_reg28:
18290         case DW_OP_reg29:
18291         case DW_OP_reg30:
18292         case DW_OP_reg31:
18293           stack[++stacki] = op - DW_OP_reg0;
18294           if (i < size)
18295             dwarf2_complex_location_expr_complaint ();
18296           break;
18297
18298         case DW_OP_regx:
18299           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18300           i += bytes_read;
18301           stack[++stacki] = unsnd;
18302           if (i < size)
18303             dwarf2_complex_location_expr_complaint ();
18304           break;
18305
18306         case DW_OP_addr:
18307           stack[++stacki] = read_address (objfile->obfd, &data[i],
18308                                           cu, &bytes_read);
18309           i += bytes_read;
18310           break;
18311
18312         case DW_OP_const1u:
18313           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18314           i += 1;
18315           break;
18316
18317         case DW_OP_const1s:
18318           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18319           i += 1;
18320           break;
18321
18322         case DW_OP_const2u:
18323           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18324           i += 2;
18325           break;
18326
18327         case DW_OP_const2s:
18328           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18329           i += 2;
18330           break;
18331
18332         case DW_OP_const4u:
18333           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18334           i += 4;
18335           break;
18336
18337         case DW_OP_const4s:
18338           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18339           i += 4;
18340           break;
18341
18342         case DW_OP_const8u:
18343           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18344           i += 8;
18345           break;
18346
18347         case DW_OP_constu:
18348           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18349                                                   &bytes_read);
18350           i += bytes_read;
18351           break;
18352
18353         case DW_OP_consts:
18354           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18355           i += bytes_read;
18356           break;
18357
18358         case DW_OP_dup:
18359           stack[stacki + 1] = stack[stacki];
18360           stacki++;
18361           break;
18362
18363         case DW_OP_plus:
18364           stack[stacki - 1] += stack[stacki];
18365           stacki--;
18366           break;
18367
18368         case DW_OP_plus_uconst:
18369           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18370                                                  &bytes_read);
18371           i += bytes_read;
18372           break;
18373
18374         case DW_OP_minus:
18375           stack[stacki - 1] -= stack[stacki];
18376           stacki--;
18377           break;
18378
18379         case DW_OP_deref:
18380           /* If we're not the last op, then we definitely can't encode
18381              this using GDB's address_class enum.  This is valid for partial
18382              global symbols, although the variable's address will be bogus
18383              in the psymtab.  */
18384           if (i < size)
18385             dwarf2_complex_location_expr_complaint ();
18386           break;
18387
18388         case DW_OP_GNU_push_tls_address:
18389           /* The top of the stack has the offset from the beginning
18390              of the thread control block at which the variable is located.  */
18391           /* Nothing should follow this operator, so the top of stack would
18392              be returned.  */
18393           /* This is valid for partial global symbols, but the variable's
18394              address will be bogus in the psymtab.  Make it always at least
18395              non-zero to not look as a variable garbage collected by linker
18396              which have DW_OP_addr 0.  */
18397           if (i < size)
18398             dwarf2_complex_location_expr_complaint ();
18399           stack[stacki]++;
18400           break;
18401
18402         case DW_OP_GNU_uninit:
18403           break;
18404
18405         case DW_OP_GNU_addr_index:
18406         case DW_OP_GNU_const_index:
18407           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18408                                                          &bytes_read);
18409           i += bytes_read;
18410           break;
18411
18412         default:
18413           {
18414             const char *name = get_DW_OP_name (op);
18415
18416             if (name)
18417               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18418                          name);
18419             else
18420               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18421                          op);
18422           }
18423
18424           return (stack[stacki]);
18425         }
18426
18427       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18428          outside of the allocated space.  Also enforce minimum>0.  */
18429       if (stacki >= ARRAY_SIZE (stack) - 1)
18430         {
18431           complaint (&symfile_complaints,
18432                      _("location description stack overflow"));
18433           return 0;
18434         }
18435
18436       if (stacki <= 0)
18437         {
18438           complaint (&symfile_complaints,
18439                      _("location description stack underflow"));
18440           return 0;
18441         }
18442     }
18443   return (stack[stacki]);
18444 }
18445
18446 /* memory allocation interface */
18447
18448 static struct dwarf_block *
18449 dwarf_alloc_block (struct dwarf2_cu *cu)
18450 {
18451   struct dwarf_block *blk;
18452
18453   blk = (struct dwarf_block *)
18454     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18455   return (blk);
18456 }
18457
18458 static struct die_info *
18459 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18460 {
18461   struct die_info *die;
18462   size_t size = sizeof (struct die_info);
18463
18464   if (num_attrs > 1)
18465     size += (num_attrs - 1) * sizeof (struct attribute);
18466
18467   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18468   memset (die, 0, sizeof (struct die_info));
18469   return (die);
18470 }
18471
18472 \f
18473 /* Macro support.  */
18474
18475 /* Return file name relative to the compilation directory of file number I in
18476    *LH's file name table.  The result is allocated using xmalloc; the caller is
18477    responsible for freeing it.  */
18478
18479 static char *
18480 file_file_name (int file, struct line_header *lh)
18481 {
18482   /* Is the file number a valid index into the line header's file name
18483      table?  Remember that file numbers start with one, not zero.  */
18484   if (1 <= file && file <= lh->num_file_names)
18485     {
18486       struct file_entry *fe = &lh->file_names[file - 1];
18487
18488       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18489         return xstrdup (fe->name);
18490       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18491                      fe->name, NULL);
18492     }
18493   else
18494     {
18495       /* The compiler produced a bogus file number.  We can at least
18496          record the macro definitions made in the file, even if we
18497          won't be able to find the file by name.  */
18498       char fake_name[80];
18499
18500       xsnprintf (fake_name, sizeof (fake_name),
18501                  "<bad macro file number %d>", file);
18502
18503       complaint (&symfile_complaints,
18504                  _("bad file number in macro information (%d)"),
18505                  file);
18506
18507       return xstrdup (fake_name);
18508     }
18509 }
18510
18511 /* Return the full name of file number I in *LH's file name table.
18512    Use COMP_DIR as the name of the current directory of the
18513    compilation.  The result is allocated using xmalloc; the caller is
18514    responsible for freeing it.  */
18515 static char *
18516 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18517 {
18518   /* Is the file number a valid index into the line header's file name
18519      table?  Remember that file numbers start with one, not zero.  */
18520   if (1 <= file && file <= lh->num_file_names)
18521     {
18522       char *relative = file_file_name (file, lh);
18523
18524       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18525         return relative;
18526       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18527     }
18528   else
18529     return file_file_name (file, lh);
18530 }
18531
18532
18533 static struct macro_source_file *
18534 macro_start_file (int file, int line,
18535                   struct macro_source_file *current_file,
18536                   const char *comp_dir,
18537                   struct line_header *lh, struct objfile *objfile)
18538 {
18539   /* File name relative to the compilation directory of this source file.  */
18540   char *file_name = file_file_name (file, lh);
18541
18542   /* We don't create a macro table for this compilation unit
18543      at all until we actually get a filename.  */
18544   if (! pending_macros)
18545     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18546                                       objfile->per_bfd->macro_cache,
18547                                       comp_dir);
18548
18549   if (! current_file)
18550     {
18551       /* If we have no current file, then this must be the start_file
18552          directive for the compilation unit's main source file.  */
18553       current_file = macro_set_main (pending_macros, file_name);
18554       macro_define_special (pending_macros);
18555     }
18556   else
18557     current_file = macro_include (current_file, line, file_name);
18558
18559   xfree (file_name);
18560
18561   return current_file;
18562 }
18563
18564
18565 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18566    followed by a null byte.  */
18567 static char *
18568 copy_string (const char *buf, int len)
18569 {
18570   char *s = xmalloc (len + 1);
18571
18572   memcpy (s, buf, len);
18573   s[len] = '\0';
18574   return s;
18575 }
18576
18577
18578 static const char *
18579 consume_improper_spaces (const char *p, const char *body)
18580 {
18581   if (*p == ' ')
18582     {
18583       complaint (&symfile_complaints,
18584                  _("macro definition contains spaces "
18585                    "in formal argument list:\n`%s'"),
18586                  body);
18587
18588       while (*p == ' ')
18589         p++;
18590     }
18591
18592   return p;
18593 }
18594
18595
18596 static void
18597 parse_macro_definition (struct macro_source_file *file, int line,
18598                         const char *body)
18599 {
18600   const char *p;
18601
18602   /* The body string takes one of two forms.  For object-like macro
18603      definitions, it should be:
18604
18605         <macro name> " " <definition>
18606
18607      For function-like macro definitions, it should be:
18608
18609         <macro name> "() " <definition>
18610      or
18611         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18612
18613      Spaces may appear only where explicitly indicated, and in the
18614      <definition>.
18615
18616      The Dwarf 2 spec says that an object-like macro's name is always
18617      followed by a space, but versions of GCC around March 2002 omit
18618      the space when the macro's definition is the empty string.
18619
18620      The Dwarf 2 spec says that there should be no spaces between the
18621      formal arguments in a function-like macro's formal argument list,
18622      but versions of GCC around March 2002 include spaces after the
18623      commas.  */
18624
18625
18626   /* Find the extent of the macro name.  The macro name is terminated
18627      by either a space or null character (for an object-like macro) or
18628      an opening paren (for a function-like macro).  */
18629   for (p = body; *p; p++)
18630     if (*p == ' ' || *p == '(')
18631       break;
18632
18633   if (*p == ' ' || *p == '\0')
18634     {
18635       /* It's an object-like macro.  */
18636       int name_len = p - body;
18637       char *name = copy_string (body, name_len);
18638       const char *replacement;
18639
18640       if (*p == ' ')
18641         replacement = body + name_len + 1;
18642       else
18643         {
18644           dwarf2_macro_malformed_definition_complaint (body);
18645           replacement = body + name_len;
18646         }
18647
18648       macro_define_object (file, line, name, replacement);
18649
18650       xfree (name);
18651     }
18652   else if (*p == '(')
18653     {
18654       /* It's a function-like macro.  */
18655       char *name = copy_string (body, p - body);
18656       int argc = 0;
18657       int argv_size = 1;
18658       char **argv = xmalloc (argv_size * sizeof (*argv));
18659
18660       p++;
18661
18662       p = consume_improper_spaces (p, body);
18663
18664       /* Parse the formal argument list.  */
18665       while (*p && *p != ')')
18666         {
18667           /* Find the extent of the current argument name.  */
18668           const char *arg_start = p;
18669
18670           while (*p && *p != ',' && *p != ')' && *p != ' ')
18671             p++;
18672
18673           if (! *p || p == arg_start)
18674             dwarf2_macro_malformed_definition_complaint (body);
18675           else
18676             {
18677               /* Make sure argv has room for the new argument.  */
18678               if (argc >= argv_size)
18679                 {
18680                   argv_size *= 2;
18681                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18682                 }
18683
18684               argv[argc++] = copy_string (arg_start, p - arg_start);
18685             }
18686
18687           p = consume_improper_spaces (p, body);
18688
18689           /* Consume the comma, if present.  */
18690           if (*p == ',')
18691             {
18692               p++;
18693
18694               p = consume_improper_spaces (p, body);
18695             }
18696         }
18697
18698       if (*p == ')')
18699         {
18700           p++;
18701
18702           if (*p == ' ')
18703             /* Perfectly formed definition, no complaints.  */
18704             macro_define_function (file, line, name,
18705                                    argc, (const char **) argv,
18706                                    p + 1);
18707           else if (*p == '\0')
18708             {
18709               /* Complain, but do define it.  */
18710               dwarf2_macro_malformed_definition_complaint (body);
18711               macro_define_function (file, line, name,
18712                                      argc, (const char **) argv,
18713                                      p);
18714             }
18715           else
18716             /* Just complain.  */
18717             dwarf2_macro_malformed_definition_complaint (body);
18718         }
18719       else
18720         /* Just complain.  */
18721         dwarf2_macro_malformed_definition_complaint (body);
18722
18723       xfree (name);
18724       {
18725         int i;
18726
18727         for (i = 0; i < argc; i++)
18728           xfree (argv[i]);
18729       }
18730       xfree (argv);
18731     }
18732   else
18733     dwarf2_macro_malformed_definition_complaint (body);
18734 }
18735
18736 /* Skip some bytes from BYTES according to the form given in FORM.
18737    Returns the new pointer.  */
18738
18739 static const gdb_byte *
18740 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
18741                  enum dwarf_form form,
18742                  unsigned int offset_size,
18743                  struct dwarf2_section_info *section)
18744 {
18745   unsigned int bytes_read;
18746
18747   switch (form)
18748     {
18749     case DW_FORM_data1:
18750     case DW_FORM_flag:
18751       ++bytes;
18752       break;
18753
18754     case DW_FORM_data2:
18755       bytes += 2;
18756       break;
18757
18758     case DW_FORM_data4:
18759       bytes += 4;
18760       break;
18761
18762     case DW_FORM_data8:
18763       bytes += 8;
18764       break;
18765
18766     case DW_FORM_string:
18767       read_direct_string (abfd, bytes, &bytes_read);
18768       bytes += bytes_read;
18769       break;
18770
18771     case DW_FORM_sec_offset:
18772     case DW_FORM_strp:
18773     case DW_FORM_GNU_strp_alt:
18774       bytes += offset_size;
18775       break;
18776
18777     case DW_FORM_block:
18778       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18779       bytes += bytes_read;
18780       break;
18781
18782     case DW_FORM_block1:
18783       bytes += 1 + read_1_byte (abfd, bytes);
18784       break;
18785     case DW_FORM_block2:
18786       bytes += 2 + read_2_bytes (abfd, bytes);
18787       break;
18788     case DW_FORM_block4:
18789       bytes += 4 + read_4_bytes (abfd, bytes);
18790       break;
18791
18792     case DW_FORM_sdata:
18793     case DW_FORM_udata:
18794     case DW_FORM_GNU_addr_index:
18795     case DW_FORM_GNU_str_index:
18796       bytes = gdb_skip_leb128 (bytes, buffer_end);
18797       if (bytes == NULL)
18798         {
18799           dwarf2_section_buffer_overflow_complaint (section);
18800           return NULL;
18801         }
18802       break;
18803
18804     default:
18805       {
18806       complain:
18807         complaint (&symfile_complaints,
18808                    _("invalid form 0x%x in `%s'"),
18809                    form,
18810                    section->asection->name);
18811         return NULL;
18812       }
18813     }
18814
18815   return bytes;
18816 }
18817
18818 /* A helper for dwarf_decode_macros that handles skipping an unknown
18819    opcode.  Returns an updated pointer to the macro data buffer; or,
18820    on error, issues a complaint and returns NULL.  */
18821
18822 static const gdb_byte *
18823 skip_unknown_opcode (unsigned int opcode,
18824                      const gdb_byte **opcode_definitions,
18825                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
18826                      bfd *abfd,
18827                      unsigned int offset_size,
18828                      struct dwarf2_section_info *section)
18829 {
18830   unsigned int bytes_read, i;
18831   unsigned long arg;
18832   const gdb_byte *defn;
18833
18834   if (opcode_definitions[opcode] == NULL)
18835     {
18836       complaint (&symfile_complaints,
18837                  _("unrecognized DW_MACFINO opcode 0x%x"),
18838                  opcode);
18839       return NULL;
18840     }
18841
18842   defn = opcode_definitions[opcode];
18843   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18844   defn += bytes_read;
18845
18846   for (i = 0; i < arg; ++i)
18847     {
18848       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18849                                  section);
18850       if (mac_ptr == NULL)
18851         {
18852           /* skip_form_bytes already issued the complaint.  */
18853           return NULL;
18854         }
18855     }
18856
18857   return mac_ptr;
18858 }
18859
18860 /* A helper function which parses the header of a macro section.
18861    If the macro section is the extended (for now called "GNU") type,
18862    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18863    the header, or issues a complaint and returns NULL on error.  */
18864
18865 static const gdb_byte *
18866 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
18867                           bfd *abfd,
18868                           const gdb_byte *mac_ptr,
18869                           unsigned int *offset_size,
18870                           int section_is_gnu)
18871 {
18872   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18873
18874   if (section_is_gnu)
18875     {
18876       unsigned int version, flags;
18877
18878       version = read_2_bytes (abfd, mac_ptr);
18879       if (version != 4)
18880         {
18881           complaint (&symfile_complaints,
18882                      _("unrecognized version `%d' in .debug_macro section"),
18883                      version);
18884           return NULL;
18885         }
18886       mac_ptr += 2;
18887
18888       flags = read_1_byte (abfd, mac_ptr);
18889       ++mac_ptr;
18890       *offset_size = (flags & 1) ? 8 : 4;
18891
18892       if ((flags & 2) != 0)
18893         /* We don't need the line table offset.  */
18894         mac_ptr += *offset_size;
18895
18896       /* Vendor opcode descriptions.  */
18897       if ((flags & 4) != 0)
18898         {
18899           unsigned int i, count;
18900
18901           count = read_1_byte (abfd, mac_ptr);
18902           ++mac_ptr;
18903           for (i = 0; i < count; ++i)
18904             {
18905               unsigned int opcode, bytes_read;
18906               unsigned long arg;
18907
18908               opcode = read_1_byte (abfd, mac_ptr);
18909               ++mac_ptr;
18910               opcode_definitions[opcode] = mac_ptr;
18911               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18912               mac_ptr += bytes_read;
18913               mac_ptr += arg;
18914             }
18915         }
18916     }
18917
18918   return mac_ptr;
18919 }
18920
18921 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18922    including DW_MACRO_GNU_transparent_include.  */
18923
18924 static void
18925 dwarf_decode_macro_bytes (bfd *abfd,
18926                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
18927                           struct macro_source_file *current_file,
18928                           struct line_header *lh, const char *comp_dir,
18929                           struct dwarf2_section_info *section,
18930                           int section_is_gnu, int section_is_dwz,
18931                           unsigned int offset_size,
18932                           struct objfile *objfile,
18933                           htab_t include_hash)
18934 {
18935   enum dwarf_macro_record_type macinfo_type;
18936   int at_commandline;
18937   const gdb_byte *opcode_definitions[256];
18938
18939   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18940                                       &offset_size, section_is_gnu);
18941   if (mac_ptr == NULL)
18942     {
18943       /* We already issued a complaint.  */
18944       return;
18945     }
18946
18947   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18948      GDB is still reading the definitions from command line.  First
18949      DW_MACINFO_start_file will need to be ignored as it was already executed
18950      to create CURRENT_FILE for the main source holding also the command line
18951      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18952      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18953
18954   at_commandline = 1;
18955
18956   do
18957     {
18958       /* Do we at least have room for a macinfo type byte?  */
18959       if (mac_ptr >= mac_end)
18960         {
18961           dwarf2_section_buffer_overflow_complaint (section);
18962           break;
18963         }
18964
18965       macinfo_type = read_1_byte (abfd, mac_ptr);
18966       mac_ptr++;
18967
18968       /* Note that we rely on the fact that the corresponding GNU and
18969          DWARF constants are the same.  */
18970       switch (macinfo_type)
18971         {
18972           /* A zero macinfo type indicates the end of the macro
18973              information.  */
18974         case 0:
18975           break;
18976
18977         case DW_MACRO_GNU_define:
18978         case DW_MACRO_GNU_undef:
18979         case DW_MACRO_GNU_define_indirect:
18980         case DW_MACRO_GNU_undef_indirect:
18981         case DW_MACRO_GNU_define_indirect_alt:
18982         case DW_MACRO_GNU_undef_indirect_alt:
18983           {
18984             unsigned int bytes_read;
18985             int line;
18986             const char *body;
18987             int is_define;
18988
18989             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18990             mac_ptr += bytes_read;
18991
18992             if (macinfo_type == DW_MACRO_GNU_define
18993                 || macinfo_type == DW_MACRO_GNU_undef)
18994               {
18995                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18996                 mac_ptr += bytes_read;
18997               }
18998             else
18999               {
19000                 LONGEST str_offset;
19001
19002                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19003                 mac_ptr += offset_size;
19004
19005                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19006                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19007                     || section_is_dwz)
19008                   {
19009                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19010
19011                     body = read_indirect_string_from_dwz (dwz, str_offset);
19012                   }
19013                 else
19014                   body = read_indirect_string_at_offset (abfd, str_offset);
19015               }
19016
19017             is_define = (macinfo_type == DW_MACRO_GNU_define
19018                          || macinfo_type == DW_MACRO_GNU_define_indirect
19019                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19020             if (! current_file)
19021               {
19022                 /* DWARF violation as no main source is present.  */
19023                 complaint (&symfile_complaints,
19024                            _("debug info with no main source gives macro %s "
19025                              "on line %d: %s"),
19026                            is_define ? _("definition") : _("undefinition"),
19027                            line, body);
19028                 break;
19029               }
19030             if ((line == 0 && !at_commandline)
19031                 || (line != 0 && at_commandline))
19032               complaint (&symfile_complaints,
19033                          _("debug info gives %s macro %s with %s line %d: %s"),
19034                          at_commandline ? _("command-line") : _("in-file"),
19035                          is_define ? _("definition") : _("undefinition"),
19036                          line == 0 ? _("zero") : _("non-zero"), line, body);
19037
19038             if (is_define)
19039               parse_macro_definition (current_file, line, body);
19040             else
19041               {
19042                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19043                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19044                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19045                 macro_undef (current_file, line, body);
19046               }
19047           }
19048           break;
19049
19050         case DW_MACRO_GNU_start_file:
19051           {
19052             unsigned int bytes_read;
19053             int line, file;
19054
19055             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19056             mac_ptr += bytes_read;
19057             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19058             mac_ptr += bytes_read;
19059
19060             if ((line == 0 && !at_commandline)
19061                 || (line != 0 && at_commandline))
19062               complaint (&symfile_complaints,
19063                          _("debug info gives source %d included "
19064                            "from %s at %s line %d"),
19065                          file, at_commandline ? _("command-line") : _("file"),
19066                          line == 0 ? _("zero") : _("non-zero"), line);
19067
19068             if (at_commandline)
19069               {
19070                 /* This DW_MACRO_GNU_start_file was executed in the
19071                    pass one.  */
19072                 at_commandline = 0;
19073               }
19074             else
19075               current_file = macro_start_file (file, line,
19076                                                current_file, comp_dir,
19077                                                lh, objfile);
19078           }
19079           break;
19080
19081         case DW_MACRO_GNU_end_file:
19082           if (! current_file)
19083             complaint (&symfile_complaints,
19084                        _("macro debug info has an unmatched "
19085                          "`close_file' directive"));
19086           else
19087             {
19088               current_file = current_file->included_by;
19089               if (! current_file)
19090                 {
19091                   enum dwarf_macro_record_type next_type;
19092
19093                   /* GCC circa March 2002 doesn't produce the zero
19094                      type byte marking the end of the compilation
19095                      unit.  Complain if it's not there, but exit no
19096                      matter what.  */
19097
19098                   /* Do we at least have room for a macinfo type byte?  */
19099                   if (mac_ptr >= mac_end)
19100                     {
19101                       dwarf2_section_buffer_overflow_complaint (section);
19102                       return;
19103                     }
19104
19105                   /* We don't increment mac_ptr here, so this is just
19106                      a look-ahead.  */
19107                   next_type = read_1_byte (abfd, mac_ptr);
19108                   if (next_type != 0)
19109                     complaint (&symfile_complaints,
19110                                _("no terminating 0-type entry for "
19111                                  "macros in `.debug_macinfo' section"));
19112
19113                   return;
19114                 }
19115             }
19116           break;
19117
19118         case DW_MACRO_GNU_transparent_include:
19119         case DW_MACRO_GNU_transparent_include_alt:
19120           {
19121             LONGEST offset;
19122             void **slot;
19123             bfd *include_bfd = abfd;
19124             struct dwarf2_section_info *include_section = section;
19125             struct dwarf2_section_info alt_section;
19126             const gdb_byte *include_mac_end = mac_end;
19127             int is_dwz = section_is_dwz;
19128             const gdb_byte *new_mac_ptr;
19129
19130             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19131             mac_ptr += offset_size;
19132
19133             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19134               {
19135                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19136
19137                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19138                                      &dwz->macro);
19139
19140                 include_bfd = dwz->macro.asection->owner;
19141                 include_section = &dwz->macro;
19142                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19143                 is_dwz = 1;
19144               }
19145
19146             new_mac_ptr = include_section->buffer + offset;
19147             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19148
19149             if (*slot != NULL)
19150               {
19151                 /* This has actually happened; see
19152                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19153                 complaint (&symfile_complaints,
19154                            _("recursive DW_MACRO_GNU_transparent_include in "
19155                              ".debug_macro section"));
19156               }
19157             else
19158               {
19159                 *slot = (void *) new_mac_ptr;
19160
19161                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19162                                           include_mac_end, current_file,
19163                                           lh, comp_dir,
19164                                           section, section_is_gnu, is_dwz,
19165                                           offset_size, objfile, include_hash);
19166
19167                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19168               }
19169           }
19170           break;
19171
19172         case DW_MACINFO_vendor_ext:
19173           if (!section_is_gnu)
19174             {
19175               unsigned int bytes_read;
19176               int constant;
19177
19178               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19179               mac_ptr += bytes_read;
19180               read_direct_string (abfd, mac_ptr, &bytes_read);
19181               mac_ptr += bytes_read;
19182
19183               /* We don't recognize any vendor extensions.  */
19184               break;
19185             }
19186           /* FALLTHROUGH */
19187
19188         default:
19189           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19190                                          mac_ptr, mac_end, abfd, offset_size,
19191                                          section);
19192           if (mac_ptr == NULL)
19193             return;
19194           break;
19195         }
19196     } while (macinfo_type != 0);
19197 }
19198
19199 static void
19200 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19201                      const char *comp_dir, int section_is_gnu)
19202 {
19203   struct objfile *objfile = dwarf2_per_objfile->objfile;
19204   struct line_header *lh = cu->line_header;
19205   bfd *abfd;
19206   const gdb_byte *mac_ptr, *mac_end;
19207   struct macro_source_file *current_file = 0;
19208   enum dwarf_macro_record_type macinfo_type;
19209   unsigned int offset_size = cu->header.offset_size;
19210   const gdb_byte *opcode_definitions[256];
19211   struct cleanup *cleanup;
19212   htab_t include_hash;
19213   void **slot;
19214   struct dwarf2_section_info *section;
19215   const char *section_name;
19216
19217   if (cu->dwo_unit != NULL)
19218     {
19219       if (section_is_gnu)
19220         {
19221           section = &cu->dwo_unit->dwo_file->sections.macro;
19222           section_name = ".debug_macro.dwo";
19223         }
19224       else
19225         {
19226           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19227           section_name = ".debug_macinfo.dwo";
19228         }
19229     }
19230   else
19231     {
19232       if (section_is_gnu)
19233         {
19234           section = &dwarf2_per_objfile->macro;
19235           section_name = ".debug_macro";
19236         }
19237       else
19238         {
19239           section = &dwarf2_per_objfile->macinfo;
19240           section_name = ".debug_macinfo";
19241         }
19242     }
19243
19244   dwarf2_read_section (objfile, section);
19245   if (section->buffer == NULL)
19246     {
19247       complaint (&symfile_complaints, _("missing %s section"), section_name);
19248       return;
19249     }
19250   abfd = section->asection->owner;
19251
19252   /* First pass: Find the name of the base filename.
19253      This filename is needed in order to process all macros whose definition
19254      (or undefinition) comes from the command line.  These macros are defined
19255      before the first DW_MACINFO_start_file entry, and yet still need to be
19256      associated to the base file.
19257
19258      To determine the base file name, we scan the macro definitions until we
19259      reach the first DW_MACINFO_start_file entry.  We then initialize
19260      CURRENT_FILE accordingly so that any macro definition found before the
19261      first DW_MACINFO_start_file can still be associated to the base file.  */
19262
19263   mac_ptr = section->buffer + offset;
19264   mac_end = section->buffer + section->size;
19265
19266   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19267                                       &offset_size, section_is_gnu);
19268   if (mac_ptr == NULL)
19269     {
19270       /* We already issued a complaint.  */
19271       return;
19272     }
19273
19274   do
19275     {
19276       /* Do we at least have room for a macinfo type byte?  */
19277       if (mac_ptr >= mac_end)
19278         {
19279           /* Complaint is printed during the second pass as GDB will probably
19280              stop the first pass earlier upon finding
19281              DW_MACINFO_start_file.  */
19282           break;
19283         }
19284
19285       macinfo_type = read_1_byte (abfd, mac_ptr);
19286       mac_ptr++;
19287
19288       /* Note that we rely on the fact that the corresponding GNU and
19289          DWARF constants are the same.  */
19290       switch (macinfo_type)
19291         {
19292           /* A zero macinfo type indicates the end of the macro
19293              information.  */
19294         case 0:
19295           break;
19296
19297         case DW_MACRO_GNU_define:
19298         case DW_MACRO_GNU_undef:
19299           /* Only skip the data by MAC_PTR.  */
19300           {
19301             unsigned int bytes_read;
19302
19303             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19304             mac_ptr += bytes_read;
19305             read_direct_string (abfd, mac_ptr, &bytes_read);
19306             mac_ptr += bytes_read;
19307           }
19308           break;
19309
19310         case DW_MACRO_GNU_start_file:
19311           {
19312             unsigned int bytes_read;
19313             int line, file;
19314
19315             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19316             mac_ptr += bytes_read;
19317             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19318             mac_ptr += bytes_read;
19319
19320             current_file = macro_start_file (file, line, current_file,
19321                                              comp_dir, lh, objfile);
19322           }
19323           break;
19324
19325         case DW_MACRO_GNU_end_file:
19326           /* No data to skip by MAC_PTR.  */
19327           break;
19328
19329         case DW_MACRO_GNU_define_indirect:
19330         case DW_MACRO_GNU_undef_indirect:
19331         case DW_MACRO_GNU_define_indirect_alt:
19332         case DW_MACRO_GNU_undef_indirect_alt:
19333           {
19334             unsigned int bytes_read;
19335
19336             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19337             mac_ptr += bytes_read;
19338             mac_ptr += offset_size;
19339           }
19340           break;
19341
19342         case DW_MACRO_GNU_transparent_include:
19343         case DW_MACRO_GNU_transparent_include_alt:
19344           /* Note that, according to the spec, a transparent include
19345              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19346              skip this opcode.  */
19347           mac_ptr += offset_size;
19348           break;
19349
19350         case DW_MACINFO_vendor_ext:
19351           /* Only skip the data by MAC_PTR.  */
19352           if (!section_is_gnu)
19353             {
19354               unsigned int bytes_read;
19355
19356               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19357               mac_ptr += bytes_read;
19358               read_direct_string (abfd, mac_ptr, &bytes_read);
19359               mac_ptr += bytes_read;
19360             }
19361           /* FALLTHROUGH */
19362
19363         default:
19364           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19365                                          mac_ptr, mac_end, abfd, offset_size,
19366                                          section);
19367           if (mac_ptr == NULL)
19368             return;
19369           break;
19370         }
19371     } while (macinfo_type != 0 && current_file == NULL);
19372
19373   /* Second pass: Process all entries.
19374
19375      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19376      command-line macro definitions/undefinitions.  This flag is unset when we
19377      reach the first DW_MACINFO_start_file entry.  */
19378
19379   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19380                                     NULL, xcalloc, xfree);
19381   cleanup = make_cleanup_htab_delete (include_hash);
19382   mac_ptr = section->buffer + offset;
19383   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19384   *slot = (void *) mac_ptr;
19385   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19386                             current_file, lh, comp_dir, section,
19387                             section_is_gnu, 0,
19388                             offset_size, objfile, include_hash);
19389   do_cleanups (cleanup);
19390 }
19391
19392 /* Check if the attribute's form is a DW_FORM_block*
19393    if so return true else false.  */
19394
19395 static int
19396 attr_form_is_block (struct attribute *attr)
19397 {
19398   return (attr == NULL ? 0 :
19399       attr->form == DW_FORM_block1
19400       || attr->form == DW_FORM_block2
19401       || attr->form == DW_FORM_block4
19402       || attr->form == DW_FORM_block
19403       || attr->form == DW_FORM_exprloc);
19404 }
19405
19406 /* Return non-zero if ATTR's value is a section offset --- classes
19407    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19408    You may use DW_UNSND (attr) to retrieve such offsets.
19409
19410    Section 7.5.4, "Attribute Encodings", explains that no attribute
19411    may have a value that belongs to more than one of these classes; it
19412    would be ambiguous if we did, because we use the same forms for all
19413    of them.  */
19414
19415 static int
19416 attr_form_is_section_offset (struct attribute *attr)
19417 {
19418   return (attr->form == DW_FORM_data4
19419           || attr->form == DW_FORM_data8
19420           || attr->form == DW_FORM_sec_offset);
19421 }
19422
19423 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19424    zero otherwise.  When this function returns true, you can apply
19425    dwarf2_get_attr_constant_value to it.
19426
19427    However, note that for some attributes you must check
19428    attr_form_is_section_offset before using this test.  DW_FORM_data4
19429    and DW_FORM_data8 are members of both the constant class, and of
19430    the classes that contain offsets into other debug sections
19431    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19432    that, if an attribute's can be either a constant or one of the
19433    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19434    taken as section offsets, not constants.  */
19435
19436 static int
19437 attr_form_is_constant (struct attribute *attr)
19438 {
19439   switch (attr->form)
19440     {
19441     case DW_FORM_sdata:
19442     case DW_FORM_udata:
19443     case DW_FORM_data1:
19444     case DW_FORM_data2:
19445     case DW_FORM_data4:
19446     case DW_FORM_data8:
19447       return 1;
19448     default:
19449       return 0;
19450     }
19451 }
19452
19453 /* Return the .debug_loc section to use for CU.
19454    For DWO files use .debug_loc.dwo.  */
19455
19456 static struct dwarf2_section_info *
19457 cu_debug_loc_section (struct dwarf2_cu *cu)
19458 {
19459   if (cu->dwo_unit)
19460     return &cu->dwo_unit->dwo_file->sections.loc;
19461   return &dwarf2_per_objfile->loc;
19462 }
19463
19464 /* A helper function that fills in a dwarf2_loclist_baton.  */
19465
19466 static void
19467 fill_in_loclist_baton (struct dwarf2_cu *cu,
19468                        struct dwarf2_loclist_baton *baton,
19469                        struct attribute *attr)
19470 {
19471   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19472
19473   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19474
19475   baton->per_cu = cu->per_cu;
19476   gdb_assert (baton->per_cu);
19477   /* We don't know how long the location list is, but make sure we
19478      don't run off the edge of the section.  */
19479   baton->size = section->size - DW_UNSND (attr);
19480   baton->data = section->buffer + DW_UNSND (attr);
19481   baton->base_address = cu->base_address;
19482   baton->from_dwo = cu->dwo_unit != NULL;
19483 }
19484
19485 static void
19486 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19487                              struct dwarf2_cu *cu, int is_block)
19488 {
19489   struct objfile *objfile = dwarf2_per_objfile->objfile;
19490   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19491
19492   if (attr_form_is_section_offset (attr)
19493       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19494          the section.  If so, fall through to the complaint in the
19495          other branch.  */
19496       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19497     {
19498       struct dwarf2_loclist_baton *baton;
19499
19500       baton = obstack_alloc (&objfile->objfile_obstack,
19501                              sizeof (struct dwarf2_loclist_baton));
19502
19503       fill_in_loclist_baton (cu, baton, attr);
19504
19505       if (cu->base_known == 0)
19506         complaint (&symfile_complaints,
19507                    _("Location list used without "
19508                      "specifying the CU base address."));
19509
19510       SYMBOL_ACLASS_INDEX (sym) = (is_block
19511                                    ? dwarf2_loclist_block_index
19512                                    : dwarf2_loclist_index);
19513       SYMBOL_LOCATION_BATON (sym) = baton;
19514     }
19515   else
19516     {
19517       struct dwarf2_locexpr_baton *baton;
19518
19519       baton = obstack_alloc (&objfile->objfile_obstack,
19520                              sizeof (struct dwarf2_locexpr_baton));
19521       baton->per_cu = cu->per_cu;
19522       gdb_assert (baton->per_cu);
19523
19524       if (attr_form_is_block (attr))
19525         {
19526           /* Note that we're just copying the block's data pointer
19527              here, not the actual data.  We're still pointing into the
19528              info_buffer for SYM's objfile; right now we never release
19529              that buffer, but when we do clean up properly this may
19530              need to change.  */
19531           baton->size = DW_BLOCK (attr)->size;
19532           baton->data = DW_BLOCK (attr)->data;
19533         }
19534       else
19535         {
19536           dwarf2_invalid_attrib_class_complaint ("location description",
19537                                                  SYMBOL_NATURAL_NAME (sym));
19538           baton->size = 0;
19539         }
19540
19541       SYMBOL_ACLASS_INDEX (sym) = (is_block
19542                                    ? dwarf2_locexpr_block_index
19543                                    : dwarf2_locexpr_index);
19544       SYMBOL_LOCATION_BATON (sym) = baton;
19545     }
19546 }
19547
19548 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19549    came from a separate debuginfo file, then the master objfile is
19550    returned.  */
19551
19552 struct objfile *
19553 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19554 {
19555   struct objfile *objfile = per_cu->objfile;
19556
19557   /* Return the master objfile, so that we can report and look up the
19558      correct file containing this variable.  */
19559   if (objfile->separate_debug_objfile_backlink)
19560     objfile = objfile->separate_debug_objfile_backlink;
19561
19562   return objfile;
19563 }
19564
19565 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19566    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19567    CU_HEADERP first.  */
19568
19569 static const struct comp_unit_head *
19570 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19571                        struct dwarf2_per_cu_data *per_cu)
19572 {
19573   const gdb_byte *info_ptr;
19574
19575   if (per_cu->cu)
19576     return &per_cu->cu->header;
19577
19578   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19579
19580   memset (cu_headerp, 0, sizeof (*cu_headerp));
19581   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19582
19583   return cu_headerp;
19584 }
19585
19586 /* Return the address size given in the compilation unit header for CU.  */
19587
19588 int
19589 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19590 {
19591   struct comp_unit_head cu_header_local;
19592   const struct comp_unit_head *cu_headerp;
19593
19594   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19595
19596   return cu_headerp->addr_size;
19597 }
19598
19599 /* Return the offset size given in the compilation unit header for CU.  */
19600
19601 int
19602 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19603 {
19604   struct comp_unit_head cu_header_local;
19605   const struct comp_unit_head *cu_headerp;
19606
19607   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19608
19609   return cu_headerp->offset_size;
19610 }
19611
19612 /* See its dwarf2loc.h declaration.  */
19613
19614 int
19615 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19616 {
19617   struct comp_unit_head cu_header_local;
19618   const struct comp_unit_head *cu_headerp;
19619
19620   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19621
19622   if (cu_headerp->version == 2)
19623     return cu_headerp->addr_size;
19624   else
19625     return cu_headerp->offset_size;
19626 }
19627
19628 /* Return the text offset of the CU.  The returned offset comes from
19629    this CU's objfile.  If this objfile came from a separate debuginfo
19630    file, then the offset may be different from the corresponding
19631    offset in the parent objfile.  */
19632
19633 CORE_ADDR
19634 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19635 {
19636   struct objfile *objfile = per_cu->objfile;
19637
19638   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19639 }
19640
19641 /* Locate the .debug_info compilation unit from CU's objfile which contains
19642    the DIE at OFFSET.  Raises an error on failure.  */
19643
19644 static struct dwarf2_per_cu_data *
19645 dwarf2_find_containing_comp_unit (sect_offset offset,
19646                                   unsigned int offset_in_dwz,
19647                                   struct objfile *objfile)
19648 {
19649   struct dwarf2_per_cu_data *this_cu;
19650   int low, high;
19651   const sect_offset *cu_off;
19652
19653   low = 0;
19654   high = dwarf2_per_objfile->n_comp_units - 1;
19655   while (high > low)
19656     {
19657       struct dwarf2_per_cu_data *mid_cu;
19658       int mid = low + (high - low) / 2;
19659
19660       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19661       cu_off = &mid_cu->offset;
19662       if (mid_cu->is_dwz > offset_in_dwz
19663           || (mid_cu->is_dwz == offset_in_dwz
19664               && cu_off->sect_off >= offset.sect_off))
19665         high = mid;
19666       else
19667         low = mid + 1;
19668     }
19669   gdb_assert (low == high);
19670   this_cu = dwarf2_per_objfile->all_comp_units[low];
19671   cu_off = &this_cu->offset;
19672   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19673     {
19674       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19675         error (_("Dwarf Error: could not find partial DIE containing "
19676                "offset 0x%lx [in module %s]"),
19677                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19678
19679       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19680                   <= offset.sect_off);
19681       return dwarf2_per_objfile->all_comp_units[low-1];
19682     }
19683   else
19684     {
19685       this_cu = dwarf2_per_objfile->all_comp_units[low];
19686       if (low == dwarf2_per_objfile->n_comp_units - 1
19687           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19688         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19689       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19690       return this_cu;
19691     }
19692 }
19693
19694 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19695
19696 static void
19697 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19698 {
19699   memset (cu, 0, sizeof (*cu));
19700   per_cu->cu = cu;
19701   cu->per_cu = per_cu;
19702   cu->objfile = per_cu->objfile;
19703   obstack_init (&cu->comp_unit_obstack);
19704 }
19705
19706 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19707
19708 static void
19709 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19710                        enum language pretend_language)
19711 {
19712   struct attribute *attr;
19713
19714   /* Set the language we're debugging.  */
19715   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19716   if (attr)
19717     set_cu_language (DW_UNSND (attr), cu);
19718   else
19719     {
19720       cu->language = pretend_language;
19721       cu->language_defn = language_def (cu->language);
19722     }
19723
19724   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19725   if (attr)
19726     cu->producer = DW_STRING (attr);
19727 }
19728
19729 /* Release one cached compilation unit, CU.  We unlink it from the tree
19730    of compilation units, but we don't remove it from the read_in_chain;
19731    the caller is responsible for that.
19732    NOTE: DATA is a void * because this function is also used as a
19733    cleanup routine.  */
19734
19735 static void
19736 free_heap_comp_unit (void *data)
19737 {
19738   struct dwarf2_cu *cu = data;
19739
19740   gdb_assert (cu->per_cu != NULL);
19741   cu->per_cu->cu = NULL;
19742   cu->per_cu = NULL;
19743
19744   obstack_free (&cu->comp_unit_obstack, NULL);
19745
19746   xfree (cu);
19747 }
19748
19749 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19750    when we're finished with it.  We can't free the pointer itself, but be
19751    sure to unlink it from the cache.  Also release any associated storage.  */
19752
19753 static void
19754 free_stack_comp_unit (void *data)
19755 {
19756   struct dwarf2_cu *cu = data;
19757
19758   gdb_assert (cu->per_cu != NULL);
19759   cu->per_cu->cu = NULL;
19760   cu->per_cu = NULL;
19761
19762   obstack_free (&cu->comp_unit_obstack, NULL);
19763   cu->partial_dies = NULL;
19764 }
19765
19766 /* Free all cached compilation units.  */
19767
19768 static void
19769 free_cached_comp_units (void *data)
19770 {
19771   struct dwarf2_per_cu_data *per_cu, **last_chain;
19772
19773   per_cu = dwarf2_per_objfile->read_in_chain;
19774   last_chain = &dwarf2_per_objfile->read_in_chain;
19775   while (per_cu != NULL)
19776     {
19777       struct dwarf2_per_cu_data *next_cu;
19778
19779       next_cu = per_cu->cu->read_in_chain;
19780
19781       free_heap_comp_unit (per_cu->cu);
19782       *last_chain = next_cu;
19783
19784       per_cu = next_cu;
19785     }
19786 }
19787
19788 /* Increase the age counter on each cached compilation unit, and free
19789    any that are too old.  */
19790
19791 static void
19792 age_cached_comp_units (void)
19793 {
19794   struct dwarf2_per_cu_data *per_cu, **last_chain;
19795
19796   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19797   per_cu = dwarf2_per_objfile->read_in_chain;
19798   while (per_cu != NULL)
19799     {
19800       per_cu->cu->last_used ++;
19801       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19802         dwarf2_mark (per_cu->cu);
19803       per_cu = per_cu->cu->read_in_chain;
19804     }
19805
19806   per_cu = dwarf2_per_objfile->read_in_chain;
19807   last_chain = &dwarf2_per_objfile->read_in_chain;
19808   while (per_cu != NULL)
19809     {
19810       struct dwarf2_per_cu_data *next_cu;
19811
19812       next_cu = per_cu->cu->read_in_chain;
19813
19814       if (!per_cu->cu->mark)
19815         {
19816           free_heap_comp_unit (per_cu->cu);
19817           *last_chain = next_cu;
19818         }
19819       else
19820         last_chain = &per_cu->cu->read_in_chain;
19821
19822       per_cu = next_cu;
19823     }
19824 }
19825
19826 /* Remove a single compilation unit from the cache.  */
19827
19828 static void
19829 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19830 {
19831   struct dwarf2_per_cu_data *per_cu, **last_chain;
19832
19833   per_cu = dwarf2_per_objfile->read_in_chain;
19834   last_chain = &dwarf2_per_objfile->read_in_chain;
19835   while (per_cu != NULL)
19836     {
19837       struct dwarf2_per_cu_data *next_cu;
19838
19839       next_cu = per_cu->cu->read_in_chain;
19840
19841       if (per_cu == target_per_cu)
19842         {
19843           free_heap_comp_unit (per_cu->cu);
19844           per_cu->cu = NULL;
19845           *last_chain = next_cu;
19846           break;
19847         }
19848       else
19849         last_chain = &per_cu->cu->read_in_chain;
19850
19851       per_cu = next_cu;
19852     }
19853 }
19854
19855 /* Release all extra memory associated with OBJFILE.  */
19856
19857 void
19858 dwarf2_free_objfile (struct objfile *objfile)
19859 {
19860   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19861
19862   if (dwarf2_per_objfile == NULL)
19863     return;
19864
19865   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19866   free_cached_comp_units (NULL);
19867
19868   if (dwarf2_per_objfile->quick_file_names_table)
19869     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19870
19871   /* Everything else should be on the objfile obstack.  */
19872 }
19873
19874 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19875    We store these in a hash table separate from the DIEs, and preserve them
19876    when the DIEs are flushed out of cache.
19877
19878    The CU "per_cu" pointer is needed because offset alone is not enough to
19879    uniquely identify the type.  A file may have multiple .debug_types sections,
19880    or the type may come from a DWO file.  Furthermore, while it's more logical
19881    to use per_cu->section+offset, with Fission the section with the data is in
19882    the DWO file but we don't know that section at the point we need it.
19883    We have to use something in dwarf2_per_cu_data (or the pointer to it)
19884    because we can enter the lookup routine, get_die_type_at_offset, from
19885    outside this file, and thus won't necessarily have PER_CU->cu.
19886    Fortunately, PER_CU is stable for the life of the objfile.  */
19887
19888 struct dwarf2_per_cu_offset_and_type
19889 {
19890   const struct dwarf2_per_cu_data *per_cu;
19891   sect_offset offset;
19892   struct type *type;
19893 };
19894
19895 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19896
19897 static hashval_t
19898 per_cu_offset_and_type_hash (const void *item)
19899 {
19900   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19901
19902   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19903 }
19904
19905 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19906
19907 static int
19908 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19909 {
19910   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19911   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19912
19913   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19914           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19915 }
19916
19917 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19918    table if necessary.  For convenience, return TYPE.
19919
19920    The DIEs reading must have careful ordering to:
19921     * Not cause infite loops trying to read in DIEs as a prerequisite for
19922       reading current DIE.
19923     * Not trying to dereference contents of still incompletely read in types
19924       while reading in other DIEs.
19925     * Enable referencing still incompletely read in types just by a pointer to
19926       the type without accessing its fields.
19927
19928    Therefore caller should follow these rules:
19929      * Try to fetch any prerequisite types we may need to build this DIE type
19930        before building the type and calling set_die_type.
19931      * After building type call set_die_type for current DIE as soon as
19932        possible before fetching more types to complete the current type.
19933      * Make the type as complete as possible before fetching more types.  */
19934
19935 static struct type *
19936 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19937 {
19938   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19939   struct objfile *objfile = cu->objfile;
19940
19941   /* For Ada types, make sure that the gnat-specific data is always
19942      initialized (if not already set).  There are a few types where
19943      we should not be doing so, because the type-specific area is
19944      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19945      where the type-specific area is used to store the floatformat).
19946      But this is not a problem, because the gnat-specific information
19947      is actually not needed for these types.  */
19948   if (need_gnat_info (cu)
19949       && TYPE_CODE (type) != TYPE_CODE_FUNC
19950       && TYPE_CODE (type) != TYPE_CODE_FLT
19951       && !HAVE_GNAT_AUX_INFO (type))
19952     INIT_GNAT_SPECIFIC (type);
19953
19954   if (dwarf2_per_objfile->die_type_hash == NULL)
19955     {
19956       dwarf2_per_objfile->die_type_hash =
19957         htab_create_alloc_ex (127,
19958                               per_cu_offset_and_type_hash,
19959                               per_cu_offset_and_type_eq,
19960                               NULL,
19961                               &objfile->objfile_obstack,
19962                               hashtab_obstack_allocate,
19963                               dummy_obstack_deallocate);
19964     }
19965
19966   ofs.per_cu = cu->per_cu;
19967   ofs.offset = die->offset;
19968   ofs.type = type;
19969   slot = (struct dwarf2_per_cu_offset_and_type **)
19970     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19971   if (*slot)
19972     complaint (&symfile_complaints,
19973                _("A problem internal to GDB: DIE 0x%x has type already set"),
19974                die->offset.sect_off);
19975   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19976   **slot = ofs;
19977   return type;
19978 }
19979
19980 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
19981    or return NULL if the die does not have a saved type.  */
19982
19983 static struct type *
19984 get_die_type_at_offset (sect_offset offset,
19985                         struct dwarf2_per_cu_data *per_cu)
19986 {
19987   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19988
19989   if (dwarf2_per_objfile->die_type_hash == NULL)
19990     return NULL;
19991
19992   ofs.per_cu = per_cu;
19993   ofs.offset = offset;
19994   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19995   if (slot)
19996     return slot->type;
19997   else
19998     return NULL;
19999 }
20000
20001 /* Look up the type for DIE in CU in die_type_hash,
20002    or return NULL if DIE does not have a saved type.  */
20003
20004 static struct type *
20005 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20006 {
20007   return get_die_type_at_offset (die->offset, cu->per_cu);
20008 }
20009
20010 /* Add a dependence relationship from CU to REF_PER_CU.  */
20011
20012 static void
20013 dwarf2_add_dependence (struct dwarf2_cu *cu,
20014                        struct dwarf2_per_cu_data *ref_per_cu)
20015 {
20016   void **slot;
20017
20018   if (cu->dependencies == NULL)
20019     cu->dependencies
20020       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20021                               NULL, &cu->comp_unit_obstack,
20022                               hashtab_obstack_allocate,
20023                               dummy_obstack_deallocate);
20024
20025   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20026   if (*slot == NULL)
20027     *slot = ref_per_cu;
20028 }
20029
20030 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20031    Set the mark field in every compilation unit in the
20032    cache that we must keep because we are keeping CU.  */
20033
20034 static int
20035 dwarf2_mark_helper (void **slot, void *data)
20036 {
20037   struct dwarf2_per_cu_data *per_cu;
20038
20039   per_cu = (struct dwarf2_per_cu_data *) *slot;
20040
20041   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20042      reading of the chain.  As such dependencies remain valid it is not much
20043      useful to track and undo them during QUIT cleanups.  */
20044   if (per_cu->cu == NULL)
20045     return 1;
20046
20047   if (per_cu->cu->mark)
20048     return 1;
20049   per_cu->cu->mark = 1;
20050
20051   if (per_cu->cu->dependencies != NULL)
20052     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20053
20054   return 1;
20055 }
20056
20057 /* Set the mark field in CU and in every other compilation unit in the
20058    cache that we must keep because we are keeping CU.  */
20059
20060 static void
20061 dwarf2_mark (struct dwarf2_cu *cu)
20062 {
20063   if (cu->mark)
20064     return;
20065   cu->mark = 1;
20066   if (cu->dependencies != NULL)
20067     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20068 }
20069
20070 static void
20071 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20072 {
20073   while (per_cu)
20074     {
20075       per_cu->cu->mark = 0;
20076       per_cu = per_cu->cu->read_in_chain;
20077     }
20078 }
20079
20080 /* Trivial hash function for partial_die_info: the hash value of a DIE
20081    is its offset in .debug_info for this objfile.  */
20082
20083 static hashval_t
20084 partial_die_hash (const void *item)
20085 {
20086   const struct partial_die_info *part_die = item;
20087
20088   return part_die->offset.sect_off;
20089 }
20090
20091 /* Trivial comparison function for partial_die_info structures: two DIEs
20092    are equal if they have the same offset.  */
20093
20094 static int
20095 partial_die_eq (const void *item_lhs, const void *item_rhs)
20096 {
20097   const struct partial_die_info *part_die_lhs = item_lhs;
20098   const struct partial_die_info *part_die_rhs = item_rhs;
20099
20100   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20101 }
20102
20103 static struct cmd_list_element *set_dwarf2_cmdlist;
20104 static struct cmd_list_element *show_dwarf2_cmdlist;
20105
20106 static void
20107 set_dwarf2_cmd (char *args, int from_tty)
20108 {
20109   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20110 }
20111
20112 static void
20113 show_dwarf2_cmd (char *args, int from_tty)
20114 {
20115   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20116 }
20117
20118 /* Free data associated with OBJFILE, if necessary.  */
20119
20120 static void
20121 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20122 {
20123   struct dwarf2_per_objfile *data = d;
20124   int ix;
20125
20126   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
20127     VEC_free (dwarf2_per_cu_ptr,
20128               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
20129
20130   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
20131     VEC_free (dwarf2_per_cu_ptr,
20132               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
20133
20134   VEC_free (dwarf2_section_info_def, data->types);
20135
20136   if (data->dwo_files)
20137     free_dwo_files (data->dwo_files, objfile);
20138   if (data->dwp_file)
20139     gdb_bfd_unref (data->dwp_file->dbfd);
20140
20141   if (data->dwz_file && data->dwz_file->dwz_bfd)
20142     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20143 }
20144
20145 \f
20146 /* The "save gdb-index" command.  */
20147
20148 /* The contents of the hash table we create when building the string
20149    table.  */
20150 struct strtab_entry
20151 {
20152   offset_type offset;
20153   const char *str;
20154 };
20155
20156 /* Hash function for a strtab_entry.
20157
20158    Function is used only during write_hash_table so no index format backward
20159    compatibility is needed.  */
20160
20161 static hashval_t
20162 hash_strtab_entry (const void *e)
20163 {
20164   const struct strtab_entry *entry = e;
20165   return mapped_index_string_hash (INT_MAX, entry->str);
20166 }
20167
20168 /* Equality function for a strtab_entry.  */
20169
20170 static int
20171 eq_strtab_entry (const void *a, const void *b)
20172 {
20173   const struct strtab_entry *ea = a;
20174   const struct strtab_entry *eb = b;
20175   return !strcmp (ea->str, eb->str);
20176 }
20177
20178 /* Create a strtab_entry hash table.  */
20179
20180 static htab_t
20181 create_strtab (void)
20182 {
20183   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20184                             xfree, xcalloc, xfree);
20185 }
20186
20187 /* Add a string to the constant pool.  Return the string's offset in
20188    host order.  */
20189
20190 static offset_type
20191 add_string (htab_t table, struct obstack *cpool, const char *str)
20192 {
20193   void **slot;
20194   struct strtab_entry entry;
20195   struct strtab_entry *result;
20196
20197   entry.str = str;
20198   slot = htab_find_slot (table, &entry, INSERT);
20199   if (*slot)
20200     result = *slot;
20201   else
20202     {
20203       result = XNEW (struct strtab_entry);
20204       result->offset = obstack_object_size (cpool);
20205       result->str = str;
20206       obstack_grow_str0 (cpool, str);
20207       *slot = result;
20208     }
20209   return result->offset;
20210 }
20211
20212 /* An entry in the symbol table.  */
20213 struct symtab_index_entry
20214 {
20215   /* The name of the symbol.  */
20216   const char *name;
20217   /* The offset of the name in the constant pool.  */
20218   offset_type index_offset;
20219   /* A sorted vector of the indices of all the CUs that hold an object
20220      of this name.  */
20221   VEC (offset_type) *cu_indices;
20222 };
20223
20224 /* The symbol table.  This is a power-of-2-sized hash table.  */
20225 struct mapped_symtab
20226 {
20227   offset_type n_elements;
20228   offset_type size;
20229   struct symtab_index_entry **data;
20230 };
20231
20232 /* Hash function for a symtab_index_entry.  */
20233
20234 static hashval_t
20235 hash_symtab_entry (const void *e)
20236 {
20237   const struct symtab_index_entry *entry = e;
20238   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20239                          sizeof (offset_type) * VEC_length (offset_type,
20240                                                             entry->cu_indices),
20241                          0);
20242 }
20243
20244 /* Equality function for a symtab_index_entry.  */
20245
20246 static int
20247 eq_symtab_entry (const void *a, const void *b)
20248 {
20249   const struct symtab_index_entry *ea = a;
20250   const struct symtab_index_entry *eb = b;
20251   int len = VEC_length (offset_type, ea->cu_indices);
20252   if (len != VEC_length (offset_type, eb->cu_indices))
20253     return 0;
20254   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20255                   VEC_address (offset_type, eb->cu_indices),
20256                   sizeof (offset_type) * len);
20257 }
20258
20259 /* Destroy a symtab_index_entry.  */
20260
20261 static void
20262 delete_symtab_entry (void *p)
20263 {
20264   struct symtab_index_entry *entry = p;
20265   VEC_free (offset_type, entry->cu_indices);
20266   xfree (entry);
20267 }
20268
20269 /* Create a hash table holding symtab_index_entry objects.  */
20270
20271 static htab_t
20272 create_symbol_hash_table (void)
20273 {
20274   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20275                             delete_symtab_entry, xcalloc, xfree);
20276 }
20277
20278 /* Create a new mapped symtab object.  */
20279
20280 static struct mapped_symtab *
20281 create_mapped_symtab (void)
20282 {
20283   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20284   symtab->n_elements = 0;
20285   symtab->size = 1024;
20286   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20287   return symtab;
20288 }
20289
20290 /* Destroy a mapped_symtab.  */
20291
20292 static void
20293 cleanup_mapped_symtab (void *p)
20294 {
20295   struct mapped_symtab *symtab = p;
20296   /* The contents of the array are freed when the other hash table is
20297      destroyed.  */
20298   xfree (symtab->data);
20299   xfree (symtab);
20300 }
20301
20302 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20303    the slot.
20304    
20305    Function is used only during write_hash_table so no index format backward
20306    compatibility is needed.  */
20307
20308 static struct symtab_index_entry **
20309 find_slot (struct mapped_symtab *symtab, const char *name)
20310 {
20311   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20312
20313   index = hash & (symtab->size - 1);
20314   step = ((hash * 17) & (symtab->size - 1)) | 1;
20315
20316   for (;;)
20317     {
20318       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20319         return &symtab->data[index];
20320       index = (index + step) & (symtab->size - 1);
20321     }
20322 }
20323
20324 /* Expand SYMTAB's hash table.  */
20325
20326 static void
20327 hash_expand (struct mapped_symtab *symtab)
20328 {
20329   offset_type old_size = symtab->size;
20330   offset_type i;
20331   struct symtab_index_entry **old_entries = symtab->data;
20332
20333   symtab->size *= 2;
20334   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20335
20336   for (i = 0; i < old_size; ++i)
20337     {
20338       if (old_entries[i])
20339         {
20340           struct symtab_index_entry **slot = find_slot (symtab,
20341                                                         old_entries[i]->name);
20342           *slot = old_entries[i];
20343         }
20344     }
20345
20346   xfree (old_entries);
20347 }
20348
20349 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20350    CU_INDEX is the index of the CU in which the symbol appears.
20351    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20352
20353 static void
20354 add_index_entry (struct mapped_symtab *symtab, const char *name,
20355                  int is_static, gdb_index_symbol_kind kind,
20356                  offset_type cu_index)
20357 {
20358   struct symtab_index_entry **slot;
20359   offset_type cu_index_and_attrs;
20360
20361   ++symtab->n_elements;
20362   if (4 * symtab->n_elements / 3 >= symtab->size)
20363     hash_expand (symtab);
20364
20365   slot = find_slot (symtab, name);
20366   if (!*slot)
20367     {
20368       *slot = XNEW (struct symtab_index_entry);
20369       (*slot)->name = name;
20370       /* index_offset is set later.  */
20371       (*slot)->cu_indices = NULL;
20372     }
20373
20374   cu_index_and_attrs = 0;
20375   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20376   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20377   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20378
20379   /* We don't want to record an index value twice as we want to avoid the
20380      duplication.
20381      We process all global symbols and then all static symbols
20382      (which would allow us to avoid the duplication by only having to check
20383      the last entry pushed), but a symbol could have multiple kinds in one CU.
20384      To keep things simple we don't worry about the duplication here and
20385      sort and uniqufy the list after we've processed all symbols.  */
20386   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20387 }
20388
20389 /* qsort helper routine for uniquify_cu_indices.  */
20390
20391 static int
20392 offset_type_compare (const void *ap, const void *bp)
20393 {
20394   offset_type a = *(offset_type *) ap;
20395   offset_type b = *(offset_type *) bp;
20396
20397   return (a > b) - (b > a);
20398 }
20399
20400 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20401
20402 static void
20403 uniquify_cu_indices (struct mapped_symtab *symtab)
20404 {
20405   int i;
20406
20407   for (i = 0; i < symtab->size; ++i)
20408     {
20409       struct symtab_index_entry *entry = symtab->data[i];
20410
20411       if (entry
20412           && entry->cu_indices != NULL)
20413         {
20414           unsigned int next_to_insert, next_to_check;
20415           offset_type last_value;
20416
20417           qsort (VEC_address (offset_type, entry->cu_indices),
20418                  VEC_length (offset_type, entry->cu_indices),
20419                  sizeof (offset_type), offset_type_compare);
20420
20421           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20422           next_to_insert = 1;
20423           for (next_to_check = 1;
20424                next_to_check < VEC_length (offset_type, entry->cu_indices);
20425                ++next_to_check)
20426             {
20427               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20428                   != last_value)
20429                 {
20430                   last_value = VEC_index (offset_type, entry->cu_indices,
20431                                           next_to_check);
20432                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20433                                last_value);
20434                   ++next_to_insert;
20435                 }
20436             }
20437           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20438         }
20439     }
20440 }
20441
20442 /* Add a vector of indices to the constant pool.  */
20443
20444 static offset_type
20445 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20446                       struct symtab_index_entry *entry)
20447 {
20448   void **slot;
20449
20450   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20451   if (!*slot)
20452     {
20453       offset_type len = VEC_length (offset_type, entry->cu_indices);
20454       offset_type val = MAYBE_SWAP (len);
20455       offset_type iter;
20456       int i;
20457
20458       *slot = entry;
20459       entry->index_offset = obstack_object_size (cpool);
20460
20461       obstack_grow (cpool, &val, sizeof (val));
20462       for (i = 0;
20463            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20464            ++i)
20465         {
20466           val = MAYBE_SWAP (iter);
20467           obstack_grow (cpool, &val, sizeof (val));
20468         }
20469     }
20470   else
20471     {
20472       struct symtab_index_entry *old_entry = *slot;
20473       entry->index_offset = old_entry->index_offset;
20474       entry = old_entry;
20475     }
20476   return entry->index_offset;
20477 }
20478
20479 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20480    constant pool entries going into the obstack CPOOL.  */
20481
20482 static void
20483 write_hash_table (struct mapped_symtab *symtab,
20484                   struct obstack *output, struct obstack *cpool)
20485 {
20486   offset_type i;
20487   htab_t symbol_hash_table;
20488   htab_t str_table;
20489
20490   symbol_hash_table = create_symbol_hash_table ();
20491   str_table = create_strtab ();
20492
20493   /* We add all the index vectors to the constant pool first, to
20494      ensure alignment is ok.  */
20495   for (i = 0; i < symtab->size; ++i)
20496     {
20497       if (symtab->data[i])
20498         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20499     }
20500
20501   /* Now write out the hash table.  */
20502   for (i = 0; i < symtab->size; ++i)
20503     {
20504       offset_type str_off, vec_off;
20505
20506       if (symtab->data[i])
20507         {
20508           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20509           vec_off = symtab->data[i]->index_offset;
20510         }
20511       else
20512         {
20513           /* While 0 is a valid constant pool index, it is not valid
20514              to have 0 for both offsets.  */
20515           str_off = 0;
20516           vec_off = 0;
20517         }
20518
20519       str_off = MAYBE_SWAP (str_off);
20520       vec_off = MAYBE_SWAP (vec_off);
20521
20522       obstack_grow (output, &str_off, sizeof (str_off));
20523       obstack_grow (output, &vec_off, sizeof (vec_off));
20524     }
20525
20526   htab_delete (str_table);
20527   htab_delete (symbol_hash_table);
20528 }
20529
20530 /* Struct to map psymtab to CU index in the index file.  */
20531 struct psymtab_cu_index_map
20532 {
20533   struct partial_symtab *psymtab;
20534   unsigned int cu_index;
20535 };
20536
20537 static hashval_t
20538 hash_psymtab_cu_index (const void *item)
20539 {
20540   const struct psymtab_cu_index_map *map = item;
20541
20542   return htab_hash_pointer (map->psymtab);
20543 }
20544
20545 static int
20546 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20547 {
20548   const struct psymtab_cu_index_map *lhs = item_lhs;
20549   const struct psymtab_cu_index_map *rhs = item_rhs;
20550
20551   return lhs->psymtab == rhs->psymtab;
20552 }
20553
20554 /* Helper struct for building the address table.  */
20555 struct addrmap_index_data
20556 {
20557   struct objfile *objfile;
20558   struct obstack *addr_obstack;
20559   htab_t cu_index_htab;
20560
20561   /* Non-zero if the previous_* fields are valid.
20562      We can't write an entry until we see the next entry (since it is only then
20563      that we know the end of the entry).  */
20564   int previous_valid;
20565   /* Index of the CU in the table of all CUs in the index file.  */
20566   unsigned int previous_cu_index;
20567   /* Start address of the CU.  */
20568   CORE_ADDR previous_cu_start;
20569 };
20570
20571 /* Write an address entry to OBSTACK.  */
20572
20573 static void
20574 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20575                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20576 {
20577   offset_type cu_index_to_write;
20578   gdb_byte addr[8];
20579   CORE_ADDR baseaddr;
20580
20581   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20582
20583   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20584   obstack_grow (obstack, addr, 8);
20585   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20586   obstack_grow (obstack, addr, 8);
20587   cu_index_to_write = MAYBE_SWAP (cu_index);
20588   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20589 }
20590
20591 /* Worker function for traversing an addrmap to build the address table.  */
20592
20593 static int
20594 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20595 {
20596   struct addrmap_index_data *data = datap;
20597   struct partial_symtab *pst = obj;
20598
20599   if (data->previous_valid)
20600     add_address_entry (data->objfile, data->addr_obstack,
20601                        data->previous_cu_start, start_addr,
20602                        data->previous_cu_index);
20603
20604   data->previous_cu_start = start_addr;
20605   if (pst != NULL)
20606     {
20607       struct psymtab_cu_index_map find_map, *map;
20608       find_map.psymtab = pst;
20609       map = htab_find (data->cu_index_htab, &find_map);
20610       gdb_assert (map != NULL);
20611       data->previous_cu_index = map->cu_index;
20612       data->previous_valid = 1;
20613     }
20614   else
20615       data->previous_valid = 0;
20616
20617   return 0;
20618 }
20619
20620 /* Write OBJFILE's address map to OBSTACK.
20621    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20622    in the index file.  */
20623
20624 static void
20625 write_address_map (struct objfile *objfile, struct obstack *obstack,
20626                    htab_t cu_index_htab)
20627 {
20628   struct addrmap_index_data addrmap_index_data;
20629
20630   /* When writing the address table, we have to cope with the fact that
20631      the addrmap iterator only provides the start of a region; we have to
20632      wait until the next invocation to get the start of the next region.  */
20633
20634   addrmap_index_data.objfile = objfile;
20635   addrmap_index_data.addr_obstack = obstack;
20636   addrmap_index_data.cu_index_htab = cu_index_htab;
20637   addrmap_index_data.previous_valid = 0;
20638
20639   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20640                    &addrmap_index_data);
20641
20642   /* It's highly unlikely the last entry (end address = 0xff...ff)
20643      is valid, but we should still handle it.
20644      The end address is recorded as the start of the next region, but that
20645      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20646      anyway.  */
20647   if (addrmap_index_data.previous_valid)
20648     add_address_entry (objfile, obstack,
20649                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20650                        addrmap_index_data.previous_cu_index);
20651 }
20652
20653 /* Return the symbol kind of PSYM.  */
20654
20655 static gdb_index_symbol_kind
20656 symbol_kind (struct partial_symbol *psym)
20657 {
20658   domain_enum domain = PSYMBOL_DOMAIN (psym);
20659   enum address_class aclass = PSYMBOL_CLASS (psym);
20660
20661   switch (domain)
20662     {
20663     case VAR_DOMAIN:
20664       switch (aclass)
20665         {
20666         case LOC_BLOCK:
20667           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20668         case LOC_TYPEDEF:
20669           return GDB_INDEX_SYMBOL_KIND_TYPE;
20670         case LOC_COMPUTED:
20671         case LOC_CONST_BYTES:
20672         case LOC_OPTIMIZED_OUT:
20673         case LOC_STATIC:
20674           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20675         case LOC_CONST:
20676           /* Note: It's currently impossible to recognize psyms as enum values
20677              short of reading the type info.  For now punt.  */
20678           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20679         default:
20680           /* There are other LOC_FOO values that one might want to classify
20681              as variables, but dwarf2read.c doesn't currently use them.  */
20682           return GDB_INDEX_SYMBOL_KIND_OTHER;
20683         }
20684     case STRUCT_DOMAIN:
20685       return GDB_INDEX_SYMBOL_KIND_TYPE;
20686     default:
20687       return GDB_INDEX_SYMBOL_KIND_OTHER;
20688     }
20689 }
20690
20691 /* Add a list of partial symbols to SYMTAB.  */
20692
20693 static void
20694 write_psymbols (struct mapped_symtab *symtab,
20695                 htab_t psyms_seen,
20696                 struct partial_symbol **psymp,
20697                 int count,
20698                 offset_type cu_index,
20699                 int is_static)
20700 {
20701   for (; count-- > 0; ++psymp)
20702     {
20703       struct partial_symbol *psym = *psymp;
20704       void **slot;
20705
20706       if (SYMBOL_LANGUAGE (psym) == language_ada)
20707         error (_("Ada is not currently supported by the index"));
20708
20709       /* Only add a given psymbol once.  */
20710       slot = htab_find_slot (psyms_seen, psym, INSERT);
20711       if (!*slot)
20712         {
20713           gdb_index_symbol_kind kind = symbol_kind (psym);
20714
20715           *slot = psym;
20716           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20717                            is_static, kind, cu_index);
20718         }
20719     }
20720 }
20721
20722 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20723    exception if there is an error.  */
20724
20725 static void
20726 write_obstack (FILE *file, struct obstack *obstack)
20727 {
20728   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20729               file)
20730       != obstack_object_size (obstack))
20731     error (_("couldn't data write to file"));
20732 }
20733
20734 /* Unlink a file if the argument is not NULL.  */
20735
20736 static void
20737 unlink_if_set (void *p)
20738 {
20739   char **filename = p;
20740   if (*filename)
20741     unlink (*filename);
20742 }
20743
20744 /* A helper struct used when iterating over debug_types.  */
20745 struct signatured_type_index_data
20746 {
20747   struct objfile *objfile;
20748   struct mapped_symtab *symtab;
20749   struct obstack *types_list;
20750   htab_t psyms_seen;
20751   int cu_index;
20752 };
20753
20754 /* A helper function that writes a single signatured_type to an
20755    obstack.  */
20756
20757 static int
20758 write_one_signatured_type (void **slot, void *d)
20759 {
20760   struct signatured_type_index_data *info = d;
20761   struct signatured_type *entry = (struct signatured_type *) *slot;
20762   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
20763   gdb_byte val[8];
20764
20765   write_psymbols (info->symtab,
20766                   info->psyms_seen,
20767                   info->objfile->global_psymbols.list
20768                   + psymtab->globals_offset,
20769                   psymtab->n_global_syms, info->cu_index,
20770                   0);
20771   write_psymbols (info->symtab,
20772                   info->psyms_seen,
20773                   info->objfile->static_psymbols.list
20774                   + psymtab->statics_offset,
20775                   psymtab->n_static_syms, info->cu_index,
20776                   1);
20777
20778   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20779                           entry->per_cu.offset.sect_off);
20780   obstack_grow (info->types_list, val, 8);
20781   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20782                           entry->type_offset_in_tu.cu_off);
20783   obstack_grow (info->types_list, val, 8);
20784   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20785   obstack_grow (info->types_list, val, 8);
20786
20787   ++info->cu_index;
20788
20789   return 1;
20790 }
20791
20792 /* Recurse into all "included" dependencies and write their symbols as
20793    if they appeared in this psymtab.  */
20794
20795 static void
20796 recursively_write_psymbols (struct objfile *objfile,
20797                             struct partial_symtab *psymtab,
20798                             struct mapped_symtab *symtab,
20799                             htab_t psyms_seen,
20800                             offset_type cu_index)
20801 {
20802   int i;
20803
20804   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20805     if (psymtab->dependencies[i]->user != NULL)
20806       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20807                                   symtab, psyms_seen, cu_index);
20808
20809   write_psymbols (symtab,
20810                   psyms_seen,
20811                   objfile->global_psymbols.list + psymtab->globals_offset,
20812                   psymtab->n_global_syms, cu_index,
20813                   0);
20814   write_psymbols (symtab,
20815                   psyms_seen,
20816                   objfile->static_psymbols.list + psymtab->statics_offset,
20817                   psymtab->n_static_syms, cu_index,
20818                   1);
20819 }
20820
20821 /* Create an index file for OBJFILE in the directory DIR.  */
20822
20823 static void
20824 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20825 {
20826   struct cleanup *cleanup;
20827   char *filename, *cleanup_filename;
20828   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20829   struct obstack cu_list, types_cu_list;
20830   int i;
20831   FILE *out_file;
20832   struct mapped_symtab *symtab;
20833   offset_type val, size_of_contents, total_len;
20834   struct stat st;
20835   htab_t psyms_seen;
20836   htab_t cu_index_htab;
20837   struct psymtab_cu_index_map *psymtab_cu_index_map;
20838
20839   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20840     return;
20841
20842   if (dwarf2_per_objfile->using_index)
20843     error (_("Cannot use an index to create the index"));
20844
20845   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20846     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20847
20848   if (stat (objfile->name, &st) < 0)
20849     perror_with_name (objfile->name);
20850
20851   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20852                      INDEX_SUFFIX, (char *) NULL);
20853   cleanup = make_cleanup (xfree, filename);
20854
20855   out_file = gdb_fopen_cloexec (filename, "wb");
20856   if (!out_file)
20857     error (_("Can't open `%s' for writing"), filename);
20858
20859   cleanup_filename = filename;
20860   make_cleanup (unlink_if_set, &cleanup_filename);
20861
20862   symtab = create_mapped_symtab ();
20863   make_cleanup (cleanup_mapped_symtab, symtab);
20864
20865   obstack_init (&addr_obstack);
20866   make_cleanup_obstack_free (&addr_obstack);
20867
20868   obstack_init (&cu_list);
20869   make_cleanup_obstack_free (&cu_list);
20870
20871   obstack_init (&types_cu_list);
20872   make_cleanup_obstack_free (&types_cu_list);
20873
20874   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20875                                   NULL, xcalloc, xfree);
20876   make_cleanup_htab_delete (psyms_seen);
20877
20878   /* While we're scanning CU's create a table that maps a psymtab pointer
20879      (which is what addrmap records) to its index (which is what is recorded
20880      in the index file).  This will later be needed to write the address
20881      table.  */
20882   cu_index_htab = htab_create_alloc (100,
20883                                      hash_psymtab_cu_index,
20884                                      eq_psymtab_cu_index,
20885                                      NULL, xcalloc, xfree);
20886   make_cleanup_htab_delete (cu_index_htab);
20887   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20888     xmalloc (sizeof (struct psymtab_cu_index_map)
20889              * dwarf2_per_objfile->n_comp_units);
20890   make_cleanup (xfree, psymtab_cu_index_map);
20891
20892   /* The CU list is already sorted, so we don't need to do additional
20893      work here.  Also, the debug_types entries do not appear in
20894      all_comp_units, but only in their own hash table.  */
20895   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20896     {
20897       struct dwarf2_per_cu_data *per_cu
20898         = dwarf2_per_objfile->all_comp_units[i];
20899       struct partial_symtab *psymtab = per_cu->v.psymtab;
20900       gdb_byte val[8];
20901       struct psymtab_cu_index_map *map;
20902       void **slot;
20903
20904       if (psymtab->user == NULL)
20905         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20906
20907       map = &psymtab_cu_index_map[i];
20908       map->psymtab = psymtab;
20909       map->cu_index = i;
20910       slot = htab_find_slot (cu_index_htab, map, INSERT);
20911       gdb_assert (slot != NULL);
20912       gdb_assert (*slot == NULL);
20913       *slot = map;
20914
20915       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20916                               per_cu->offset.sect_off);
20917       obstack_grow (&cu_list, val, 8);
20918       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20919       obstack_grow (&cu_list, val, 8);
20920     }
20921
20922   /* Dump the address map.  */
20923   write_address_map (objfile, &addr_obstack, cu_index_htab);
20924
20925   /* Write out the .debug_type entries, if any.  */
20926   if (dwarf2_per_objfile->signatured_types)
20927     {
20928       struct signatured_type_index_data sig_data;
20929
20930       sig_data.objfile = objfile;
20931       sig_data.symtab = symtab;
20932       sig_data.types_list = &types_cu_list;
20933       sig_data.psyms_seen = psyms_seen;
20934       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20935       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20936                               write_one_signatured_type, &sig_data);
20937     }
20938
20939   /* Now that we've processed all symbols we can shrink their cu_indices
20940      lists.  */
20941   uniquify_cu_indices (symtab);
20942
20943   obstack_init (&constant_pool);
20944   make_cleanup_obstack_free (&constant_pool);
20945   obstack_init (&symtab_obstack);
20946   make_cleanup_obstack_free (&symtab_obstack);
20947   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20948
20949   obstack_init (&contents);
20950   make_cleanup_obstack_free (&contents);
20951   size_of_contents = 6 * sizeof (offset_type);
20952   total_len = size_of_contents;
20953
20954   /* The version number.  */
20955   val = MAYBE_SWAP (8);
20956   obstack_grow (&contents, &val, sizeof (val));
20957
20958   /* The offset of the CU list from the start of the file.  */
20959   val = MAYBE_SWAP (total_len);
20960   obstack_grow (&contents, &val, sizeof (val));
20961   total_len += obstack_object_size (&cu_list);
20962
20963   /* The offset of the types CU list from the start of the file.  */
20964   val = MAYBE_SWAP (total_len);
20965   obstack_grow (&contents, &val, sizeof (val));
20966   total_len += obstack_object_size (&types_cu_list);
20967
20968   /* The offset of the address table from the start of the file.  */
20969   val = MAYBE_SWAP (total_len);
20970   obstack_grow (&contents, &val, sizeof (val));
20971   total_len += obstack_object_size (&addr_obstack);
20972
20973   /* The offset of the symbol table from the start of the file.  */
20974   val = MAYBE_SWAP (total_len);
20975   obstack_grow (&contents, &val, sizeof (val));
20976   total_len += obstack_object_size (&symtab_obstack);
20977
20978   /* The offset of the constant pool from the start of the file.  */
20979   val = MAYBE_SWAP (total_len);
20980   obstack_grow (&contents, &val, sizeof (val));
20981   total_len += obstack_object_size (&constant_pool);
20982
20983   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20984
20985   write_obstack (out_file, &contents);
20986   write_obstack (out_file, &cu_list);
20987   write_obstack (out_file, &types_cu_list);
20988   write_obstack (out_file, &addr_obstack);
20989   write_obstack (out_file, &symtab_obstack);
20990   write_obstack (out_file, &constant_pool);
20991
20992   fclose (out_file);
20993
20994   /* We want to keep the file, so we set cleanup_filename to NULL
20995      here.  See unlink_if_set.  */
20996   cleanup_filename = NULL;
20997
20998   do_cleanups (cleanup);
20999 }
21000
21001 /* Implementation of the `save gdb-index' command.
21002    
21003    Note that the file format used by this command is documented in the
21004    GDB manual.  Any changes here must be documented there.  */
21005
21006 static void
21007 save_gdb_index_command (char *arg, int from_tty)
21008 {
21009   struct objfile *objfile;
21010
21011   if (!arg || !*arg)
21012     error (_("usage: save gdb-index DIRECTORY"));
21013
21014   ALL_OBJFILES (objfile)
21015   {
21016     struct stat st;
21017
21018     /* If the objfile does not correspond to an actual file, skip it.  */
21019     if (stat (objfile->name, &st) < 0)
21020       continue;
21021
21022     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21023     if (dwarf2_per_objfile)
21024       {
21025         volatile struct gdb_exception except;
21026
21027         TRY_CATCH (except, RETURN_MASK_ERROR)
21028           {
21029             write_psymtabs_to_index (objfile, arg);
21030           }
21031         if (except.reason < 0)
21032           exception_fprintf (gdb_stderr, except,
21033                              _("Error while writing index for `%s': "),
21034                              objfile->name);
21035       }
21036   }
21037 }
21038
21039 \f
21040
21041 int dwarf2_always_disassemble;
21042
21043 static void
21044 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21045                                 struct cmd_list_element *c, const char *value)
21046 {
21047   fprintf_filtered (file,
21048                     _("Whether to always disassemble "
21049                       "DWARF expressions is %s.\n"),
21050                     value);
21051 }
21052
21053 static void
21054 show_check_physname (struct ui_file *file, int from_tty,
21055                      struct cmd_list_element *c, const char *value)
21056 {
21057   fprintf_filtered (file,
21058                     _("Whether to check \"physname\" is %s.\n"),
21059                     value);
21060 }
21061
21062 void _initialize_dwarf2_read (void);
21063
21064 void
21065 _initialize_dwarf2_read (void)
21066 {
21067   struct cmd_list_element *c;
21068
21069   dwarf2_objfile_data_key
21070     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21071
21072   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21073 Set DWARF 2 specific variables.\n\
21074 Configure DWARF 2 variables such as the cache size"),
21075                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21076                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21077
21078   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21079 Show DWARF 2 specific variables\n\
21080 Show DWARF 2 variables such as the cache size"),
21081                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21082                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21083
21084   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21085                             &dwarf2_max_cache_age, _("\
21086 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21087 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21088 A higher limit means that cached compilation units will be stored\n\
21089 in memory longer, and more total memory will be used.  Zero disables\n\
21090 caching, which can slow down startup."),
21091                             NULL,
21092                             show_dwarf2_max_cache_age,
21093                             &set_dwarf2_cmdlist,
21094                             &show_dwarf2_cmdlist);
21095
21096   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21097                            &dwarf2_always_disassemble, _("\
21098 Set whether `info address' always disassembles DWARF expressions."), _("\
21099 Show whether `info address' always disassembles DWARF expressions."), _("\
21100 When enabled, DWARF expressions are always printed in an assembly-like\n\
21101 syntax.  When disabled, expressions will be printed in a more\n\
21102 conversational style, when possible."),
21103                            NULL,
21104                            show_dwarf2_always_disassemble,
21105                            &set_dwarf2_cmdlist,
21106                            &show_dwarf2_cmdlist);
21107
21108   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21109 Set debugging of the dwarf2 reader."), _("\
21110 Show debugging of the dwarf2 reader."), _("\
21111 When enabled, debugging messages are printed during dwarf2 reading\n\
21112 and symtab expansion."),
21113                             NULL,
21114                             NULL,
21115                             &setdebuglist, &showdebuglist);
21116
21117   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21118 Set debugging of the dwarf2 DIE reader."), _("\
21119 Show debugging of the dwarf2 DIE reader."), _("\
21120 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21121 The value is the maximum depth to print."),
21122                              NULL,
21123                              NULL,
21124                              &setdebuglist, &showdebuglist);
21125
21126   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21127 Set cross-checking of \"physname\" code against demangler."), _("\
21128 Show cross-checking of \"physname\" code against demangler."), _("\
21129 When enabled, GDB's internal \"physname\" code is checked against\n\
21130 the demangler."),
21131                            NULL, show_check_physname,
21132                            &setdebuglist, &showdebuglist);
21133
21134   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21135                            no_class, &use_deprecated_index_sections, _("\
21136 Set whether to use deprecated gdb_index sections."), _("\
21137 Show whether to use deprecated gdb_index sections."), _("\
21138 When enabled, deprecated .gdb_index sections are used anyway.\n\
21139 Normally they are ignored either because of a missing feature or\n\
21140 performance issue.\n\
21141 Warning: This option must be enabled before gdb reads the file."),
21142                            NULL,
21143                            NULL,
21144                            &setlist, &showlist);
21145
21146   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21147                _("\
21148 Save a gdb-index file.\n\
21149 Usage: save gdb-index DIRECTORY"),
21150                &save_cmdlist);
21151   set_cmd_completer (c, filename_completer);
21152
21153   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21154                                                         &dwarf2_locexpr_funcs);
21155   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21156                                                         &dwarf2_loclist_funcs);
21157
21158   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21159                                         &dwarf2_block_frame_base_locexpr_funcs);
21160   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21161                                         &dwarf2_block_frame_base_loclist_funcs);
21162 }