PR c++/14998:
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70
71 #include <fcntl.h>
72 #include "gdb_string.h"
73 #include "gdb_assert.h"
74 #include <sys/types.h>
75
76 typedef struct symbol *symbolp;
77 DEF_VEC_P (symbolp);
78
79 /* When non-zero, print basic high level tracing messages.
80    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
81 static int dwarf2_read_debug = 0;
82
83 /* When non-zero, dump DIEs after they are read in.  */
84 static unsigned int dwarf2_die_debug = 0;
85
86 /* When non-zero, cross-check physname against demangler.  */
87 static int check_physname = 0;
88
89 /* When non-zero, do not reject deprecated .gdb_index sections.  */
90 static int use_deprecated_index_sections = 0;
91
92 static const struct objfile_data *dwarf2_objfile_data_key;
93
94 struct dwarf2_section_info
95 {
96   asection *asection;
97   gdb_byte *buffer;
98   bfd_size_type size;
99   /* True if we have tried to read this section.  */
100   int readin;
101 };
102
103 typedef struct dwarf2_section_info dwarf2_section_info_def;
104 DEF_VEC_O (dwarf2_section_info_def);
105
106 /* All offsets in the index are of this type.  It must be
107    architecture-independent.  */
108 typedef uint32_t offset_type;
109
110 DEF_VEC_I (offset_type);
111
112 /* Ensure only legit values are used.  */
113 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
114   do { \
115     gdb_assert ((unsigned int) (value) <= 1); \
116     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
117   } while (0)
118
119 /* Ensure only legit values are used.  */
120 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
121   do { \
122     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
123                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
124     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
125   } while (0)
126
127 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
128 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
129   do { \
130     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
131     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
132   } while (0)
133
134 /* A description of the mapped index.  The file format is described in
135    a comment by the code that writes the index.  */
136 struct mapped_index
137 {
138   /* Index data format version.  */
139   int version;
140
141   /* The total length of the buffer.  */
142   off_t total_size;
143
144   /* A pointer to the address table data.  */
145   const gdb_byte *address_table;
146
147   /* Size of the address table data in bytes.  */
148   offset_type address_table_size;
149
150   /* The symbol table, implemented as a hash table.  */
151   const offset_type *symbol_table;
152
153   /* Size in slots, each slot is 2 offset_types.  */
154   offset_type symbol_table_slots;
155
156   /* A pointer to the constant pool.  */
157   const char *constant_pool;
158 };
159
160 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
161 DEF_VEC_P (dwarf2_per_cu_ptr);
162
163 /* Collection of data recorded per objfile.
164    This hangs off of dwarf2_objfile_data_key.  */
165
166 struct dwarf2_per_objfile
167 {
168   struct dwarf2_section_info info;
169   struct dwarf2_section_info abbrev;
170   struct dwarf2_section_info line;
171   struct dwarf2_section_info loc;
172   struct dwarf2_section_info macinfo;
173   struct dwarf2_section_info macro;
174   struct dwarf2_section_info str;
175   struct dwarf2_section_info ranges;
176   struct dwarf2_section_info addr;
177   struct dwarf2_section_info frame;
178   struct dwarf2_section_info eh_frame;
179   struct dwarf2_section_info gdb_index;
180
181   VEC (dwarf2_section_info_def) *types;
182
183   /* Back link.  */
184   struct objfile *objfile;
185
186   /* Table of all the compilation units.  This is used to locate
187      the target compilation unit of a particular reference.  */
188   struct dwarf2_per_cu_data **all_comp_units;
189
190   /* The number of compilation units in ALL_COMP_UNITS.  */
191   int n_comp_units;
192
193   /* The number of .debug_types-related CUs.  */
194   int n_type_units;
195
196   /* The .debug_types-related CUs (TUs).  */
197   struct signatured_type **all_type_units;
198
199   /* The number of entries in all_type_unit_groups.  */
200   int n_type_unit_groups;
201
202   /* Table of type unit groups.
203      This exists to make it easy to iterate over all CUs and TU groups.  */
204   struct type_unit_group **all_type_unit_groups;
205
206   /* Table of struct type_unit_group objects.
207      The hash key is the DW_AT_stmt_list value.  */
208   htab_t type_unit_groups;
209
210   /* A table mapping .debug_types signatures to its signatured_type entry.
211      This is NULL if the .debug_types section hasn't been read in yet.  */
212   htab_t signatured_types;
213
214   /* Type unit statistics, to see how well the scaling improvements
215      are doing.  */
216   struct tu_stats
217   {
218     int nr_uniq_abbrev_tables;
219     int nr_symtabs;
220     int nr_symtab_sharers;
221     int nr_stmt_less_type_units;
222   } tu_stats;
223
224   /* A chain of compilation units that are currently read in, so that
225      they can be freed later.  */
226   struct dwarf2_per_cu_data *read_in_chain;
227
228   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
229      This is NULL if the table hasn't been allocated yet.  */
230   htab_t dwo_files;
231
232   /* Non-zero if we've check for whether there is a DWP file.  */
233   int dwp_checked;
234
235   /* The DWP file if there is one, or NULL.  */
236   struct dwp_file *dwp_file;
237
238   /* The shared '.dwz' file, if one exists.  This is used when the
239      original data was compressed using 'dwz -m'.  */
240   struct dwz_file *dwz_file;
241
242   /* A flag indicating wether this objfile has a section loaded at a
243      VMA of 0.  */
244   int has_section_at_zero;
245
246   /* True if we are using the mapped index,
247      or we are faking it for OBJF_READNOW's sake.  */
248   unsigned char using_index;
249
250   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
251   struct mapped_index *index_table;
252
253   /* When using index_table, this keeps track of all quick_file_names entries.
254      TUs typically share line table entries with a CU, so we maintain a
255      separate table of all line table entries to support the sharing.
256      Note that while there can be way more TUs than CUs, we've already
257      sorted all the TUs into "type unit groups", grouped by their
258      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
259      CU and its associated TU group if there is one.  */
260   htab_t quick_file_names_table;
261
262   /* Set during partial symbol reading, to prevent queueing of full
263      symbols.  */
264   int reading_partial_symbols;
265
266   /* Table mapping type DIEs to their struct type *.
267      This is NULL if not allocated yet.
268      The mapping is done via (CU/TU signature + DIE offset) -> type.  */
269   htab_t die_type_hash;
270
271   /* The CUs we recently read.  */
272   VEC (dwarf2_per_cu_ptr) *just_read_cus;
273 };
274
275 static struct dwarf2_per_objfile *dwarf2_per_objfile;
276
277 /* Default names of the debugging sections.  */
278
279 /* Note that if the debugging section has been compressed, it might
280    have a name like .zdebug_info.  */
281
282 static const struct dwarf2_debug_sections dwarf2_elf_names =
283 {
284   { ".debug_info", ".zdebug_info" },
285   { ".debug_abbrev", ".zdebug_abbrev" },
286   { ".debug_line", ".zdebug_line" },
287   { ".debug_loc", ".zdebug_loc" },
288   { ".debug_macinfo", ".zdebug_macinfo" },
289   { ".debug_macro", ".zdebug_macro" },
290   { ".debug_str", ".zdebug_str" },
291   { ".debug_ranges", ".zdebug_ranges" },
292   { ".debug_types", ".zdebug_types" },
293   { ".debug_addr", ".zdebug_addr" },
294   { ".debug_frame", ".zdebug_frame" },
295   { ".eh_frame", NULL },
296   { ".gdb_index", ".zgdb_index" },
297   23
298 };
299
300 /* List of DWO/DWP sections.  */
301
302 static const struct dwop_section_names
303 {
304   struct dwarf2_section_names abbrev_dwo;
305   struct dwarf2_section_names info_dwo;
306   struct dwarf2_section_names line_dwo;
307   struct dwarf2_section_names loc_dwo;
308   struct dwarf2_section_names macinfo_dwo;
309   struct dwarf2_section_names macro_dwo;
310   struct dwarf2_section_names str_dwo;
311   struct dwarf2_section_names str_offsets_dwo;
312   struct dwarf2_section_names types_dwo;
313   struct dwarf2_section_names cu_index;
314   struct dwarf2_section_names tu_index;
315 }
316 dwop_section_names =
317 {
318   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
319   { ".debug_info.dwo", ".zdebug_info.dwo" },
320   { ".debug_line.dwo", ".zdebug_line.dwo" },
321   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
322   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
323   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
324   { ".debug_str.dwo", ".zdebug_str.dwo" },
325   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
326   { ".debug_types.dwo", ".zdebug_types.dwo" },
327   { ".debug_cu_index", ".zdebug_cu_index" },
328   { ".debug_tu_index", ".zdebug_tu_index" },
329 };
330
331 /* local data types */
332
333 /* The data in a compilation unit header, after target2host
334    translation, looks like this.  */
335 struct comp_unit_head
336 {
337   unsigned int length;
338   short version;
339   unsigned char addr_size;
340   unsigned char signed_addr_p;
341   sect_offset abbrev_offset;
342
343   /* Size of file offsets; either 4 or 8.  */
344   unsigned int offset_size;
345
346   /* Size of the length field; either 4 or 12.  */
347   unsigned int initial_length_size;
348
349   /* Offset to the first byte of this compilation unit header in the
350      .debug_info section, for resolving relative reference dies.  */
351   sect_offset offset;
352
353   /* Offset to first die in this cu from the start of the cu.
354      This will be the first byte following the compilation unit header.  */
355   cu_offset first_die_offset;
356 };
357
358 /* Type used for delaying computation of method physnames.
359    See comments for compute_delayed_physnames.  */
360 struct delayed_method_info
361 {
362   /* The type to which the method is attached, i.e., its parent class.  */
363   struct type *type;
364
365   /* The index of the method in the type's function fieldlists.  */
366   int fnfield_index;
367
368   /* The index of the method in the fieldlist.  */
369   int index;
370
371   /* The name of the DIE.  */
372   const char *name;
373
374   /*  The DIE associated with this method.  */
375   struct die_info *die;
376 };
377
378 typedef struct delayed_method_info delayed_method_info;
379 DEF_VEC_O (delayed_method_info);
380
381 /* Internal state when decoding a particular compilation unit.  */
382 struct dwarf2_cu
383 {
384   /* The objfile containing this compilation unit.  */
385   struct objfile *objfile;
386
387   /* The header of the compilation unit.  */
388   struct comp_unit_head header;
389
390   /* Base address of this compilation unit.  */
391   CORE_ADDR base_address;
392
393   /* Non-zero if base_address has been set.  */
394   int base_known;
395
396   /* The language we are debugging.  */
397   enum language language;
398   const struct language_defn *language_defn;
399
400   const char *producer;
401
402   /* The generic symbol table building routines have separate lists for
403      file scope symbols and all all other scopes (local scopes).  So
404      we need to select the right one to pass to add_symbol_to_list().
405      We do it by keeping a pointer to the correct list in list_in_scope.
406
407      FIXME: The original dwarf code just treated the file scope as the
408      first local scope, and all other local scopes as nested local
409      scopes, and worked fine.  Check to see if we really need to
410      distinguish these in buildsym.c.  */
411   struct pending **list_in_scope;
412
413   /* The abbrev table for this CU.
414      Normally this points to the abbrev table in the objfile.
415      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
416   struct abbrev_table *abbrev_table;
417
418   /* Hash table holding all the loaded partial DIEs
419      with partial_die->offset.SECT_OFF as hash.  */
420   htab_t partial_dies;
421
422   /* Storage for things with the same lifetime as this read-in compilation
423      unit, including partial DIEs.  */
424   struct obstack comp_unit_obstack;
425
426   /* When multiple dwarf2_cu structures are living in memory, this field
427      chains them all together, so that they can be released efficiently.
428      We will probably also want a generation counter so that most-recently-used
429      compilation units are cached...  */
430   struct dwarf2_per_cu_data *read_in_chain;
431
432   /* Backchain to our per_cu entry if the tree has been built.  */
433   struct dwarf2_per_cu_data *per_cu;
434
435   /* How many compilation units ago was this CU last referenced?  */
436   int last_used;
437
438   /* A hash table of DIE cu_offset for following references with
439      die_info->offset.sect_off as hash.  */
440   htab_t die_hash;
441
442   /* Full DIEs if read in.  */
443   struct die_info *dies;
444
445   /* A set of pointers to dwarf2_per_cu_data objects for compilation
446      units referenced by this one.  Only set during full symbol processing;
447      partial symbol tables do not have dependencies.  */
448   htab_t dependencies;
449
450   /* Header data from the line table, during full symbol processing.  */
451   struct line_header *line_header;
452
453   /* A list of methods which need to have physnames computed
454      after all type information has been read.  */
455   VEC (delayed_method_info) *method_list;
456
457   /* To be copied to symtab->call_site_htab.  */
458   htab_t call_site_htab;
459
460   /* Non-NULL if this CU came from a DWO file.
461      There is an invariant here that is important to remember:
462      Except for attributes copied from the top level DIE in the "main"
463      (or "stub") file in preparation for reading the DWO file
464      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
465      Either there isn't a DWO file (in which case this is NULL and the point
466      is moot), or there is and either we're not going to read it (in which
467      case this is NULL) or there is and we are reading it (in which case this
468      is non-NULL).  */
469   struct dwo_unit *dwo_unit;
470
471   /* The DW_AT_addr_base attribute if present, zero otherwise
472      (zero is a valid value though).
473      Note this value comes from the stub CU/TU's DIE.  */
474   ULONGEST addr_base;
475
476   /* The DW_AT_ranges_base attribute if present, zero otherwise
477      (zero is a valid value though).
478      Note this value comes from the stub CU/TU's DIE.
479      Also note that the value is zero in the non-DWO case so this value can
480      be used without needing to know whether DWO files are in use or not.
481      N.B. This does not apply to DW_AT_ranges appearing in
482      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
483      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
484      DW_AT_ranges_base *would* have to be applied, and we'd have to care
485      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
486   ULONGEST ranges_base;
487
488   /* Mark used when releasing cached dies.  */
489   unsigned int mark : 1;
490
491   /* This CU references .debug_loc.  See the symtab->locations_valid field.
492      This test is imperfect as there may exist optimized debug code not using
493      any location list and still facing inlining issues if handled as
494      unoptimized code.  For a future better test see GCC PR other/32998.  */
495   unsigned int has_loclist : 1;
496
497   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
498      if all the producer_is_* fields are valid.  This information is cached
499      because profiling CU expansion showed excessive time spent in
500      producer_is_gxx_lt_4_6.  */
501   unsigned int checked_producer : 1;
502   unsigned int producer_is_gxx_lt_4_6 : 1;
503   unsigned int producer_is_gcc_lt_4_3 : 1;
504   unsigned int producer_is_icc : 1;
505
506   /* When set, the file that we're processing is known to have
507      debugging info for C++ namespaces.  GCC 3.3.x did not produce
508      this information, but later versions do.  */
509
510   unsigned int processing_has_namespace_info : 1;
511 };
512
513 /* Persistent data held for a compilation unit, even when not
514    processing it.  We put a pointer to this structure in the
515    read_symtab_private field of the psymtab.  */
516
517 struct dwarf2_per_cu_data
518 {
519   /* The start offset and length of this compilation unit.
520      NOTE: Unlike comp_unit_head.length, this length includes
521      initial_length_size.
522      If the DIE refers to a DWO file, this is always of the original die,
523      not the DWO file.  */
524   sect_offset offset;
525   unsigned int length;
526
527   /* Flag indicating this compilation unit will be read in before
528      any of the current compilation units are processed.  */
529   unsigned int queued : 1;
530
531   /* This flag will be set when reading partial DIEs if we need to load
532      absolutely all DIEs for this compilation unit, instead of just the ones
533      we think are interesting.  It gets set if we look for a DIE in the
534      hash table and don't find it.  */
535   unsigned int load_all_dies : 1;
536
537   /* Non-zero if this CU is from .debug_types.  */
538   unsigned int is_debug_types : 1;
539
540   /* Non-zero if this CU is from the .dwz file.  */
541   unsigned int is_dwz : 1;
542
543   /* The section this CU/TU lives in.
544      If the DIE refers to a DWO file, this is always the original die,
545      not the DWO file.  */
546   struct dwarf2_section_info *info_or_types_section;
547
548   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
549      of the CU cache it gets reset to NULL again.  */
550   struct dwarf2_cu *cu;
551
552   /* The corresponding objfile.
553      Normally we can get the objfile from dwarf2_per_objfile.
554      However we can enter this file with just a "per_cu" handle.  */
555   struct objfile *objfile;
556
557   /* When using partial symbol tables, the 'psymtab' field is active.
558      Otherwise the 'quick' field is active.  */
559   union
560   {
561     /* The partial symbol table associated with this compilation unit,
562        or NULL for unread partial units.  */
563     struct partial_symtab *psymtab;
564
565     /* Data needed by the "quick" functions.  */
566     struct dwarf2_per_cu_quick_data *quick;
567   } v;
568
569   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
570      while reading psymtabs, used to compute the psymtab dependencies,
571      and then cleared.  Then it is filled in again while reading full
572      symbols, and only deleted when the objfile is destroyed.
573
574      This is also used to work around a difference between the way gold
575      generates .gdb_index version <=7 and the way gdb does.  Arguably this
576      is a gold bug.  For symbols coming from TUs, gold records in the index
577      the CU that includes the TU instead of the TU itself.  This breaks
578      dw2_lookup_symbol: It assumes that if the index says symbol X lives
579      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
580      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
581      we need to look in TU Z to find X.  Fortunately, this is akin to
582      DW_TAG_imported_unit, so we just use the same mechanism: For
583      .gdb_index version <=7 this also records the TUs that the CU referred
584      to.  Concurrently with this change gdb was modified to emit version 8
585      indices so we only pay a price for gold generated indices.  */
586   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
587
588   /* Type units are grouped by their DW_AT_stmt_list entry so that they
589      can share them.  If this is a TU, this points to the containing
590      symtab.  */
591   struct type_unit_group *type_unit_group;
592 };
593
594 /* Entry in the signatured_types hash table.  */
595
596 struct signatured_type
597 {
598   /* The "per_cu" object of this type.
599      N.B.: This is the first member so that it's easy to convert pointers
600      between them.  */
601   struct dwarf2_per_cu_data per_cu;
602
603   /* The type's signature.  */
604   ULONGEST signature;
605
606   /* Offset in the TU of the type's DIE, as read from the TU header.
607      If the definition lives in a DWO file, this value is unusable.  */
608   cu_offset type_offset_in_tu;
609
610   /* Offset in the section of the type's DIE.
611      If the definition lives in a DWO file, this is the offset in the
612      .debug_types.dwo section.
613      The value is zero until the actual value is known.
614      Zero is otherwise not a valid section offset.  */
615   sect_offset type_offset_in_section;
616 };
617
618 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
619    This includes type_unit_group and quick_file_names.  */
620
621 struct stmt_list_hash
622 {
623   /* The DWO unit this table is from or NULL if there is none.  */
624   struct dwo_unit *dwo_unit;
625
626   /* Offset in .debug_line or .debug_line.dwo.  */
627   sect_offset line_offset;
628 };
629
630 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
631    an object of this type.  */
632
633 struct type_unit_group
634 {
635   /* dwarf2read.c's main "handle" on the symtab.
636      To simplify things we create an artificial CU that "includes" all the
637      type units using this stmt_list so that the rest of the code still has
638      a "per_cu" handle on the symtab.
639      This PER_CU is recognized by having no section.  */
640 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->info_or_types_section == NULL)
641   struct dwarf2_per_cu_data per_cu;
642
643   union
644   {
645     /* The TUs that share this DW_AT_stmt_list entry.
646        This is added to while parsing type units to build partial symtabs,
647        and is deleted afterwards and not used again.  */
648     VEC (dwarf2_per_cu_ptr) *tus;
649
650     /* When reading the line table in "quick" functions, we need a real TU.
651        Any will do, we know they all share the same DW_AT_stmt_list entry.
652        For simplicity's sake, we pick the first one.  */
653     struct dwarf2_per_cu_data *first_tu;
654   } t;
655
656   /* The primary symtab.
657      Type units in a group needn't all be defined in the same source file,
658      so we create an essentially anonymous symtab as the primary symtab.  */
659   struct symtab *primary_symtab;
660
661   /* The data used to construct the hash key.  */
662   struct stmt_list_hash hash;
663
664   /* The number of symtabs from the line header.
665      The value here must match line_header.num_file_names.  */
666   unsigned int num_symtabs;
667
668   /* The symbol tables for this TU (obtained from the files listed in
669      DW_AT_stmt_list).
670      WARNING: The order of entries here must match the order of entries
671      in the line header.  After the first TU using this type_unit_group, the
672      line header for the subsequent TUs is recreated from this.  This is done
673      because we need to use the same symtabs for each TU using the same
674      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
675      there's no guarantee the line header doesn't have duplicate entries.  */
676   struct symtab **symtabs;
677 };
678
679 /* These sections are what may appear in a DWO file.  */
680
681 struct dwo_sections
682 {
683   struct dwarf2_section_info abbrev;
684   struct dwarf2_section_info line;
685   struct dwarf2_section_info loc;
686   struct dwarf2_section_info macinfo;
687   struct dwarf2_section_info macro;
688   struct dwarf2_section_info str;
689   struct dwarf2_section_info str_offsets;
690   /* In the case of a virtual DWO file, these two are unused.  */
691   struct dwarf2_section_info info;
692   VEC (dwarf2_section_info_def) *types;
693 };
694
695 /* Common bits of DWO CUs/TUs.  */
696
697 struct dwo_unit
698 {
699   /* Backlink to the containing struct dwo_file.  */
700   struct dwo_file *dwo_file;
701
702   /* The "id" that distinguishes this CU/TU.
703      .debug_info calls this "dwo_id", .debug_types calls this "signature".
704      Since signatures came first, we stick with it for consistency.  */
705   ULONGEST signature;
706
707   /* The section this CU/TU lives in, in the DWO file.  */
708   struct dwarf2_section_info *info_or_types_section;
709
710   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
711   sect_offset offset;
712   unsigned int length;
713
714   /* For types, offset in the type's DIE of the type defined by this TU.  */
715   cu_offset type_offset_in_tu;
716 };
717
718 /* Data for one DWO file.
719    This includes virtual DWO files that have been packaged into a
720    DWP file.  */
721
722 struct dwo_file
723 {
724   /* The DW_AT_GNU_dwo_name attribute.  This is the hash key.
725      For virtual DWO files the name is constructed from the section offsets
726      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
727      from related CU+TUs.  */
728   const char *name;
729
730   /* The bfd, when the file is open.  Otherwise this is NULL.
731      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
732   bfd *dbfd;
733
734   /* Section info for this file.  */
735   struct dwo_sections sections;
736
737   /* Table of CUs in the file.
738      Each element is a struct dwo_unit.  */
739   htab_t cus;
740
741   /* Table of TUs in the file.
742      Each element is a struct dwo_unit.  */
743   htab_t tus;
744 };
745
746 /* These sections are what may appear in a DWP file.  */
747
748 struct dwp_sections
749 {
750   struct dwarf2_section_info str;
751   struct dwarf2_section_info cu_index;
752   struct dwarf2_section_info tu_index;
753   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
754      by section number.  We don't need to record them here.  */
755 };
756
757 /* These sections are what may appear in a virtual DWO file.  */
758
759 struct virtual_dwo_sections
760 {
761   struct dwarf2_section_info abbrev;
762   struct dwarf2_section_info line;
763   struct dwarf2_section_info loc;
764   struct dwarf2_section_info macinfo;
765   struct dwarf2_section_info macro;
766   struct dwarf2_section_info str_offsets;
767   /* Each DWP hash table entry records one CU or one TU.
768      That is recorded here, and copied to dwo_unit.info_or_types_section.  */
769   struct dwarf2_section_info info_or_types;
770 };
771
772 /* Contents of DWP hash tables.  */
773
774 struct dwp_hash_table
775 {
776   uint32_t nr_units, nr_slots;
777   const gdb_byte *hash_table, *unit_table, *section_pool;
778 };
779
780 /* Data for one DWP file.  */
781
782 struct dwp_file
783 {
784   /* Name of the file.  */
785   const char *name;
786
787   /* The bfd, when the file is open.  Otherwise this is NULL.  */
788   bfd *dbfd;
789
790   /* Section info for this file.  */
791   struct dwp_sections sections;
792
793   /* Table of CUs in the file. */
794   const struct dwp_hash_table *cus;
795
796   /* Table of TUs in the file.  */
797   const struct dwp_hash_table *tus;
798
799   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
800   htab_t loaded_cutus;
801
802   /* Table to map ELF section numbers to their sections.  */
803   unsigned int num_sections;
804   asection **elf_sections;
805 };
806
807 /* This represents a '.dwz' file.  */
808
809 struct dwz_file
810 {
811   /* A dwz file can only contain a few sections.  */
812   struct dwarf2_section_info abbrev;
813   struct dwarf2_section_info info;
814   struct dwarf2_section_info str;
815   struct dwarf2_section_info line;
816   struct dwarf2_section_info macro;
817   struct dwarf2_section_info gdb_index;
818
819   /* The dwz's BFD.  */
820   bfd *dwz_bfd;
821 };
822
823 /* Struct used to pass misc. parameters to read_die_and_children, et
824    al.  which are used for both .debug_info and .debug_types dies.
825    All parameters here are unchanging for the life of the call.  This
826    struct exists to abstract away the constant parameters of die reading.  */
827
828 struct die_reader_specs
829 {
830   /* die_section->asection->owner.  */
831   bfd* abfd;
832
833   /* The CU of the DIE we are parsing.  */
834   struct dwarf2_cu *cu;
835
836   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
837   struct dwo_file *dwo_file;
838
839   /* The section the die comes from.
840      This is either .debug_info or .debug_types, or the .dwo variants.  */
841   struct dwarf2_section_info *die_section;
842
843   /* die_section->buffer.  */
844   gdb_byte *buffer;
845
846   /* The end of the buffer.  */
847   const gdb_byte *buffer_end;
848 };
849
850 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
851 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
852                                       gdb_byte *info_ptr,
853                                       struct die_info *comp_unit_die,
854                                       int has_children,
855                                       void *data);
856
857 /* The line number information for a compilation unit (found in the
858    .debug_line section) begins with a "statement program header",
859    which contains the following information.  */
860 struct line_header
861 {
862   unsigned int total_length;
863   unsigned short version;
864   unsigned int header_length;
865   unsigned char minimum_instruction_length;
866   unsigned char maximum_ops_per_instruction;
867   unsigned char default_is_stmt;
868   int line_base;
869   unsigned char line_range;
870   unsigned char opcode_base;
871
872   /* standard_opcode_lengths[i] is the number of operands for the
873      standard opcode whose value is i.  This means that
874      standard_opcode_lengths[0] is unused, and the last meaningful
875      element is standard_opcode_lengths[opcode_base - 1].  */
876   unsigned char *standard_opcode_lengths;
877
878   /* The include_directories table.  NOTE!  These strings are not
879      allocated with xmalloc; instead, they are pointers into
880      debug_line_buffer.  If you try to free them, `free' will get
881      indigestion.  */
882   unsigned int num_include_dirs, include_dirs_size;
883   char **include_dirs;
884
885   /* The file_names table.  NOTE!  These strings are not allocated
886      with xmalloc; instead, they are pointers into debug_line_buffer.
887      Don't try to free them directly.  */
888   unsigned int num_file_names, file_names_size;
889   struct file_entry
890   {
891     char *name;
892     unsigned int dir_index;
893     unsigned int mod_time;
894     unsigned int length;
895     int included_p; /* Non-zero if referenced by the Line Number Program.  */
896     struct symtab *symtab; /* The associated symbol table, if any.  */
897   } *file_names;
898
899   /* The start and end of the statement program following this
900      header.  These point into dwarf2_per_objfile->line_buffer.  */
901   gdb_byte *statement_program_start, *statement_program_end;
902 };
903
904 /* When we construct a partial symbol table entry we only
905    need this much information.  */
906 struct partial_die_info
907   {
908     /* Offset of this DIE.  */
909     sect_offset offset;
910
911     /* DWARF-2 tag for this DIE.  */
912     ENUM_BITFIELD(dwarf_tag) tag : 16;
913
914     /* Assorted flags describing the data found in this DIE.  */
915     unsigned int has_children : 1;
916     unsigned int is_external : 1;
917     unsigned int is_declaration : 1;
918     unsigned int has_type : 1;
919     unsigned int has_specification : 1;
920     unsigned int has_pc_info : 1;
921     unsigned int may_be_inlined : 1;
922
923     /* Flag set if the SCOPE field of this structure has been
924        computed.  */
925     unsigned int scope_set : 1;
926
927     /* Flag set if the DIE has a byte_size attribute.  */
928     unsigned int has_byte_size : 1;
929
930     /* Flag set if any of the DIE's children are template arguments.  */
931     unsigned int has_template_arguments : 1;
932
933     /* Flag set if fixup_partial_die has been called on this die.  */
934     unsigned int fixup_called : 1;
935
936     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
937     unsigned int is_dwz : 1;
938
939     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
940     unsigned int spec_is_dwz : 1;
941
942     /* The name of this DIE.  Normally the value of DW_AT_name, but
943        sometimes a default name for unnamed DIEs.  */
944     const char *name;
945
946     /* The linkage name, if present.  */
947     const char *linkage_name;
948
949     /* The scope to prepend to our children.  This is generally
950        allocated on the comp_unit_obstack, so will disappear
951        when this compilation unit leaves the cache.  */
952     const char *scope;
953
954     /* Some data associated with the partial DIE.  The tag determines
955        which field is live.  */
956     union
957     {
958       /* The location description associated with this DIE, if any.  */
959       struct dwarf_block *locdesc;
960       /* The offset of an import, for DW_TAG_imported_unit.  */
961       sect_offset offset;
962     } d;
963
964     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
965     CORE_ADDR lowpc;
966     CORE_ADDR highpc;
967
968     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
969        DW_AT_sibling, if any.  */
970     /* NOTE: This member isn't strictly necessary, read_partial_die could
971        return DW_AT_sibling values to its caller load_partial_dies.  */
972     gdb_byte *sibling;
973
974     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
975        DW_AT_specification (or DW_AT_abstract_origin or
976        DW_AT_extension).  */
977     sect_offset spec_offset;
978
979     /* Pointers to this DIE's parent, first child, and next sibling,
980        if any.  */
981     struct partial_die_info *die_parent, *die_child, *die_sibling;
982   };
983
984 /* This data structure holds the information of an abbrev.  */
985 struct abbrev_info
986   {
987     unsigned int number;        /* number identifying abbrev */
988     enum dwarf_tag tag;         /* dwarf tag */
989     unsigned short has_children;                /* boolean */
990     unsigned short num_attrs;   /* number of attributes */
991     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
992     struct abbrev_info *next;   /* next in chain */
993   };
994
995 struct attr_abbrev
996   {
997     ENUM_BITFIELD(dwarf_attribute) name : 16;
998     ENUM_BITFIELD(dwarf_form) form : 16;
999   };
1000
1001 /* Size of abbrev_table.abbrev_hash_table.  */
1002 #define ABBREV_HASH_SIZE 121
1003
1004 /* Top level data structure to contain an abbreviation table.  */
1005
1006 struct abbrev_table
1007 {
1008   /* Where the abbrev table came from.
1009      This is used as a sanity check when the table is used.  */
1010   sect_offset offset;
1011
1012   /* Storage for the abbrev table.  */
1013   struct obstack abbrev_obstack;
1014
1015   /* Hash table of abbrevs.
1016      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1017      It could be statically allocated, but the previous code didn't so we
1018      don't either.  */
1019   struct abbrev_info **abbrevs;
1020 };
1021
1022 /* Attributes have a name and a value.  */
1023 struct attribute
1024   {
1025     ENUM_BITFIELD(dwarf_attribute) name : 16;
1026     ENUM_BITFIELD(dwarf_form) form : 15;
1027
1028     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1029        field should be in u.str (existing only for DW_STRING) but it is kept
1030        here for better struct attribute alignment.  */
1031     unsigned int string_is_canonical : 1;
1032
1033     union
1034       {
1035         const char *str;
1036         struct dwarf_block *blk;
1037         ULONGEST unsnd;
1038         LONGEST snd;
1039         CORE_ADDR addr;
1040         struct signatured_type *signatured_type;
1041       }
1042     u;
1043   };
1044
1045 /* This data structure holds a complete die structure.  */
1046 struct die_info
1047   {
1048     /* DWARF-2 tag for this DIE.  */
1049     ENUM_BITFIELD(dwarf_tag) tag : 16;
1050
1051     /* Number of attributes */
1052     unsigned char num_attrs;
1053
1054     /* True if we're presently building the full type name for the
1055        type derived from this DIE.  */
1056     unsigned char building_fullname : 1;
1057
1058     /* Abbrev number */
1059     unsigned int abbrev;
1060
1061     /* Offset in .debug_info or .debug_types section.  */
1062     sect_offset offset;
1063
1064     /* The dies in a compilation unit form an n-ary tree.  PARENT
1065        points to this die's parent; CHILD points to the first child of
1066        this node; and all the children of a given node are chained
1067        together via their SIBLING fields.  */
1068     struct die_info *child;     /* Its first child, if any.  */
1069     struct die_info *sibling;   /* Its next sibling, if any.  */
1070     struct die_info *parent;    /* Its parent, if any.  */
1071
1072     /* An array of attributes, with NUM_ATTRS elements.  There may be
1073        zero, but it's not common and zero-sized arrays are not
1074        sufficiently portable C.  */
1075     struct attribute attrs[1];
1076   };
1077
1078 /* Get at parts of an attribute structure.  */
1079
1080 #define DW_STRING(attr)    ((attr)->u.str)
1081 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1082 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1083 #define DW_BLOCK(attr)     ((attr)->u.blk)
1084 #define DW_SND(attr)       ((attr)->u.snd)
1085 #define DW_ADDR(attr)      ((attr)->u.addr)
1086 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
1087
1088 /* Blocks are a bunch of untyped bytes.  */
1089 struct dwarf_block
1090   {
1091     size_t size;
1092
1093     /* Valid only if SIZE is not zero.  */
1094     gdb_byte *data;
1095   };
1096
1097 #ifndef ATTR_ALLOC_CHUNK
1098 #define ATTR_ALLOC_CHUNK 4
1099 #endif
1100
1101 /* Allocate fields for structs, unions and enums in this size.  */
1102 #ifndef DW_FIELD_ALLOC_CHUNK
1103 #define DW_FIELD_ALLOC_CHUNK 4
1104 #endif
1105
1106 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1107    but this would require a corresponding change in unpack_field_as_long
1108    and friends.  */
1109 static int bits_per_byte = 8;
1110
1111 /* The routines that read and process dies for a C struct or C++ class
1112    pass lists of data member fields and lists of member function fields
1113    in an instance of a field_info structure, as defined below.  */
1114 struct field_info
1115   {
1116     /* List of data member and baseclasses fields.  */
1117     struct nextfield
1118       {
1119         struct nextfield *next;
1120         int accessibility;
1121         int virtuality;
1122         struct field field;
1123       }
1124      *fields, *baseclasses;
1125
1126     /* Number of fields (including baseclasses).  */
1127     int nfields;
1128
1129     /* Number of baseclasses.  */
1130     int nbaseclasses;
1131
1132     /* Set if the accesibility of one of the fields is not public.  */
1133     int non_public_fields;
1134
1135     /* Member function fields array, entries are allocated in the order they
1136        are encountered in the object file.  */
1137     struct nextfnfield
1138       {
1139         struct nextfnfield *next;
1140         struct fn_field fnfield;
1141       }
1142      *fnfields;
1143
1144     /* Member function fieldlist array, contains name of possibly overloaded
1145        member function, number of overloaded member functions and a pointer
1146        to the head of the member function field chain.  */
1147     struct fnfieldlist
1148       {
1149         const char *name;
1150         int length;
1151         struct nextfnfield *head;
1152       }
1153      *fnfieldlists;
1154
1155     /* Number of entries in the fnfieldlists array.  */
1156     int nfnfields;
1157
1158     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1159        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1160     struct typedef_field_list
1161       {
1162         struct typedef_field field;
1163         struct typedef_field_list *next;
1164       }
1165     *typedef_field_list;
1166     unsigned typedef_field_list_count;
1167   };
1168
1169 /* One item on the queue of compilation units to read in full symbols
1170    for.  */
1171 struct dwarf2_queue_item
1172 {
1173   struct dwarf2_per_cu_data *per_cu;
1174   enum language pretend_language;
1175   struct dwarf2_queue_item *next;
1176 };
1177
1178 /* The current queue.  */
1179 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1180
1181 /* Loaded secondary compilation units are kept in memory until they
1182    have not been referenced for the processing of this many
1183    compilation units.  Set this to zero to disable caching.  Cache
1184    sizes of up to at least twenty will improve startup time for
1185    typical inter-CU-reference binaries, at an obvious memory cost.  */
1186 static int dwarf2_max_cache_age = 5;
1187 static void
1188 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1189                            struct cmd_list_element *c, const char *value)
1190 {
1191   fprintf_filtered (file, _("The upper bound on the age of cached "
1192                             "dwarf2 compilation units is %s.\n"),
1193                     value);
1194 }
1195
1196
1197 /* Various complaints about symbol reading that don't abort the process.  */
1198
1199 static void
1200 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1201 {
1202   complaint (&symfile_complaints,
1203              _("statement list doesn't fit in .debug_line section"));
1204 }
1205
1206 static void
1207 dwarf2_debug_line_missing_file_complaint (void)
1208 {
1209   complaint (&symfile_complaints,
1210              _(".debug_line section has line data without a file"));
1211 }
1212
1213 static void
1214 dwarf2_debug_line_missing_end_sequence_complaint (void)
1215 {
1216   complaint (&symfile_complaints,
1217              _(".debug_line section has line "
1218                "program sequence without an end"));
1219 }
1220
1221 static void
1222 dwarf2_complex_location_expr_complaint (void)
1223 {
1224   complaint (&symfile_complaints, _("location expression too complex"));
1225 }
1226
1227 static void
1228 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1229                                               int arg3)
1230 {
1231   complaint (&symfile_complaints,
1232              _("const value length mismatch for '%s', got %d, expected %d"),
1233              arg1, arg2, arg3);
1234 }
1235
1236 static void
1237 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1238 {
1239   complaint (&symfile_complaints,
1240              _("debug info runs off end of %s section"
1241                " [in module %s]"),
1242              section->asection->name,
1243              bfd_get_filename (section->asection->owner));
1244 }
1245
1246 static void
1247 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1248 {
1249   complaint (&symfile_complaints,
1250              _("macro debug info contains a "
1251                "malformed macro definition:\n`%s'"),
1252              arg1);
1253 }
1254
1255 static void
1256 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1257 {
1258   complaint (&symfile_complaints,
1259              _("invalid attribute class or form for '%s' in '%s'"),
1260              arg1, arg2);
1261 }
1262
1263 /* local function prototypes */
1264
1265 static void dwarf2_locate_sections (bfd *, asection *, void *);
1266
1267 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1268                                            struct objfile *);
1269
1270 static void dwarf2_find_base_address (struct die_info *die,
1271                                       struct dwarf2_cu *cu);
1272
1273 static void dwarf2_build_psymtabs_hard (struct objfile *);
1274
1275 static void scan_partial_symbols (struct partial_die_info *,
1276                                   CORE_ADDR *, CORE_ADDR *,
1277                                   int, struct dwarf2_cu *);
1278
1279 static void add_partial_symbol (struct partial_die_info *,
1280                                 struct dwarf2_cu *);
1281
1282 static void add_partial_namespace (struct partial_die_info *pdi,
1283                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1284                                    int need_pc, struct dwarf2_cu *cu);
1285
1286 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1287                                 CORE_ADDR *highpc, int need_pc,
1288                                 struct dwarf2_cu *cu);
1289
1290 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1291                                      struct dwarf2_cu *cu);
1292
1293 static void add_partial_subprogram (struct partial_die_info *pdi,
1294                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1295                                     int need_pc, struct dwarf2_cu *cu);
1296
1297 static void dwarf2_read_symtab (struct partial_symtab *,
1298                                 struct objfile *);
1299
1300 static void psymtab_to_symtab_1 (struct partial_symtab *);
1301
1302 static struct abbrev_info *abbrev_table_lookup_abbrev
1303   (const struct abbrev_table *, unsigned int);
1304
1305 static struct abbrev_table *abbrev_table_read_table
1306   (struct dwarf2_section_info *, sect_offset);
1307
1308 static void abbrev_table_free (struct abbrev_table *);
1309
1310 static void abbrev_table_free_cleanup (void *);
1311
1312 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1313                                  struct dwarf2_section_info *);
1314
1315 static void dwarf2_free_abbrev_table (void *);
1316
1317 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1318
1319 static struct partial_die_info *load_partial_dies
1320   (const struct die_reader_specs *, gdb_byte *, int);
1321
1322 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1323                                    struct partial_die_info *,
1324                                    struct abbrev_info *,
1325                                    unsigned int,
1326                                    gdb_byte *);
1327
1328 static struct partial_die_info *find_partial_die (sect_offset, int,
1329                                                   struct dwarf2_cu *);
1330
1331 static void fixup_partial_die (struct partial_die_info *,
1332                                struct dwarf2_cu *);
1333
1334 static gdb_byte *read_attribute (const struct die_reader_specs *,
1335                                  struct attribute *, struct attr_abbrev *,
1336                                  gdb_byte *);
1337
1338 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1339
1340 static int read_1_signed_byte (bfd *, const gdb_byte *);
1341
1342 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1343
1344 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1345
1346 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1347
1348 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1349                                unsigned int *);
1350
1351 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1352
1353 static LONGEST read_checked_initial_length_and_offset
1354   (bfd *, gdb_byte *, const struct comp_unit_head *,
1355    unsigned int *, unsigned int *);
1356
1357 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1358                             unsigned int *);
1359
1360 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1361
1362 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1363                                        sect_offset);
1364
1365 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1366
1367 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1368
1369 static char *read_indirect_string (bfd *, gdb_byte *,
1370                                    const struct comp_unit_head *,
1371                                    unsigned int *);
1372
1373 static char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1374
1375 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1376
1377 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1378
1379 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1380                                               unsigned int *);
1381
1382 static char *read_str_index (const struct die_reader_specs *reader,
1383                              struct dwarf2_cu *cu, ULONGEST str_index);
1384
1385 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1386
1387 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1388                                       struct dwarf2_cu *);
1389
1390 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1391                                                 unsigned int);
1392
1393 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1394                                struct dwarf2_cu *cu);
1395
1396 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1397
1398 static struct die_info *die_specification (struct die_info *die,
1399                                            struct dwarf2_cu **);
1400
1401 static void free_line_header (struct line_header *lh);
1402
1403 static void add_file_name (struct line_header *, char *, unsigned int,
1404                            unsigned int, unsigned int);
1405
1406 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1407                                                      struct dwarf2_cu *cu);
1408
1409 static void dwarf_decode_lines (struct line_header *, const char *,
1410                                 struct dwarf2_cu *, struct partial_symtab *,
1411                                 int);
1412
1413 static void dwarf2_start_subfile (char *, const char *, const char *);
1414
1415 static void dwarf2_start_symtab (struct dwarf2_cu *,
1416                                  const char *, const char *, CORE_ADDR);
1417
1418 static struct symbol *new_symbol (struct die_info *, struct type *,
1419                                   struct dwarf2_cu *);
1420
1421 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1422                                        struct dwarf2_cu *, struct symbol *);
1423
1424 static void dwarf2_const_value (struct attribute *, struct symbol *,
1425                                 struct dwarf2_cu *);
1426
1427 static void dwarf2_const_value_attr (struct attribute *attr,
1428                                      struct type *type,
1429                                      const char *name,
1430                                      struct obstack *obstack,
1431                                      struct dwarf2_cu *cu, LONGEST *value,
1432                                      gdb_byte **bytes,
1433                                      struct dwarf2_locexpr_baton **baton);
1434
1435 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1436
1437 static int need_gnat_info (struct dwarf2_cu *);
1438
1439 static struct type *die_descriptive_type (struct die_info *,
1440                                           struct dwarf2_cu *);
1441
1442 static void set_descriptive_type (struct type *, struct die_info *,
1443                                   struct dwarf2_cu *);
1444
1445 static struct type *die_containing_type (struct die_info *,
1446                                          struct dwarf2_cu *);
1447
1448 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1449                                      struct dwarf2_cu *);
1450
1451 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1452
1453 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1454
1455 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1456
1457 static char *typename_concat (struct obstack *obs, const char *prefix,
1458                               const char *suffix, int physname,
1459                               struct dwarf2_cu *cu);
1460
1461 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1462
1463 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1464
1465 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1466
1467 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1468
1469 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1470
1471 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1472                                struct dwarf2_cu *, struct partial_symtab *);
1473
1474 static int dwarf2_get_pc_bounds (struct die_info *,
1475                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1476                                  struct partial_symtab *);
1477
1478 static void get_scope_pc_bounds (struct die_info *,
1479                                  CORE_ADDR *, CORE_ADDR *,
1480                                  struct dwarf2_cu *);
1481
1482 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1483                                         CORE_ADDR, struct dwarf2_cu *);
1484
1485 static void dwarf2_add_field (struct field_info *, struct die_info *,
1486                               struct dwarf2_cu *);
1487
1488 static void dwarf2_attach_fields_to_type (struct field_info *,
1489                                           struct type *, struct dwarf2_cu *);
1490
1491 static void dwarf2_add_member_fn (struct field_info *,
1492                                   struct die_info *, struct type *,
1493                                   struct dwarf2_cu *);
1494
1495 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1496                                              struct type *,
1497                                              struct dwarf2_cu *);
1498
1499 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1500
1501 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1502
1503 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1504
1505 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1506
1507 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1508
1509 static struct type *read_module_type (struct die_info *die,
1510                                       struct dwarf2_cu *cu);
1511
1512 static const char *namespace_name (struct die_info *die,
1513                                    int *is_anonymous, struct dwarf2_cu *);
1514
1515 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1516
1517 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1518
1519 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1520                                                        struct dwarf2_cu *);
1521
1522 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1523                                                gdb_byte *info_ptr,
1524                                                gdb_byte **new_info_ptr,
1525                                                struct die_info *parent);
1526
1527 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1528                                                gdb_byte *info_ptr,
1529                                                gdb_byte **new_info_ptr,
1530                                                struct die_info *parent);
1531
1532 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1533                                   struct die_info **, gdb_byte *, int *, int);
1534
1535 static gdb_byte *read_full_die (const struct die_reader_specs *,
1536                                 struct die_info **, gdb_byte *, int *);
1537
1538 static void process_die (struct die_info *, struct dwarf2_cu *);
1539
1540 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1541                                              struct obstack *);
1542
1543 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1544
1545 static const char *dwarf2_full_name (const char *name,
1546                                      struct die_info *die,
1547                                      struct dwarf2_cu *cu);
1548
1549 static struct die_info *dwarf2_extension (struct die_info *die,
1550                                           struct dwarf2_cu **);
1551
1552 static const char *dwarf_tag_name (unsigned int);
1553
1554 static const char *dwarf_attr_name (unsigned int);
1555
1556 static const char *dwarf_form_name (unsigned int);
1557
1558 static char *dwarf_bool_name (unsigned int);
1559
1560 static const char *dwarf_type_encoding_name (unsigned int);
1561
1562 static struct die_info *sibling_die (struct die_info *);
1563
1564 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1565
1566 static void dump_die_for_error (struct die_info *);
1567
1568 static void dump_die_1 (struct ui_file *, int level, int max_level,
1569                         struct die_info *);
1570
1571 /*static*/ void dump_die (struct die_info *, int max_level);
1572
1573 static void store_in_ref_table (struct die_info *,
1574                                 struct dwarf2_cu *);
1575
1576 static int is_ref_attr (struct attribute *);
1577
1578 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1579
1580 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1581
1582 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1583                                                struct attribute *,
1584                                                struct dwarf2_cu **);
1585
1586 static struct die_info *follow_die_ref (struct die_info *,
1587                                         struct attribute *,
1588                                         struct dwarf2_cu **);
1589
1590 static struct die_info *follow_die_sig (struct die_info *,
1591                                         struct attribute *,
1592                                         struct dwarf2_cu **);
1593
1594 static struct signatured_type *lookup_signatured_type_at_offset
1595     (struct objfile *objfile,
1596      struct dwarf2_section_info *section, sect_offset offset);
1597
1598 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1599
1600 static void read_signatured_type (struct signatured_type *);
1601
1602 static struct type_unit_group *get_type_unit_group
1603     (struct dwarf2_cu *, struct attribute *);
1604
1605 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1606
1607 /* memory allocation interface */
1608
1609 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1610
1611 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1612
1613 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1614                                  const char *, int);
1615
1616 static int attr_form_is_block (struct attribute *);
1617
1618 static int attr_form_is_section_offset (struct attribute *);
1619
1620 static int attr_form_is_constant (struct attribute *);
1621
1622 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1623                                    struct dwarf2_loclist_baton *baton,
1624                                    struct attribute *attr);
1625
1626 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1627                                          struct symbol *sym,
1628                                          struct dwarf2_cu *cu);
1629
1630 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1631                                gdb_byte *info_ptr,
1632                                struct abbrev_info *abbrev);
1633
1634 static void free_stack_comp_unit (void *);
1635
1636 static hashval_t partial_die_hash (const void *item);
1637
1638 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1639
1640 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1641   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1642
1643 static void init_one_comp_unit (struct dwarf2_cu *cu,
1644                                 struct dwarf2_per_cu_data *per_cu);
1645
1646 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1647                                    struct die_info *comp_unit_die,
1648                                    enum language pretend_language);
1649
1650 static void free_heap_comp_unit (void *);
1651
1652 static void free_cached_comp_units (void *);
1653
1654 static void age_cached_comp_units (void);
1655
1656 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1657
1658 static struct type *set_die_type (struct die_info *, struct type *,
1659                                   struct dwarf2_cu *);
1660
1661 static void create_all_comp_units (struct objfile *);
1662
1663 static int create_all_type_units (struct objfile *);
1664
1665 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1666                                  enum language);
1667
1668 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1669                                     enum language);
1670
1671 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1672                                     enum language);
1673
1674 static void dwarf2_add_dependence (struct dwarf2_cu *,
1675                                    struct dwarf2_per_cu_data *);
1676
1677 static void dwarf2_mark (struct dwarf2_cu *);
1678
1679 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1680
1681 static struct type *get_die_type_at_offset (sect_offset,
1682                                             struct dwarf2_per_cu_data *per_cu);
1683
1684 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1685
1686 static void dwarf2_release_queue (void *dummy);
1687
1688 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1689                              enum language pretend_language);
1690
1691 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1692                                   struct dwarf2_per_cu_data *per_cu,
1693                                   enum language pretend_language);
1694
1695 static void process_queue (void);
1696
1697 static void find_file_and_directory (struct die_info *die,
1698                                      struct dwarf2_cu *cu,
1699                                      const char **name, const char **comp_dir);
1700
1701 static char *file_full_name (int file, struct line_header *lh,
1702                              const char *comp_dir);
1703
1704 static gdb_byte *read_and_check_comp_unit_head
1705   (struct comp_unit_head *header,
1706    struct dwarf2_section_info *section,
1707    struct dwarf2_section_info *abbrev_section, gdb_byte *info_ptr,
1708    int is_debug_types_section);
1709
1710 static void init_cutu_and_read_dies
1711   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1712    int use_existing_cu, int keep,
1713    die_reader_func_ftype *die_reader_func, void *data);
1714
1715 static void init_cutu_and_read_dies_simple
1716   (struct dwarf2_per_cu_data *this_cu,
1717    die_reader_func_ftype *die_reader_func, void *data);
1718
1719 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1720
1721 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1722
1723 static struct dwo_unit *lookup_dwo_comp_unit
1724   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1725
1726 static struct dwo_unit *lookup_dwo_type_unit
1727   (struct signatured_type *, const char *, const char *);
1728
1729 static void free_dwo_file_cleanup (void *);
1730
1731 static void process_cu_includes (void);
1732
1733 static void check_producer (struct dwarf2_cu *cu);
1734
1735 #if WORDS_BIGENDIAN
1736
1737 /* Convert VALUE between big- and little-endian.  */
1738 static offset_type
1739 byte_swap (offset_type value)
1740 {
1741   offset_type result;
1742
1743   result = (value & 0xff) << 24;
1744   result |= (value & 0xff00) << 8;
1745   result |= (value & 0xff0000) >> 8;
1746   result |= (value & 0xff000000) >> 24;
1747   return result;
1748 }
1749
1750 #define MAYBE_SWAP(V)  byte_swap (V)
1751
1752 #else
1753 #define MAYBE_SWAP(V) (V)
1754 #endif /* WORDS_BIGENDIAN */
1755
1756 /* The suffix for an index file.  */
1757 #define INDEX_SUFFIX ".gdb-index"
1758
1759 static const char *dwarf2_physname (const char *name, struct die_info *die,
1760                                     struct dwarf2_cu *cu);
1761
1762 /* Try to locate the sections we need for DWARF 2 debugging
1763    information and return true if we have enough to do something.
1764    NAMES points to the dwarf2 section names, or is NULL if the standard
1765    ELF names are used.  */
1766
1767 int
1768 dwarf2_has_info (struct objfile *objfile,
1769                  const struct dwarf2_debug_sections *names)
1770 {
1771   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1772   if (!dwarf2_per_objfile)
1773     {
1774       /* Initialize per-objfile state.  */
1775       struct dwarf2_per_objfile *data
1776         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1777
1778       memset (data, 0, sizeof (*data));
1779       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1780       dwarf2_per_objfile = data;
1781
1782       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1783                              (void *) names);
1784       dwarf2_per_objfile->objfile = objfile;
1785     }
1786   return (dwarf2_per_objfile->info.asection != NULL
1787           && dwarf2_per_objfile->abbrev.asection != NULL);
1788 }
1789
1790 /* When loading sections, we look either for uncompressed section or for
1791    compressed section names.  */
1792
1793 static int
1794 section_is_p (const char *section_name,
1795               const struct dwarf2_section_names *names)
1796 {
1797   if (names->normal != NULL
1798       && strcmp (section_name, names->normal) == 0)
1799     return 1;
1800   if (names->compressed != NULL
1801       && strcmp (section_name, names->compressed) == 0)
1802     return 1;
1803   return 0;
1804 }
1805
1806 /* This function is mapped across the sections and remembers the
1807    offset and size of each of the debugging sections we are interested
1808    in.  */
1809
1810 static void
1811 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1812 {
1813   const struct dwarf2_debug_sections *names;
1814   flagword aflag = bfd_get_section_flags (abfd, sectp);
1815
1816   if (vnames == NULL)
1817     names = &dwarf2_elf_names;
1818   else
1819     names = (const struct dwarf2_debug_sections *) vnames;
1820
1821   if ((aflag & SEC_HAS_CONTENTS) == 0)
1822     {
1823     }
1824   else if (section_is_p (sectp->name, &names->info))
1825     {
1826       dwarf2_per_objfile->info.asection = sectp;
1827       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1828     }
1829   else if (section_is_p (sectp->name, &names->abbrev))
1830     {
1831       dwarf2_per_objfile->abbrev.asection = sectp;
1832       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1833     }
1834   else if (section_is_p (sectp->name, &names->line))
1835     {
1836       dwarf2_per_objfile->line.asection = sectp;
1837       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1838     }
1839   else if (section_is_p (sectp->name, &names->loc))
1840     {
1841       dwarf2_per_objfile->loc.asection = sectp;
1842       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1843     }
1844   else if (section_is_p (sectp->name, &names->macinfo))
1845     {
1846       dwarf2_per_objfile->macinfo.asection = sectp;
1847       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1848     }
1849   else if (section_is_p (sectp->name, &names->macro))
1850     {
1851       dwarf2_per_objfile->macro.asection = sectp;
1852       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1853     }
1854   else if (section_is_p (sectp->name, &names->str))
1855     {
1856       dwarf2_per_objfile->str.asection = sectp;
1857       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1858     }
1859   else if (section_is_p (sectp->name, &names->addr))
1860     {
1861       dwarf2_per_objfile->addr.asection = sectp;
1862       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1863     }
1864   else if (section_is_p (sectp->name, &names->frame))
1865     {
1866       dwarf2_per_objfile->frame.asection = sectp;
1867       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1868     }
1869   else if (section_is_p (sectp->name, &names->eh_frame))
1870     {
1871       dwarf2_per_objfile->eh_frame.asection = sectp;
1872       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1873     }
1874   else if (section_is_p (sectp->name, &names->ranges))
1875     {
1876       dwarf2_per_objfile->ranges.asection = sectp;
1877       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1878     }
1879   else if (section_is_p (sectp->name, &names->types))
1880     {
1881       struct dwarf2_section_info type_section;
1882
1883       memset (&type_section, 0, sizeof (type_section));
1884       type_section.asection = sectp;
1885       type_section.size = bfd_get_section_size (sectp);
1886
1887       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1888                      &type_section);
1889     }
1890   else if (section_is_p (sectp->name, &names->gdb_index))
1891     {
1892       dwarf2_per_objfile->gdb_index.asection = sectp;
1893       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1894     }
1895
1896   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1897       && bfd_section_vma (abfd, sectp) == 0)
1898     dwarf2_per_objfile->has_section_at_zero = 1;
1899 }
1900
1901 /* A helper function that decides whether a section is empty,
1902    or not present.  */
1903
1904 static int
1905 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1906 {
1907   return info->asection == NULL || info->size == 0;
1908 }
1909
1910 /* Read the contents of the section INFO.
1911    OBJFILE is the main object file, but not necessarily the file where
1912    the section comes from.  E.g., for DWO files INFO->asection->owner
1913    is the bfd of the DWO file.
1914    If the section is compressed, uncompress it before returning.  */
1915
1916 static void
1917 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1918 {
1919   asection *sectp = info->asection;
1920   bfd *abfd;
1921   gdb_byte *buf, *retbuf;
1922   unsigned char header[4];
1923
1924   if (info->readin)
1925     return;
1926   info->buffer = NULL;
1927   info->readin = 1;
1928
1929   if (dwarf2_section_empty_p (info))
1930     return;
1931
1932   abfd = sectp->owner;
1933
1934   /* If the section has relocations, we must read it ourselves.
1935      Otherwise we attach it to the BFD.  */
1936   if ((sectp->flags & SEC_RELOC) == 0)
1937     {
1938       const gdb_byte *bytes = gdb_bfd_map_section (sectp, &info->size);
1939
1940       /* We have to cast away const here for historical reasons.
1941          Fixing dwarf2read to be const-correct would be quite nice.  */
1942       info->buffer = (gdb_byte *) bytes;
1943       return;
1944     }
1945
1946   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1947   info->buffer = buf;
1948
1949   /* When debugging .o files, we may need to apply relocations; see
1950      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1951      We never compress sections in .o files, so we only need to
1952      try this when the section is not compressed.  */
1953   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1954   if (retbuf != NULL)
1955     {
1956       info->buffer = retbuf;
1957       return;
1958     }
1959
1960   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1961       || bfd_bread (buf, info->size, abfd) != info->size)
1962     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1963            bfd_get_filename (abfd));
1964 }
1965
1966 /* A helper function that returns the size of a section in a safe way.
1967    If you are positive that the section has been read before using the
1968    size, then it is safe to refer to the dwarf2_section_info object's
1969    "size" field directly.  In other cases, you must call this
1970    function, because for compressed sections the size field is not set
1971    correctly until the section has been read.  */
1972
1973 static bfd_size_type
1974 dwarf2_section_size (struct objfile *objfile,
1975                      struct dwarf2_section_info *info)
1976 {
1977   if (!info->readin)
1978     dwarf2_read_section (objfile, info);
1979   return info->size;
1980 }
1981
1982 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1983    SECTION_NAME.  */
1984
1985 void
1986 dwarf2_get_section_info (struct objfile *objfile,
1987                          enum dwarf2_section_enum sect,
1988                          asection **sectp, gdb_byte **bufp,
1989                          bfd_size_type *sizep)
1990 {
1991   struct dwarf2_per_objfile *data
1992     = objfile_data (objfile, dwarf2_objfile_data_key);
1993   struct dwarf2_section_info *info;
1994
1995   /* We may see an objfile without any DWARF, in which case we just
1996      return nothing.  */
1997   if (data == NULL)
1998     {
1999       *sectp = NULL;
2000       *bufp = NULL;
2001       *sizep = 0;
2002       return;
2003     }
2004   switch (sect)
2005     {
2006     case DWARF2_DEBUG_FRAME:
2007       info = &data->frame;
2008       break;
2009     case DWARF2_EH_FRAME:
2010       info = &data->eh_frame;
2011       break;
2012     default:
2013       gdb_assert_not_reached ("unexpected section");
2014     }
2015
2016   dwarf2_read_section (objfile, info);
2017
2018   *sectp = info->asection;
2019   *bufp = info->buffer;
2020   *sizep = info->size;
2021 }
2022
2023 /* A helper function to find the sections for a .dwz file.  */
2024
2025 static void
2026 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2027 {
2028   struct dwz_file *dwz_file = arg;
2029
2030   /* Note that we only support the standard ELF names, because .dwz
2031      is ELF-only (at the time of writing).  */
2032   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2033     {
2034       dwz_file->abbrev.asection = sectp;
2035       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2036     }
2037   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2038     {
2039       dwz_file->info.asection = sectp;
2040       dwz_file->info.size = bfd_get_section_size (sectp);
2041     }
2042   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2043     {
2044       dwz_file->str.asection = sectp;
2045       dwz_file->str.size = bfd_get_section_size (sectp);
2046     }
2047   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2048     {
2049       dwz_file->line.asection = sectp;
2050       dwz_file->line.size = bfd_get_section_size (sectp);
2051     }
2052   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2053     {
2054       dwz_file->macro.asection = sectp;
2055       dwz_file->macro.size = bfd_get_section_size (sectp);
2056     }
2057   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2058     {
2059       dwz_file->gdb_index.asection = sectp;
2060       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2061     }
2062 }
2063
2064 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2065    cannot be found.  */
2066
2067 static struct dwz_file *
2068 dwarf2_get_dwz_file (void)
2069 {
2070   bfd *abfd, *dwz_bfd;
2071   asection *section;
2072   gdb_byte *data;
2073   struct cleanup *cleanup;
2074   const char *filename;
2075   struct dwz_file *result;
2076
2077   if (dwarf2_per_objfile->dwz_file != NULL)
2078     return dwarf2_per_objfile->dwz_file;
2079
2080   abfd = dwarf2_per_objfile->objfile->obfd;
2081   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2082   if (section == NULL)
2083     error (_("could not find '.gnu_debugaltlink' section"));
2084   if (!bfd_malloc_and_get_section (abfd, section, &data))
2085     error (_("could not read '.gnu_debugaltlink' section: %s"),
2086            bfd_errmsg (bfd_get_error ()));
2087   cleanup = make_cleanup (xfree, data);
2088
2089   filename = data;
2090   if (!IS_ABSOLUTE_PATH (filename))
2091     {
2092       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2093       char *rel;
2094
2095       make_cleanup (xfree, abs);
2096       abs = ldirname (abs);
2097       make_cleanup (xfree, abs);
2098
2099       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2100       make_cleanup (xfree, rel);
2101       filename = rel;
2102     }
2103
2104   /* The format is just a NUL-terminated file name, followed by the
2105      build-id.  For now, though, we ignore the build-id.  */
2106   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2107   if (dwz_bfd == NULL)
2108     error (_("could not read '%s': %s"), filename,
2109            bfd_errmsg (bfd_get_error ()));
2110
2111   if (!bfd_check_format (dwz_bfd, bfd_object))
2112     {
2113       gdb_bfd_unref (dwz_bfd);
2114       error (_("file '%s' was not usable: %s"), filename,
2115              bfd_errmsg (bfd_get_error ()));
2116     }
2117
2118   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2119                            struct dwz_file);
2120   result->dwz_bfd = dwz_bfd;
2121
2122   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2123
2124   do_cleanups (cleanup);
2125
2126   dwarf2_per_objfile->dwz_file = result;
2127   return result;
2128 }
2129 \f
2130 /* DWARF quick_symbols_functions support.  */
2131
2132 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2133    unique line tables, so we maintain a separate table of all .debug_line
2134    derived entries to support the sharing.
2135    All the quick functions need is the list of file names.  We discard the
2136    line_header when we're done and don't need to record it here.  */
2137 struct quick_file_names
2138 {
2139   /* The data used to construct the hash key.  */
2140   struct stmt_list_hash hash;
2141
2142   /* The number of entries in file_names, real_names.  */
2143   unsigned int num_file_names;
2144
2145   /* The file names from the line table, after being run through
2146      file_full_name.  */
2147   const char **file_names;
2148
2149   /* The file names from the line table after being run through
2150      gdb_realpath.  These are computed lazily.  */
2151   const char **real_names;
2152 };
2153
2154 /* When using the index (and thus not using psymtabs), each CU has an
2155    object of this type.  This is used to hold information needed by
2156    the various "quick" methods.  */
2157 struct dwarf2_per_cu_quick_data
2158 {
2159   /* The file table.  This can be NULL if there was no file table
2160      or it's currently not read in.
2161      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2162   struct quick_file_names *file_names;
2163
2164   /* The corresponding symbol table.  This is NULL if symbols for this
2165      CU have not yet been read.  */
2166   struct symtab *symtab;
2167
2168   /* A temporary mark bit used when iterating over all CUs in
2169      expand_symtabs_matching.  */
2170   unsigned int mark : 1;
2171
2172   /* True if we've tried to read the file table and found there isn't one.
2173      There will be no point in trying to read it again next time.  */
2174   unsigned int no_file_data : 1;
2175 };
2176
2177 /* Utility hash function for a stmt_list_hash.  */
2178
2179 static hashval_t
2180 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2181 {
2182   hashval_t v = 0;
2183
2184   if (stmt_list_hash->dwo_unit != NULL)
2185     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2186   v += stmt_list_hash->line_offset.sect_off;
2187   return v;
2188 }
2189
2190 /* Utility equality function for a stmt_list_hash.  */
2191
2192 static int
2193 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2194                     const struct stmt_list_hash *rhs)
2195 {
2196   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2197     return 0;
2198   if (lhs->dwo_unit != NULL
2199       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2200     return 0;
2201
2202   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2203 }
2204
2205 /* Hash function for a quick_file_names.  */
2206
2207 static hashval_t
2208 hash_file_name_entry (const void *e)
2209 {
2210   const struct quick_file_names *file_data = e;
2211
2212   return hash_stmt_list_entry (&file_data->hash);
2213 }
2214
2215 /* Equality function for a quick_file_names.  */
2216
2217 static int
2218 eq_file_name_entry (const void *a, const void *b)
2219 {
2220   const struct quick_file_names *ea = a;
2221   const struct quick_file_names *eb = b;
2222
2223   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2224 }
2225
2226 /* Delete function for a quick_file_names.  */
2227
2228 static void
2229 delete_file_name_entry (void *e)
2230 {
2231   struct quick_file_names *file_data = e;
2232   int i;
2233
2234   for (i = 0; i < file_data->num_file_names; ++i)
2235     {
2236       xfree ((void*) file_data->file_names[i]);
2237       if (file_data->real_names)
2238         xfree ((void*) file_data->real_names[i]);
2239     }
2240
2241   /* The space for the struct itself lives on objfile_obstack,
2242      so we don't free it here.  */
2243 }
2244
2245 /* Create a quick_file_names hash table.  */
2246
2247 static htab_t
2248 create_quick_file_names_table (unsigned int nr_initial_entries)
2249 {
2250   return htab_create_alloc (nr_initial_entries,
2251                             hash_file_name_entry, eq_file_name_entry,
2252                             delete_file_name_entry, xcalloc, xfree);
2253 }
2254
2255 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2256    have to be created afterwards.  You should call age_cached_comp_units after
2257    processing PER_CU->CU.  dw2_setup must have been already called.  */
2258
2259 static void
2260 load_cu (struct dwarf2_per_cu_data *per_cu)
2261 {
2262   if (per_cu->is_debug_types)
2263     load_full_type_unit (per_cu);
2264   else
2265     load_full_comp_unit (per_cu, language_minimal);
2266
2267   gdb_assert (per_cu->cu != NULL);
2268
2269   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2270 }
2271
2272 /* Read in the symbols for PER_CU.  */
2273
2274 static void
2275 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2276 {
2277   struct cleanup *back_to;
2278
2279   /* Skip type_unit_groups, reading the type units they contain
2280      is handled elsewhere.  */
2281   if (IS_TYPE_UNIT_GROUP (per_cu))
2282     return;
2283
2284   back_to = make_cleanup (dwarf2_release_queue, NULL);
2285
2286   if (dwarf2_per_objfile->using_index
2287       ? per_cu->v.quick->symtab == NULL
2288       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2289     {
2290       queue_comp_unit (per_cu, language_minimal);
2291       load_cu (per_cu);
2292     }
2293
2294   process_queue ();
2295
2296   /* Age the cache, releasing compilation units that have not
2297      been used recently.  */
2298   age_cached_comp_units ();
2299
2300   do_cleanups (back_to);
2301 }
2302
2303 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2304    the objfile from which this CU came.  Returns the resulting symbol
2305    table.  */
2306
2307 static struct symtab *
2308 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2309 {
2310   gdb_assert (dwarf2_per_objfile->using_index);
2311   if (!per_cu->v.quick->symtab)
2312     {
2313       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2314       increment_reading_symtab ();
2315       dw2_do_instantiate_symtab (per_cu);
2316       process_cu_includes ();
2317       do_cleanups (back_to);
2318     }
2319   return per_cu->v.quick->symtab;
2320 }
2321
2322 /* Return the CU given its index.
2323
2324    This is intended for loops like:
2325
2326    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2327                     + dwarf2_per_objfile->n_type_units); ++i)
2328      {
2329        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2330
2331        ...;
2332      }
2333 */
2334
2335 static struct dwarf2_per_cu_data *
2336 dw2_get_cu (int index)
2337 {
2338   if (index >= dwarf2_per_objfile->n_comp_units)
2339     {
2340       index -= dwarf2_per_objfile->n_comp_units;
2341       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2342       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2343     }
2344
2345   return dwarf2_per_objfile->all_comp_units[index];
2346 }
2347
2348 /* Return the primary CU given its index.
2349    The difference between this function and dw2_get_cu is in the handling
2350    of type units (TUs).  Here we return the type_unit_group object.
2351
2352    This is intended for loops like:
2353
2354    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2355                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2356      {
2357        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2358
2359        ...;
2360      }
2361 */
2362
2363 static struct dwarf2_per_cu_data *
2364 dw2_get_primary_cu (int index)
2365 {
2366   if (index >= dwarf2_per_objfile->n_comp_units)
2367     {
2368       index -= dwarf2_per_objfile->n_comp_units;
2369       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2370       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2371     }
2372
2373   return dwarf2_per_objfile->all_comp_units[index];
2374 }
2375
2376 /* A helper for create_cus_from_index that handles a given list of
2377    CUs.  */
2378
2379 static void
2380 create_cus_from_index_list (struct objfile *objfile,
2381                             const gdb_byte *cu_list, offset_type n_elements,
2382                             struct dwarf2_section_info *section,
2383                             int is_dwz,
2384                             int base_offset)
2385 {
2386   offset_type i;
2387
2388   for (i = 0; i < n_elements; i += 2)
2389     {
2390       struct dwarf2_per_cu_data *the_cu;
2391       ULONGEST offset, length;
2392
2393       gdb_static_assert (sizeof (ULONGEST) >= 8);
2394       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2395       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2396       cu_list += 2 * 8;
2397
2398       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2399                                struct dwarf2_per_cu_data);
2400       the_cu->offset.sect_off = offset;
2401       the_cu->length = length;
2402       the_cu->objfile = objfile;
2403       the_cu->info_or_types_section = section;
2404       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2405                                         struct dwarf2_per_cu_quick_data);
2406       the_cu->is_dwz = is_dwz;
2407       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2408     }
2409 }
2410
2411 /* Read the CU list from the mapped index, and use it to create all
2412    the CU objects for this objfile.  */
2413
2414 static void
2415 create_cus_from_index (struct objfile *objfile,
2416                        const gdb_byte *cu_list, offset_type cu_list_elements,
2417                        const gdb_byte *dwz_list, offset_type dwz_elements)
2418 {
2419   struct dwz_file *dwz;
2420
2421   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2422   dwarf2_per_objfile->all_comp_units
2423     = obstack_alloc (&objfile->objfile_obstack,
2424                      dwarf2_per_objfile->n_comp_units
2425                      * sizeof (struct dwarf2_per_cu_data *));
2426
2427   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2428                               &dwarf2_per_objfile->info, 0, 0);
2429
2430   if (dwz_elements == 0)
2431     return;
2432
2433   dwz = dwarf2_get_dwz_file ();
2434   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2435                               cu_list_elements / 2);
2436 }
2437
2438 /* Create the signatured type hash table from the index.  */
2439
2440 static void
2441 create_signatured_type_table_from_index (struct objfile *objfile,
2442                                          struct dwarf2_section_info *section,
2443                                          const gdb_byte *bytes,
2444                                          offset_type elements)
2445 {
2446   offset_type i;
2447   htab_t sig_types_hash;
2448
2449   dwarf2_per_objfile->n_type_units = elements / 3;
2450   dwarf2_per_objfile->all_type_units
2451     = obstack_alloc (&objfile->objfile_obstack,
2452                      dwarf2_per_objfile->n_type_units
2453                      * sizeof (struct signatured_type *));
2454
2455   sig_types_hash = allocate_signatured_type_table (objfile);
2456
2457   for (i = 0; i < elements; i += 3)
2458     {
2459       struct signatured_type *sig_type;
2460       ULONGEST offset, type_offset_in_tu, signature;
2461       void **slot;
2462
2463       gdb_static_assert (sizeof (ULONGEST) >= 8);
2464       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2465       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2466                                                     BFD_ENDIAN_LITTLE);
2467       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2468       bytes += 3 * 8;
2469
2470       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2471                                  struct signatured_type);
2472       sig_type->signature = signature;
2473       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2474       sig_type->per_cu.is_debug_types = 1;
2475       sig_type->per_cu.info_or_types_section = section;
2476       sig_type->per_cu.offset.sect_off = offset;
2477       sig_type->per_cu.objfile = objfile;
2478       sig_type->per_cu.v.quick
2479         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2480                           struct dwarf2_per_cu_quick_data);
2481
2482       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2483       *slot = sig_type;
2484
2485       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2486     }
2487
2488   dwarf2_per_objfile->signatured_types = sig_types_hash;
2489 }
2490
2491 /* Read the address map data from the mapped index, and use it to
2492    populate the objfile's psymtabs_addrmap.  */
2493
2494 static void
2495 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2496 {
2497   const gdb_byte *iter, *end;
2498   struct obstack temp_obstack;
2499   struct addrmap *mutable_map;
2500   struct cleanup *cleanup;
2501   CORE_ADDR baseaddr;
2502
2503   obstack_init (&temp_obstack);
2504   cleanup = make_cleanup_obstack_free (&temp_obstack);
2505   mutable_map = addrmap_create_mutable (&temp_obstack);
2506
2507   iter = index->address_table;
2508   end = iter + index->address_table_size;
2509
2510   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2511
2512   while (iter < end)
2513     {
2514       ULONGEST hi, lo, cu_index;
2515       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2516       iter += 8;
2517       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2518       iter += 8;
2519       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2520       iter += 4;
2521       
2522       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2523                          dw2_get_cu (cu_index));
2524     }
2525
2526   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2527                                                     &objfile->objfile_obstack);
2528   do_cleanups (cleanup);
2529 }
2530
2531 /* The hash function for strings in the mapped index.  This is the same as
2532    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2533    implementation.  This is necessary because the hash function is tied to the
2534    format of the mapped index file.  The hash values do not have to match with
2535    SYMBOL_HASH_NEXT.
2536    
2537    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2538
2539 static hashval_t
2540 mapped_index_string_hash (int index_version, const void *p)
2541 {
2542   const unsigned char *str = (const unsigned char *) p;
2543   hashval_t r = 0;
2544   unsigned char c;
2545
2546   while ((c = *str++) != 0)
2547     {
2548       if (index_version >= 5)
2549         c = tolower (c);
2550       r = r * 67 + c - 113;
2551     }
2552
2553   return r;
2554 }
2555
2556 /* Find a slot in the mapped index INDEX for the object named NAME.
2557    If NAME is found, set *VEC_OUT to point to the CU vector in the
2558    constant pool and return 1.  If NAME cannot be found, return 0.  */
2559
2560 static int
2561 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2562                           offset_type **vec_out)
2563 {
2564   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2565   offset_type hash;
2566   offset_type slot, step;
2567   int (*cmp) (const char *, const char *);
2568
2569   if (current_language->la_language == language_cplus
2570       || current_language->la_language == language_java
2571       || current_language->la_language == language_fortran)
2572     {
2573       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2574          not contain any.  */
2575       const char *paren = strchr (name, '(');
2576
2577       if (paren)
2578         {
2579           char *dup;
2580
2581           dup = xmalloc (paren - name + 1);
2582           memcpy (dup, name, paren - name);
2583           dup[paren - name] = 0;
2584
2585           make_cleanup (xfree, dup);
2586           name = dup;
2587         }
2588     }
2589
2590   /* Index version 4 did not support case insensitive searches.  But the
2591      indices for case insensitive languages are built in lowercase, therefore
2592      simulate our NAME being searched is also lowercased.  */
2593   hash = mapped_index_string_hash ((index->version == 4
2594                                     && case_sensitivity == case_sensitive_off
2595                                     ? 5 : index->version),
2596                                    name);
2597
2598   slot = hash & (index->symbol_table_slots - 1);
2599   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2600   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2601
2602   for (;;)
2603     {
2604       /* Convert a slot number to an offset into the table.  */
2605       offset_type i = 2 * slot;
2606       const char *str;
2607       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2608         {
2609           do_cleanups (back_to);
2610           return 0;
2611         }
2612
2613       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2614       if (!cmp (name, str))
2615         {
2616           *vec_out = (offset_type *) (index->constant_pool
2617                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2618           do_cleanups (back_to);
2619           return 1;
2620         }
2621
2622       slot = (slot + step) & (index->symbol_table_slots - 1);
2623     }
2624 }
2625
2626 /* A helper function that reads the .gdb_index from SECTION and fills
2627    in MAP.  FILENAME is the name of the file containing the section;
2628    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2629    ok to use deprecated sections.
2630
2631    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2632    out parameters that are filled in with information about the CU and
2633    TU lists in the section.
2634
2635    Returns 1 if all went well, 0 otherwise.  */
2636
2637 static int
2638 read_index_from_section (struct objfile *objfile,
2639                          const char *filename,
2640                          int deprecated_ok,
2641                          struct dwarf2_section_info *section,
2642                          struct mapped_index *map,
2643                          const gdb_byte **cu_list,
2644                          offset_type *cu_list_elements,
2645                          const gdb_byte **types_list,
2646                          offset_type *types_list_elements)
2647 {
2648   char *addr;
2649   offset_type version;
2650   offset_type *metadata;
2651   int i;
2652
2653   if (dwarf2_section_empty_p (section))
2654     return 0;
2655
2656   /* Older elfutils strip versions could keep the section in the main
2657      executable while splitting it for the separate debug info file.  */
2658   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2659     return 0;
2660
2661   dwarf2_read_section (objfile, section);
2662
2663   addr = section->buffer;
2664   /* Version check.  */
2665   version = MAYBE_SWAP (*(offset_type *) addr);
2666   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2667      causes the index to behave very poorly for certain requests.  Version 3
2668      contained incomplete addrmap.  So, it seems better to just ignore such
2669      indices.  */
2670   if (version < 4)
2671     {
2672       static int warning_printed = 0;
2673       if (!warning_printed)
2674         {
2675           warning (_("Skipping obsolete .gdb_index section in %s."),
2676                    filename);
2677           warning_printed = 1;
2678         }
2679       return 0;
2680     }
2681   /* Index version 4 uses a different hash function than index version
2682      5 and later.
2683
2684      Versions earlier than 6 did not emit psymbols for inlined
2685      functions.  Using these files will cause GDB not to be able to
2686      set breakpoints on inlined functions by name, so we ignore these
2687      indices unless the user has done
2688      "set use-deprecated-index-sections on".  */
2689   if (version < 6 && !deprecated_ok)
2690     {
2691       static int warning_printed = 0;
2692       if (!warning_printed)
2693         {
2694           warning (_("\
2695 Skipping deprecated .gdb_index section in %s.\n\
2696 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2697 to use the section anyway."),
2698                    filename);
2699           warning_printed = 1;
2700         }
2701       return 0;
2702     }
2703   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2704      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2705      we can't distinguish gdb-generated indices from gold-generated ones, so
2706      nothing to do here.  */
2707
2708   /* Indexes with higher version than the one supported by GDB may be no
2709      longer backward compatible.  */
2710   if (version > 8)
2711     return 0;
2712
2713   map->version = version;
2714   map->total_size = section->size;
2715
2716   metadata = (offset_type *) (addr + sizeof (offset_type));
2717
2718   i = 0;
2719   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2720   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2721                        / 8);
2722   ++i;
2723
2724   *types_list = addr + MAYBE_SWAP (metadata[i]);
2725   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2726                            - MAYBE_SWAP (metadata[i]))
2727                           / 8);
2728   ++i;
2729
2730   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2731   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2732                              - MAYBE_SWAP (metadata[i]));
2733   ++i;
2734
2735   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2736   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2737                               - MAYBE_SWAP (metadata[i]))
2738                              / (2 * sizeof (offset_type)));
2739   ++i;
2740
2741   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2742
2743   return 1;
2744 }
2745
2746
2747 /* Read the index file.  If everything went ok, initialize the "quick"
2748    elements of all the CUs and return 1.  Otherwise, return 0.  */
2749
2750 static int
2751 dwarf2_read_index (struct objfile *objfile)
2752 {
2753   struct mapped_index local_map, *map;
2754   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2755   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2756
2757   if (!read_index_from_section (objfile, objfile->name,
2758                                 use_deprecated_index_sections,
2759                                 &dwarf2_per_objfile->gdb_index, &local_map,
2760                                 &cu_list, &cu_list_elements,
2761                                 &types_list, &types_list_elements))
2762     return 0;
2763
2764   /* Don't use the index if it's empty.  */
2765   if (local_map.symbol_table_slots == 0)
2766     return 0;
2767
2768   /* If there is a .dwz file, read it so we can get its CU list as
2769      well.  */
2770   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2771     {
2772       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2773       struct mapped_index dwz_map;
2774       const gdb_byte *dwz_types_ignore;
2775       offset_type dwz_types_elements_ignore;
2776
2777       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2778                                     1,
2779                                     &dwz->gdb_index, &dwz_map,
2780                                     &dwz_list, &dwz_list_elements,
2781                                     &dwz_types_ignore,
2782                                     &dwz_types_elements_ignore))
2783         {
2784           warning (_("could not read '.gdb_index' section from %s; skipping"),
2785                    bfd_get_filename (dwz->dwz_bfd));
2786           return 0;
2787         }
2788     }
2789
2790   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2791                          dwz_list_elements);
2792
2793   if (types_list_elements)
2794     {
2795       struct dwarf2_section_info *section;
2796
2797       /* We can only handle a single .debug_types when we have an
2798          index.  */
2799       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2800         return 0;
2801
2802       section = VEC_index (dwarf2_section_info_def,
2803                            dwarf2_per_objfile->types, 0);
2804
2805       create_signatured_type_table_from_index (objfile, section, types_list,
2806                                                types_list_elements);
2807     }
2808
2809   create_addrmap_from_index (objfile, &local_map);
2810
2811   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2812   *map = local_map;
2813
2814   dwarf2_per_objfile->index_table = map;
2815   dwarf2_per_objfile->using_index = 1;
2816   dwarf2_per_objfile->quick_file_names_table =
2817     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2818
2819   return 1;
2820 }
2821
2822 /* A helper for the "quick" functions which sets the global
2823    dwarf2_per_objfile according to OBJFILE.  */
2824
2825 static void
2826 dw2_setup (struct objfile *objfile)
2827 {
2828   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2829   gdb_assert (dwarf2_per_objfile);
2830 }
2831
2832 /* die_reader_func for dw2_get_file_names.  */
2833
2834 static void
2835 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2836                            gdb_byte *info_ptr,
2837                            struct die_info *comp_unit_die,
2838                            int has_children,
2839                            void *data)
2840 {
2841   struct dwarf2_cu *cu = reader->cu;
2842   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2843   struct objfile *objfile = dwarf2_per_objfile->objfile;
2844   struct dwarf2_per_cu_data *lh_cu;
2845   struct line_header *lh;
2846   struct attribute *attr;
2847   int i;
2848   const char *name, *comp_dir;
2849   void **slot;
2850   struct quick_file_names *qfn;
2851   unsigned int line_offset;
2852
2853   /* Our callers never want to match partial units -- instead they
2854      will match the enclosing full CU.  */
2855   if (comp_unit_die->tag == DW_TAG_partial_unit)
2856     {
2857       this_cu->v.quick->no_file_data = 1;
2858       return;
2859     }
2860
2861   /* If we're reading the line header for TUs, store it in the "per_cu"
2862      for tu_group.  */
2863   if (this_cu->is_debug_types)
2864     {
2865       struct type_unit_group *tu_group = data;
2866
2867       gdb_assert (tu_group != NULL);
2868       lh_cu = &tu_group->per_cu;
2869     }
2870   else
2871     lh_cu = this_cu;
2872
2873   lh = NULL;
2874   slot = NULL;
2875   line_offset = 0;
2876
2877   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2878   if (attr)
2879     {
2880       struct quick_file_names find_entry;
2881
2882       line_offset = DW_UNSND (attr);
2883
2884       /* We may have already read in this line header (TU line header sharing).
2885          If we have we're done.  */
2886       find_entry.hash.dwo_unit = cu->dwo_unit;
2887       find_entry.hash.line_offset.sect_off = line_offset;
2888       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2889                              &find_entry, INSERT);
2890       if (*slot != NULL)
2891         {
2892           lh_cu->v.quick->file_names = *slot;
2893           return;
2894         }
2895
2896       lh = dwarf_decode_line_header (line_offset, cu);
2897     }
2898   if (lh == NULL)
2899     {
2900       lh_cu->v.quick->no_file_data = 1;
2901       return;
2902     }
2903
2904   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2905   qfn->hash.dwo_unit = cu->dwo_unit;
2906   qfn->hash.line_offset.sect_off = line_offset;
2907   gdb_assert (slot != NULL);
2908   *slot = qfn;
2909
2910   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2911
2912   qfn->num_file_names = lh->num_file_names;
2913   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2914                                    lh->num_file_names * sizeof (char *));
2915   for (i = 0; i < lh->num_file_names; ++i)
2916     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2917   qfn->real_names = NULL;
2918
2919   free_line_header (lh);
2920
2921   lh_cu->v.quick->file_names = qfn;
2922 }
2923
2924 /* A helper for the "quick" functions which attempts to read the line
2925    table for THIS_CU.  */
2926
2927 static struct quick_file_names *
2928 dw2_get_file_names (struct objfile *objfile,
2929                     struct dwarf2_per_cu_data *this_cu)
2930 {
2931   /* For TUs this should only be called on the parent group.  */
2932   if (this_cu->is_debug_types)
2933     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2934
2935   if (this_cu->v.quick->file_names != NULL)
2936     return this_cu->v.quick->file_names;
2937   /* If we know there is no line data, no point in looking again.  */
2938   if (this_cu->v.quick->no_file_data)
2939     return NULL;
2940
2941   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2942      in the stub for CUs, there's is no need to lookup the DWO file.
2943      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2944      DWO file.  */
2945   if (this_cu->is_debug_types)
2946     {
2947       struct type_unit_group *tu_group = this_cu->type_unit_group;
2948
2949       init_cutu_and_read_dies (tu_group->t.first_tu, NULL, 0, 0,
2950                                dw2_get_file_names_reader, tu_group);
2951     }
2952   else
2953     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2954
2955   if (this_cu->v.quick->no_file_data)
2956     return NULL;
2957   return this_cu->v.quick->file_names;
2958 }
2959
2960 /* A helper for the "quick" functions which computes and caches the
2961    real path for a given file name from the line table.  */
2962
2963 static const char *
2964 dw2_get_real_path (struct objfile *objfile,
2965                    struct quick_file_names *qfn, int index)
2966 {
2967   if (qfn->real_names == NULL)
2968     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2969                                       qfn->num_file_names, sizeof (char *));
2970
2971   if (qfn->real_names[index] == NULL)
2972     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2973
2974   return qfn->real_names[index];
2975 }
2976
2977 static struct symtab *
2978 dw2_find_last_source_symtab (struct objfile *objfile)
2979 {
2980   int index;
2981
2982   dw2_setup (objfile);
2983   index = dwarf2_per_objfile->n_comp_units - 1;
2984   return dw2_instantiate_symtab (dw2_get_cu (index));
2985 }
2986
2987 /* Traversal function for dw2_forget_cached_source_info.  */
2988
2989 static int
2990 dw2_free_cached_file_names (void **slot, void *info)
2991 {
2992   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2993
2994   if (file_data->real_names)
2995     {
2996       int i;
2997
2998       for (i = 0; i < file_data->num_file_names; ++i)
2999         {
3000           xfree ((void*) file_data->real_names[i]);
3001           file_data->real_names[i] = NULL;
3002         }
3003     }
3004
3005   return 1;
3006 }
3007
3008 static void
3009 dw2_forget_cached_source_info (struct objfile *objfile)
3010 {
3011   dw2_setup (objfile);
3012
3013   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3014                           dw2_free_cached_file_names, NULL);
3015 }
3016
3017 /* Helper function for dw2_map_symtabs_matching_filename that expands
3018    the symtabs and calls the iterator.  */
3019
3020 static int
3021 dw2_map_expand_apply (struct objfile *objfile,
3022                       struct dwarf2_per_cu_data *per_cu,
3023                       const char *name,
3024                       const char *full_path, const char *real_path,
3025                       int (*callback) (struct symtab *, void *),
3026                       void *data)
3027 {
3028   struct symtab *last_made = objfile->symtabs;
3029
3030   /* Don't visit already-expanded CUs.  */
3031   if (per_cu->v.quick->symtab)
3032     return 0;
3033
3034   /* This may expand more than one symtab, and we want to iterate over
3035      all of them.  */
3036   dw2_instantiate_symtab (per_cu);
3037
3038   return iterate_over_some_symtabs (name, full_path, real_path, callback, data,
3039                                     objfile->symtabs, last_made);
3040 }
3041
3042 /* Implementation of the map_symtabs_matching_filename method.  */
3043
3044 static int
3045 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3046                                    const char *full_path, const char *real_path,
3047                                    int (*callback) (struct symtab *, void *),
3048                                    void *data)
3049 {
3050   int i;
3051   const char *name_basename = lbasename (name);
3052   int is_abs = IS_ABSOLUTE_PATH (name);
3053
3054   dw2_setup (objfile);
3055
3056   /* The rule is CUs specify all the files, including those used by
3057      any TU, so there's no need to scan TUs here.  */
3058
3059   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3060     {
3061       int j;
3062       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3063       struct quick_file_names *file_data;
3064
3065       /* We only need to look at symtabs not already expanded.  */
3066       if (per_cu->v.quick->symtab)
3067         continue;
3068
3069       file_data = dw2_get_file_names (objfile, per_cu);
3070       if (file_data == NULL)
3071         continue;
3072
3073       for (j = 0; j < file_data->num_file_names; ++j)
3074         {
3075           const char *this_name = file_data->file_names[j];
3076
3077           if (FILENAME_CMP (name, this_name) == 0
3078               || (!is_abs && compare_filenames_for_search (this_name, name)))
3079             {
3080               if (dw2_map_expand_apply (objfile, per_cu,
3081                                         name, full_path, real_path,
3082                                         callback, data))
3083                 return 1;
3084             }
3085
3086           /* Before we invoke realpath, which can get expensive when many
3087              files are involved, do a quick comparison of the basenames.  */
3088           if (! basenames_may_differ
3089               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3090             continue;
3091
3092           if (full_path != NULL)
3093             {
3094               const char *this_real_name = dw2_get_real_path (objfile,
3095                                                               file_data, j);
3096
3097               if (this_real_name != NULL
3098                   && (FILENAME_CMP (full_path, this_real_name) == 0
3099                       || (!is_abs
3100                           && compare_filenames_for_search (this_real_name,
3101                                                            name))))
3102                 {
3103                   if (dw2_map_expand_apply (objfile, per_cu,
3104                                             name, full_path, real_path,
3105                                             callback, data))
3106                     return 1;
3107                 }
3108             }
3109
3110           if (real_path != NULL)
3111             {
3112               const char *this_real_name = dw2_get_real_path (objfile,
3113                                                               file_data, j);
3114
3115               if (this_real_name != NULL
3116                   && (FILENAME_CMP (real_path, this_real_name) == 0
3117                       || (!is_abs
3118                           && compare_filenames_for_search (this_real_name,
3119                                                            name))))
3120                 {
3121                   if (dw2_map_expand_apply (objfile, per_cu,
3122                                             name, full_path, real_path,
3123                                             callback, data))
3124                     return 1;
3125                 }
3126             }
3127         }
3128     }
3129
3130   return 0;
3131 }
3132
3133 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3134
3135 struct dw2_symtab_iterator
3136 {
3137   /* The internalized form of .gdb_index.  */
3138   struct mapped_index *index;
3139   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3140   int want_specific_block;
3141   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3142      Unused if !WANT_SPECIFIC_BLOCK.  */
3143   int block_index;
3144   /* The kind of symbol we're looking for.  */
3145   domain_enum domain;
3146   /* The list of CUs from the index entry of the symbol,
3147      or NULL if not found.  */
3148   offset_type *vec;
3149   /* The next element in VEC to look at.  */
3150   int next;
3151   /* The number of elements in VEC, or zero if there is no match.  */
3152   int length;
3153 };
3154
3155 /* Initialize the index symtab iterator ITER.
3156    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3157    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3158
3159 static void
3160 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3161                       struct mapped_index *index,
3162                       int want_specific_block,
3163                       int block_index,
3164                       domain_enum domain,
3165                       const char *name)
3166 {
3167   iter->index = index;
3168   iter->want_specific_block = want_specific_block;
3169   iter->block_index = block_index;
3170   iter->domain = domain;
3171   iter->next = 0;
3172
3173   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3174     iter->length = MAYBE_SWAP (*iter->vec);
3175   else
3176     {
3177       iter->vec = NULL;
3178       iter->length = 0;
3179     }
3180 }
3181
3182 /* Return the next matching CU or NULL if there are no more.  */
3183
3184 static struct dwarf2_per_cu_data *
3185 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3186 {
3187   for ( ; iter->next < iter->length; ++iter->next)
3188     {
3189       offset_type cu_index_and_attrs =
3190         MAYBE_SWAP (iter->vec[iter->next + 1]);
3191       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3192       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3193       int want_static = iter->block_index != GLOBAL_BLOCK;
3194       /* This value is only valid for index versions >= 7.  */
3195       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3196       gdb_index_symbol_kind symbol_kind =
3197         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3198       /* Only check the symbol attributes if they're present.
3199          Indices prior to version 7 don't record them,
3200          and indices >= 7 may elide them for certain symbols
3201          (gold does this).  */
3202       int attrs_valid =
3203         (iter->index->version >= 7
3204          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3205
3206       /* Skip if already read in.  */
3207       if (per_cu->v.quick->symtab)
3208         continue;
3209
3210       if (attrs_valid
3211           && iter->want_specific_block
3212           && want_static != is_static)
3213         continue;
3214
3215       /* Only check the symbol's kind if it has one.  */
3216       if (attrs_valid)
3217         {
3218           switch (iter->domain)
3219             {
3220             case VAR_DOMAIN:
3221               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3222                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3223                   /* Some types are also in VAR_DOMAIN.  */
3224                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3225                 continue;
3226               break;
3227             case STRUCT_DOMAIN:
3228               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3229                 continue;
3230               break;
3231             case LABEL_DOMAIN:
3232               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3233                 continue;
3234               break;
3235             default:
3236               break;
3237             }
3238         }
3239
3240       ++iter->next;
3241       return per_cu;
3242     }
3243
3244   return NULL;
3245 }
3246
3247 static struct symtab *
3248 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3249                    const char *name, domain_enum domain)
3250 {
3251   struct symtab *stab_best = NULL;
3252   struct mapped_index *index;
3253
3254   dw2_setup (objfile);
3255
3256   index = dwarf2_per_objfile->index_table;
3257
3258   /* index is NULL if OBJF_READNOW.  */
3259   if (index)
3260     {
3261       struct dw2_symtab_iterator iter;
3262       struct dwarf2_per_cu_data *per_cu;
3263
3264       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3265
3266       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3267         {
3268           struct symbol *sym = NULL;
3269           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3270
3271           /* Some caution must be observed with overloaded functions
3272              and methods, since the index will not contain any overload
3273              information (but NAME might contain it).  */
3274           if (stab->primary)
3275             {
3276               struct blockvector *bv = BLOCKVECTOR (stab);
3277               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3278
3279               sym = lookup_block_symbol (block, name, domain);
3280             }
3281
3282           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3283             {
3284               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3285                 return stab;
3286
3287               stab_best = stab;
3288             }
3289
3290           /* Keep looking through other CUs.  */
3291         }
3292     }
3293
3294   return stab_best;
3295 }
3296
3297 static void
3298 dw2_print_stats (struct objfile *objfile)
3299 {
3300   int i, count;
3301
3302   dw2_setup (objfile);
3303   count = 0;
3304   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3305                    + dwarf2_per_objfile->n_type_units); ++i)
3306     {
3307       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3308
3309       if (!per_cu->v.quick->symtab)
3310         ++count;
3311     }
3312   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3313 }
3314
3315 static void
3316 dw2_dump (struct objfile *objfile)
3317 {
3318   /* Nothing worth printing.  */
3319 }
3320
3321 static void
3322 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3323               struct section_offsets *delta)
3324 {
3325   /* There's nothing to relocate here.  */
3326 }
3327
3328 static void
3329 dw2_expand_symtabs_for_function (struct objfile *objfile,
3330                                  const char *func_name)
3331 {
3332   struct mapped_index *index;
3333
3334   dw2_setup (objfile);
3335
3336   index = dwarf2_per_objfile->index_table;
3337
3338   /* index is NULL if OBJF_READNOW.  */
3339   if (index)
3340     {
3341       struct dw2_symtab_iterator iter;
3342       struct dwarf2_per_cu_data *per_cu;
3343
3344       /* Note: It doesn't matter what we pass for block_index here.  */
3345       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3346                             func_name);
3347
3348       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3349         dw2_instantiate_symtab (per_cu);
3350     }
3351 }
3352
3353 static void
3354 dw2_expand_all_symtabs (struct objfile *objfile)
3355 {
3356   int i;
3357
3358   dw2_setup (objfile);
3359
3360   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3361                    + dwarf2_per_objfile->n_type_units); ++i)
3362     {
3363       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3364
3365       dw2_instantiate_symtab (per_cu);
3366     }
3367 }
3368
3369 static void
3370 dw2_expand_symtabs_with_filename (struct objfile *objfile,
3371                                   const char *filename)
3372 {
3373   int i;
3374
3375   dw2_setup (objfile);
3376
3377   /* We don't need to consider type units here.
3378      This is only called for examining code, e.g. expand_line_sal.
3379      There can be an order of magnitude (or more) more type units
3380      than comp units, and we avoid them if we can.  */
3381
3382   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3383     {
3384       int j;
3385       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3386       struct quick_file_names *file_data;
3387
3388       /* We only need to look at symtabs not already expanded.  */
3389       if (per_cu->v.quick->symtab)
3390         continue;
3391
3392       file_data = dw2_get_file_names (objfile, per_cu);
3393       if (file_data == NULL)
3394         continue;
3395
3396       for (j = 0; j < file_data->num_file_names; ++j)
3397         {
3398           const char *this_name = file_data->file_names[j];
3399           if (FILENAME_CMP (this_name, filename) == 0)
3400             {
3401               dw2_instantiate_symtab (per_cu);
3402               break;
3403             }
3404         }
3405     }
3406 }
3407
3408 /* A helper function for dw2_find_symbol_file that finds the primary
3409    file name for a given CU.  This is a die_reader_func.  */
3410
3411 static void
3412 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3413                                  gdb_byte *info_ptr,
3414                                  struct die_info *comp_unit_die,
3415                                  int has_children,
3416                                  void *data)
3417 {
3418   const char **result_ptr = data;
3419   struct dwarf2_cu *cu = reader->cu;
3420   struct attribute *attr;
3421
3422   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3423   if (attr == NULL)
3424     *result_ptr = NULL;
3425   else
3426     *result_ptr = DW_STRING (attr);
3427 }
3428
3429 static const char *
3430 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3431 {
3432   struct dwarf2_per_cu_data *per_cu;
3433   offset_type *vec;
3434   const char *filename;
3435
3436   dw2_setup (objfile);
3437
3438   /* index_table is NULL if OBJF_READNOW.  */
3439   if (!dwarf2_per_objfile->index_table)
3440     {
3441       struct symtab *s;
3442
3443       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3444         {
3445           struct blockvector *bv = BLOCKVECTOR (s);
3446           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3447           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3448
3449           if (sym)
3450             return SYMBOL_SYMTAB (sym)->filename;
3451         }
3452       return NULL;
3453     }
3454
3455   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3456                                  name, &vec))
3457     return NULL;
3458
3459   /* Note that this just looks at the very first one named NAME -- but
3460      actually we are looking for a function.  find_main_filename
3461      should be rewritten so that it doesn't require a custom hook.  It
3462      could just use the ordinary symbol tables.  */
3463   /* vec[0] is the length, which must always be >0.  */
3464   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3465
3466   if (per_cu->v.quick->symtab != NULL)
3467     return per_cu->v.quick->symtab->filename;
3468
3469   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3470                            dw2_get_primary_filename_reader, &filename);
3471
3472   return filename;
3473 }
3474
3475 static void
3476 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3477                           struct objfile *objfile, int global,
3478                           int (*callback) (struct block *,
3479                                            struct symbol *, void *),
3480                           void *data, symbol_compare_ftype *match,
3481                           symbol_compare_ftype *ordered_compare)
3482 {
3483   /* Currently unimplemented; used for Ada.  The function can be called if the
3484      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3485      does not look for non-Ada symbols this function should just return.  */
3486 }
3487
3488 static void
3489 dw2_expand_symtabs_matching
3490   (struct objfile *objfile,
3491    int (*file_matcher) (const char *, void *),
3492    int (*name_matcher) (const char *, void *),
3493    enum search_domain kind,
3494    void *data)
3495 {
3496   int i;
3497   offset_type iter;
3498   struct mapped_index *index;
3499
3500   dw2_setup (objfile);
3501
3502   /* index_table is NULL if OBJF_READNOW.  */
3503   if (!dwarf2_per_objfile->index_table)
3504     return;
3505   index = dwarf2_per_objfile->index_table;
3506
3507   if (file_matcher != NULL)
3508     {
3509       struct cleanup *cleanup;
3510       htab_t visited_found, visited_not_found;
3511
3512       visited_found = htab_create_alloc (10,
3513                                          htab_hash_pointer, htab_eq_pointer,
3514                                          NULL, xcalloc, xfree);
3515       cleanup = make_cleanup_htab_delete (visited_found);
3516       visited_not_found = htab_create_alloc (10,
3517                                              htab_hash_pointer, htab_eq_pointer,
3518                                              NULL, xcalloc, xfree);
3519       make_cleanup_htab_delete (visited_not_found);
3520
3521       /* The rule is CUs specify all the files, including those used by
3522          any TU, so there's no need to scan TUs here.  */
3523
3524       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3525         {
3526           int j;
3527           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3528           struct quick_file_names *file_data;
3529           void **slot;
3530
3531           per_cu->v.quick->mark = 0;
3532
3533           /* We only need to look at symtabs not already expanded.  */
3534           if (per_cu->v.quick->symtab)
3535             continue;
3536
3537           file_data = dw2_get_file_names (objfile, per_cu);
3538           if (file_data == NULL)
3539             continue;
3540
3541           if (htab_find (visited_not_found, file_data) != NULL)
3542             continue;
3543           else if (htab_find (visited_found, file_data) != NULL)
3544             {
3545               per_cu->v.quick->mark = 1;
3546               continue;
3547             }
3548
3549           for (j = 0; j < file_data->num_file_names; ++j)
3550             {
3551               if (file_matcher (file_data->file_names[j], data))
3552                 {
3553                   per_cu->v.quick->mark = 1;
3554                   break;
3555                 }
3556             }
3557
3558           slot = htab_find_slot (per_cu->v.quick->mark
3559                                  ? visited_found
3560                                  : visited_not_found,
3561                                  file_data, INSERT);
3562           *slot = file_data;
3563         }
3564
3565       do_cleanups (cleanup);
3566     }
3567
3568   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3569     {
3570       offset_type idx = 2 * iter;
3571       const char *name;
3572       offset_type *vec, vec_len, vec_idx;
3573
3574       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3575         continue;
3576
3577       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3578
3579       if (! (*name_matcher) (name, data))
3580         continue;
3581
3582       /* The name was matched, now expand corresponding CUs that were
3583          marked.  */
3584       vec = (offset_type *) (index->constant_pool
3585                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3586       vec_len = MAYBE_SWAP (vec[0]);
3587       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3588         {
3589           struct dwarf2_per_cu_data *per_cu;
3590           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3591           gdb_index_symbol_kind symbol_kind =
3592             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3593           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3594
3595           /* Don't crash on bad data.  */
3596           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3597                            + dwarf2_per_objfile->n_type_units))
3598             continue;
3599
3600           /* Only check the symbol's kind if it has one.
3601              Indices prior to version 7 don't record it.  */
3602           if (index->version >= 7)
3603             {
3604               switch (kind)
3605                 {
3606                 case VARIABLES_DOMAIN:
3607                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3608                     continue;
3609                   break;
3610                 case FUNCTIONS_DOMAIN:
3611                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3612                     continue;
3613                   break;
3614                 case TYPES_DOMAIN:
3615                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3616                     continue;
3617                   break;
3618                 default:
3619                   break;
3620                 }
3621             }
3622
3623           per_cu = dw2_get_cu (cu_index);
3624           if (file_matcher == NULL || per_cu->v.quick->mark)
3625             dw2_instantiate_symtab (per_cu);
3626         }
3627     }
3628 }
3629
3630 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3631    symtab.  */
3632
3633 static struct symtab *
3634 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3635 {
3636   int i;
3637
3638   if (BLOCKVECTOR (symtab) != NULL
3639       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3640     return symtab;
3641
3642   if (symtab->includes == NULL)
3643     return NULL;
3644
3645   for (i = 0; symtab->includes[i]; ++i)
3646     {
3647       struct symtab *s = symtab->includes[i];
3648
3649       s = recursively_find_pc_sect_symtab (s, pc);
3650       if (s != NULL)
3651         return s;
3652     }
3653
3654   return NULL;
3655 }
3656
3657 static struct symtab *
3658 dw2_find_pc_sect_symtab (struct objfile *objfile,
3659                          struct minimal_symbol *msymbol,
3660                          CORE_ADDR pc,
3661                          struct obj_section *section,
3662                          int warn_if_readin)
3663 {
3664   struct dwarf2_per_cu_data *data;
3665   struct symtab *result;
3666
3667   dw2_setup (objfile);
3668
3669   if (!objfile->psymtabs_addrmap)
3670     return NULL;
3671
3672   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3673   if (!data)
3674     return NULL;
3675
3676   if (warn_if_readin && data->v.quick->symtab)
3677     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3678              paddress (get_objfile_arch (objfile), pc));
3679
3680   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3681   gdb_assert (result != NULL);
3682   return result;
3683 }
3684
3685 static void
3686 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3687                           void *data, int need_fullname)
3688 {
3689   int i;
3690   struct cleanup *cleanup;
3691   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3692                                       NULL, xcalloc, xfree);
3693
3694   cleanup = make_cleanup_htab_delete (visited);
3695   dw2_setup (objfile);
3696
3697   /* The rule is CUs specify all the files, including those used by
3698      any TU, so there's no need to scan TUs here.
3699      We can ignore file names coming from already-expanded CUs.  */
3700
3701   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3702     {
3703       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3704
3705       if (per_cu->v.quick->symtab)
3706         {
3707           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3708                                         INSERT);
3709
3710           *slot = per_cu->v.quick->file_names;
3711         }
3712     }
3713
3714   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3715     {
3716       int j;
3717       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3718       struct quick_file_names *file_data;
3719       void **slot;
3720
3721       /* We only need to look at symtabs not already expanded.  */
3722       if (per_cu->v.quick->symtab)
3723         continue;
3724
3725       file_data = dw2_get_file_names (objfile, per_cu);
3726       if (file_data == NULL)
3727         continue;
3728
3729       slot = htab_find_slot (visited, file_data, INSERT);
3730       if (*slot)
3731         {
3732           /* Already visited.  */
3733           continue;
3734         }
3735       *slot = file_data;
3736
3737       for (j = 0; j < file_data->num_file_names; ++j)
3738         {
3739           const char *this_real_name;
3740
3741           if (need_fullname)
3742             this_real_name = dw2_get_real_path (objfile, file_data, j);
3743           else
3744             this_real_name = NULL;
3745           (*fun) (file_data->file_names[j], this_real_name, data);
3746         }
3747     }
3748
3749   do_cleanups (cleanup);
3750 }
3751
3752 static int
3753 dw2_has_symbols (struct objfile *objfile)
3754 {
3755   return 1;
3756 }
3757
3758 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3759 {
3760   dw2_has_symbols,
3761   dw2_find_last_source_symtab,
3762   dw2_forget_cached_source_info,
3763   dw2_map_symtabs_matching_filename,
3764   dw2_lookup_symbol,
3765   dw2_print_stats,
3766   dw2_dump,
3767   dw2_relocate,
3768   dw2_expand_symtabs_for_function,
3769   dw2_expand_all_symtabs,
3770   dw2_expand_symtabs_with_filename,
3771   dw2_find_symbol_file,
3772   dw2_map_matching_symbols,
3773   dw2_expand_symtabs_matching,
3774   dw2_find_pc_sect_symtab,
3775   dw2_map_symbol_filenames
3776 };
3777
3778 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3779    file will use psymtabs, or 1 if using the GNU index.  */
3780
3781 int
3782 dwarf2_initialize_objfile (struct objfile *objfile)
3783 {
3784   /* If we're about to read full symbols, don't bother with the
3785      indices.  In this case we also don't care if some other debug
3786      format is making psymtabs, because they are all about to be
3787      expanded anyway.  */
3788   if ((objfile->flags & OBJF_READNOW))
3789     {
3790       int i;
3791
3792       dwarf2_per_objfile->using_index = 1;
3793       create_all_comp_units (objfile);
3794       create_all_type_units (objfile);
3795       dwarf2_per_objfile->quick_file_names_table =
3796         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3797
3798       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3799                        + dwarf2_per_objfile->n_type_units); ++i)
3800         {
3801           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3802
3803           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3804                                             struct dwarf2_per_cu_quick_data);
3805         }
3806
3807       /* Return 1 so that gdb sees the "quick" functions.  However,
3808          these functions will be no-ops because we will have expanded
3809          all symtabs.  */
3810       return 1;
3811     }
3812
3813   if (dwarf2_read_index (objfile))
3814     return 1;
3815
3816   return 0;
3817 }
3818
3819 \f
3820
3821 /* Build a partial symbol table.  */
3822
3823 void
3824 dwarf2_build_psymtabs (struct objfile *objfile)
3825 {
3826   volatile struct gdb_exception except;
3827
3828   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3829     {
3830       init_psymbol_list (objfile, 1024);
3831     }
3832
3833   TRY_CATCH (except, RETURN_MASK_ERROR)
3834     {
3835       /* This isn't really ideal: all the data we allocate on the
3836          objfile's obstack is still uselessly kept around.  However,
3837          freeing it seems unsafe.  */
3838       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3839
3840       dwarf2_build_psymtabs_hard (objfile);
3841       discard_cleanups (cleanups);
3842     }
3843   if (except.reason < 0)
3844     exception_print (gdb_stderr, except);
3845 }
3846
3847 /* Return the total length of the CU described by HEADER.  */
3848
3849 static unsigned int
3850 get_cu_length (const struct comp_unit_head *header)
3851 {
3852   return header->initial_length_size + header->length;
3853 }
3854
3855 /* Return TRUE if OFFSET is within CU_HEADER.  */
3856
3857 static inline int
3858 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3859 {
3860   sect_offset bottom = { cu_header->offset.sect_off };
3861   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3862
3863   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3864 }
3865
3866 /* Find the base address of the compilation unit for range lists and
3867    location lists.  It will normally be specified by DW_AT_low_pc.
3868    In DWARF-3 draft 4, the base address could be overridden by
3869    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3870    compilation units with discontinuous ranges.  */
3871
3872 static void
3873 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3874 {
3875   struct attribute *attr;
3876
3877   cu->base_known = 0;
3878   cu->base_address = 0;
3879
3880   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3881   if (attr)
3882     {
3883       cu->base_address = DW_ADDR (attr);
3884       cu->base_known = 1;
3885     }
3886   else
3887     {
3888       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3889       if (attr)
3890         {
3891           cu->base_address = DW_ADDR (attr);
3892           cu->base_known = 1;
3893         }
3894     }
3895 }
3896
3897 /* Read in the comp unit header information from the debug_info at info_ptr.
3898    NOTE: This leaves members offset, first_die_offset to be filled in
3899    by the caller.  */
3900
3901 static gdb_byte *
3902 read_comp_unit_head (struct comp_unit_head *cu_header,
3903                      gdb_byte *info_ptr, bfd *abfd)
3904 {
3905   int signed_addr;
3906   unsigned int bytes_read;
3907
3908   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3909   cu_header->initial_length_size = bytes_read;
3910   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3911   info_ptr += bytes_read;
3912   cu_header->version = read_2_bytes (abfd, info_ptr);
3913   info_ptr += 2;
3914   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3915                                              &bytes_read);
3916   info_ptr += bytes_read;
3917   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3918   info_ptr += 1;
3919   signed_addr = bfd_get_sign_extend_vma (abfd);
3920   if (signed_addr < 0)
3921     internal_error (__FILE__, __LINE__,
3922                     _("read_comp_unit_head: dwarf from non elf file"));
3923   cu_header->signed_addr_p = signed_addr;
3924
3925   return info_ptr;
3926 }
3927
3928 /* Helper function that returns the proper abbrev section for
3929    THIS_CU.  */
3930
3931 static struct dwarf2_section_info *
3932 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3933 {
3934   struct dwarf2_section_info *abbrev;
3935
3936   if (this_cu->is_dwz)
3937     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3938   else
3939     abbrev = &dwarf2_per_objfile->abbrev;
3940
3941   return abbrev;
3942 }
3943
3944 /* Subroutine of read_and_check_comp_unit_head and
3945    read_and_check_type_unit_head to simplify them.
3946    Perform various error checking on the header.  */
3947
3948 static void
3949 error_check_comp_unit_head (struct comp_unit_head *header,
3950                             struct dwarf2_section_info *section,
3951                             struct dwarf2_section_info *abbrev_section)
3952 {
3953   bfd *abfd = section->asection->owner;
3954   const char *filename = bfd_get_filename (abfd);
3955
3956   if (header->version != 2 && header->version != 3 && header->version != 4)
3957     error (_("Dwarf Error: wrong version in compilation unit header "
3958            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3959            filename);
3960
3961   if (header->abbrev_offset.sect_off
3962       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3963     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3964            "(offset 0x%lx + 6) [in module %s]"),
3965            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3966            filename);
3967
3968   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3969      avoid potential 32-bit overflow.  */
3970   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3971       > section->size)
3972     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3973            "(offset 0x%lx + 0) [in module %s]"),
3974            (long) header->length, (long) header->offset.sect_off,
3975            filename);
3976 }
3977
3978 /* Read in a CU/TU header and perform some basic error checking.
3979    The contents of the header are stored in HEADER.
3980    The result is a pointer to the start of the first DIE.  */
3981
3982 static gdb_byte *
3983 read_and_check_comp_unit_head (struct comp_unit_head *header,
3984                                struct dwarf2_section_info *section,
3985                                struct dwarf2_section_info *abbrev_section,
3986                                gdb_byte *info_ptr,
3987                                int is_debug_types_section)
3988 {
3989   gdb_byte *beg_of_comp_unit = info_ptr;
3990   bfd *abfd = section->asection->owner;
3991
3992   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3993
3994   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3995
3996   /* If we're reading a type unit, skip over the signature and
3997      type_offset fields.  */
3998   if (is_debug_types_section)
3999     info_ptr += 8 /*signature*/ + header->offset_size;
4000
4001   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4002
4003   error_check_comp_unit_head (header, section, abbrev_section);
4004
4005   return info_ptr;
4006 }
4007
4008 /* Read in the types comp unit header information from .debug_types entry at
4009    types_ptr.  The result is a pointer to one past the end of the header.  */
4010
4011 static gdb_byte *
4012 read_and_check_type_unit_head (struct comp_unit_head *header,
4013                                struct dwarf2_section_info *section,
4014                                struct dwarf2_section_info *abbrev_section,
4015                                gdb_byte *info_ptr,
4016                                ULONGEST *signature,
4017                                cu_offset *type_offset_in_tu)
4018 {
4019   gdb_byte *beg_of_comp_unit = info_ptr;
4020   bfd *abfd = section->asection->owner;
4021
4022   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4023
4024   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4025
4026   /* If we're reading a type unit, skip over the signature and
4027      type_offset fields.  */
4028   if (signature != NULL)
4029     *signature = read_8_bytes (abfd, info_ptr);
4030   info_ptr += 8;
4031   if (type_offset_in_tu != NULL)
4032     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4033                                                header->offset_size);
4034   info_ptr += header->offset_size;
4035
4036   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4037
4038   error_check_comp_unit_head (header, section, abbrev_section);
4039
4040   return info_ptr;
4041 }
4042
4043 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4044
4045 static sect_offset
4046 read_abbrev_offset (struct dwarf2_section_info *section,
4047                     sect_offset offset)
4048 {
4049   bfd *abfd = section->asection->owner;
4050   gdb_byte *info_ptr;
4051   unsigned int length, initial_length_size, offset_size;
4052   sect_offset abbrev_offset;
4053
4054   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4055   info_ptr = section->buffer + offset.sect_off;
4056   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4057   offset_size = initial_length_size == 4 ? 4 : 8;
4058   info_ptr += initial_length_size + 2 /*version*/;
4059   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4060   return abbrev_offset;
4061 }
4062
4063 /* Allocate a new partial symtab for file named NAME and mark this new
4064    partial symtab as being an include of PST.  */
4065
4066 static void
4067 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
4068                                struct objfile *objfile)
4069 {
4070   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4071
4072   subpst->section_offsets = pst->section_offsets;
4073   subpst->textlow = 0;
4074   subpst->texthigh = 0;
4075
4076   subpst->dependencies = (struct partial_symtab **)
4077     obstack_alloc (&objfile->objfile_obstack,
4078                    sizeof (struct partial_symtab *));
4079   subpst->dependencies[0] = pst;
4080   subpst->number_of_dependencies = 1;
4081
4082   subpst->globals_offset = 0;
4083   subpst->n_global_syms = 0;
4084   subpst->statics_offset = 0;
4085   subpst->n_static_syms = 0;
4086   subpst->symtab = NULL;
4087   subpst->read_symtab = pst->read_symtab;
4088   subpst->readin = 0;
4089
4090   /* No private part is necessary for include psymtabs.  This property
4091      can be used to differentiate between such include psymtabs and
4092      the regular ones.  */
4093   subpst->read_symtab_private = NULL;
4094 }
4095
4096 /* Read the Line Number Program data and extract the list of files
4097    included by the source file represented by PST.  Build an include
4098    partial symtab for each of these included files.  */
4099
4100 static void
4101 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4102                                struct die_info *die,
4103                                struct partial_symtab *pst)
4104 {
4105   struct line_header *lh = NULL;
4106   struct attribute *attr;
4107
4108   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4109   if (attr)
4110     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4111   if (lh == NULL)
4112     return;  /* No linetable, so no includes.  */
4113
4114   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4115   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4116
4117   free_line_header (lh);
4118 }
4119
4120 static hashval_t
4121 hash_signatured_type (const void *item)
4122 {
4123   const struct signatured_type *sig_type = item;
4124
4125   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4126   return sig_type->signature;
4127 }
4128
4129 static int
4130 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4131 {
4132   const struct signatured_type *lhs = item_lhs;
4133   const struct signatured_type *rhs = item_rhs;
4134
4135   return lhs->signature == rhs->signature;
4136 }
4137
4138 /* Allocate a hash table for signatured types.  */
4139
4140 static htab_t
4141 allocate_signatured_type_table (struct objfile *objfile)
4142 {
4143   return htab_create_alloc_ex (41,
4144                                hash_signatured_type,
4145                                eq_signatured_type,
4146                                NULL,
4147                                &objfile->objfile_obstack,
4148                                hashtab_obstack_allocate,
4149                                dummy_obstack_deallocate);
4150 }
4151
4152 /* A helper function to add a signatured type CU to a table.  */
4153
4154 static int
4155 add_signatured_type_cu_to_table (void **slot, void *datum)
4156 {
4157   struct signatured_type *sigt = *slot;
4158   struct signatured_type ***datap = datum;
4159
4160   **datap = sigt;
4161   ++*datap;
4162
4163   return 1;
4164 }
4165
4166 /* Create the hash table of all entries in the .debug_types section.
4167    DWO_FILE is a pointer to the DWO file for .debug_types.dwo,
4168    NULL otherwise.
4169    Note: This function processes DWO files only, not DWP files.
4170    The result is a pointer to the hash table or NULL if there are
4171    no types.  */
4172
4173 static htab_t
4174 create_debug_types_hash_table (struct dwo_file *dwo_file,
4175                                VEC (dwarf2_section_info_def) *types)
4176 {
4177   struct objfile *objfile = dwarf2_per_objfile->objfile;
4178   htab_t types_htab = NULL;
4179   int ix;
4180   struct dwarf2_section_info *section;
4181   struct dwarf2_section_info *abbrev_section;
4182
4183   if (VEC_empty (dwarf2_section_info_def, types))
4184     return NULL;
4185
4186   abbrev_section = (dwo_file != NULL
4187                     ? &dwo_file->sections.abbrev
4188                     : &dwarf2_per_objfile->abbrev);
4189
4190   if (dwarf2_read_debug)
4191     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4192                         dwo_file ? ".dwo" : "",
4193                         bfd_get_filename (abbrev_section->asection->owner));
4194
4195   for (ix = 0;
4196        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4197        ++ix)
4198     {
4199       bfd *abfd;
4200       gdb_byte *info_ptr, *end_ptr;
4201       struct dwarf2_section_info *abbrev_section;
4202
4203       dwarf2_read_section (objfile, section);
4204       info_ptr = section->buffer;
4205
4206       if (info_ptr == NULL)
4207         continue;
4208
4209       /* We can't set abfd until now because the section may be empty or
4210          not present, in which case section->asection will be NULL.  */
4211       abfd = section->asection->owner;
4212
4213       if (dwo_file)
4214         abbrev_section = &dwo_file->sections.abbrev;
4215       else
4216         abbrev_section = &dwarf2_per_objfile->abbrev;
4217
4218       if (types_htab == NULL)
4219         {
4220           if (dwo_file)
4221             types_htab = allocate_dwo_unit_table (objfile);
4222           else
4223             types_htab = allocate_signatured_type_table (objfile);
4224         }
4225
4226       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4227          because we don't need to read any dies: the signature is in the
4228          header.  */
4229
4230       end_ptr = info_ptr + section->size;
4231       while (info_ptr < end_ptr)
4232         {
4233           sect_offset offset;
4234           cu_offset type_offset_in_tu;
4235           ULONGEST signature;
4236           struct signatured_type *sig_type;
4237           struct dwo_unit *dwo_tu;
4238           void **slot;
4239           gdb_byte *ptr = info_ptr;
4240           struct comp_unit_head header;
4241           unsigned int length;
4242
4243           offset.sect_off = ptr - section->buffer;
4244
4245           /* We need to read the type's signature in order to build the hash
4246              table, but we don't need anything else just yet.  */
4247
4248           ptr = read_and_check_type_unit_head (&header, section,
4249                                                abbrev_section, ptr,
4250                                                &signature, &type_offset_in_tu);
4251
4252           length = get_cu_length (&header);
4253
4254           /* Skip dummy type units.  */
4255           if (ptr >= info_ptr + length
4256               || peek_abbrev_code (abfd, ptr) == 0)
4257             {
4258               info_ptr += length;
4259               continue;
4260             }
4261
4262           if (dwo_file)
4263             {
4264               sig_type = NULL;
4265               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4266                                        struct dwo_unit);
4267               dwo_tu->dwo_file = dwo_file;
4268               dwo_tu->signature = signature;
4269               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4270               dwo_tu->info_or_types_section = section;
4271               dwo_tu->offset = offset;
4272               dwo_tu->length = length;
4273             }
4274           else
4275             {
4276               /* N.B.: type_offset is not usable if this type uses a DWO file.
4277                  The real type_offset is in the DWO file.  */
4278               dwo_tu = NULL;
4279               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4280                                          struct signatured_type);
4281               sig_type->signature = signature;
4282               sig_type->type_offset_in_tu = type_offset_in_tu;
4283               sig_type->per_cu.objfile = objfile;
4284               sig_type->per_cu.is_debug_types = 1;
4285               sig_type->per_cu.info_or_types_section = section;
4286               sig_type->per_cu.offset = offset;
4287               sig_type->per_cu.length = length;
4288             }
4289
4290           slot = htab_find_slot (types_htab,
4291                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4292                                  INSERT);
4293           gdb_assert (slot != NULL);
4294           if (*slot != NULL)
4295             {
4296               sect_offset dup_offset;
4297
4298               if (dwo_file)
4299                 {
4300                   const struct dwo_unit *dup_tu = *slot;
4301
4302                   dup_offset = dup_tu->offset;
4303                 }
4304               else
4305                 {
4306                   const struct signatured_type *dup_tu = *slot;
4307
4308                   dup_offset = dup_tu->per_cu.offset;
4309                 }
4310
4311               complaint (&symfile_complaints,
4312                          _("debug type entry at offset 0x%x is duplicate to the "
4313                            "entry at offset 0x%x, signature 0x%s"),
4314                          offset.sect_off, dup_offset.sect_off,
4315                          phex (signature, sizeof (signature)));
4316             }
4317           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4318
4319           if (dwarf2_read_debug)
4320             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4321                                 offset.sect_off,
4322                                 phex (signature, sizeof (signature)));
4323
4324           info_ptr += length;
4325         }
4326     }
4327
4328   return types_htab;
4329 }
4330
4331 /* Create the hash table of all entries in the .debug_types section,
4332    and initialize all_type_units.
4333    The result is zero if there is an error (e.g. missing .debug_types section),
4334    otherwise non-zero.  */
4335
4336 static int
4337 create_all_type_units (struct objfile *objfile)
4338 {
4339   htab_t types_htab;
4340   struct signatured_type **iter;
4341
4342   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4343   if (types_htab == NULL)
4344     {
4345       dwarf2_per_objfile->signatured_types = NULL;
4346       return 0;
4347     }
4348
4349   dwarf2_per_objfile->signatured_types = types_htab;
4350
4351   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4352   dwarf2_per_objfile->all_type_units
4353     = obstack_alloc (&objfile->objfile_obstack,
4354                      dwarf2_per_objfile->n_type_units
4355                      * sizeof (struct signatured_type *));
4356   iter = &dwarf2_per_objfile->all_type_units[0];
4357   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4358   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4359               == dwarf2_per_objfile->n_type_units);
4360
4361   return 1;
4362 }
4363
4364 /* Lookup a signature based type for DW_FORM_ref_sig8.
4365    Returns NULL if signature SIG is not present in the table.  */
4366
4367 static struct signatured_type *
4368 lookup_signatured_type (ULONGEST sig)
4369 {
4370   struct signatured_type find_entry, *entry;
4371
4372   if (dwarf2_per_objfile->signatured_types == NULL)
4373     {
4374       complaint (&symfile_complaints,
4375                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4376       return NULL;
4377     }
4378
4379   find_entry.signature = sig;
4380   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4381   return entry;
4382 }
4383 \f
4384 /* Low level DIE reading support.  */
4385
4386 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4387
4388 static void
4389 init_cu_die_reader (struct die_reader_specs *reader,
4390                     struct dwarf2_cu *cu,
4391                     struct dwarf2_section_info *section,
4392                     struct dwo_file *dwo_file)
4393 {
4394   gdb_assert (section->readin && section->buffer != NULL);
4395   reader->abfd = section->asection->owner;
4396   reader->cu = cu;
4397   reader->dwo_file = dwo_file;
4398   reader->die_section = section;
4399   reader->buffer = section->buffer;
4400   reader->buffer_end = section->buffer + section->size;
4401 }
4402
4403 /* Initialize a CU (or TU) and read its DIEs.
4404    If the CU defers to a DWO file, read the DWO file as well.
4405
4406    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4407    Otherwise the table specified in the comp unit header is read in and used.
4408    This is an optimization for when we already have the abbrev table.
4409
4410    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4411    Otherwise, a new CU is allocated with xmalloc.
4412
4413    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4414    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4415
4416    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4417    linker) then DIE_READER_FUNC will not get called.  */
4418
4419 static void
4420 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4421                          struct abbrev_table *abbrev_table,
4422                          int use_existing_cu, int keep,
4423                          die_reader_func_ftype *die_reader_func,
4424                          void *data)
4425 {
4426   struct objfile *objfile = dwarf2_per_objfile->objfile;
4427   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4428   bfd *abfd = section->asection->owner;
4429   struct dwarf2_cu *cu;
4430   gdb_byte *begin_info_ptr, *info_ptr;
4431   struct die_reader_specs reader;
4432   struct die_info *comp_unit_die;
4433   int has_children;
4434   struct attribute *attr;
4435   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4436   struct signatured_type *sig_type = NULL;
4437   struct dwarf2_section_info *abbrev_section;
4438   /* Non-zero if CU currently points to a DWO file and we need to
4439      reread it.  When this happens we need to reread the skeleton die
4440      before we can reread the DWO file.  */
4441   int rereading_dwo_cu = 0;
4442
4443   if (dwarf2_die_debug)
4444     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4445                         this_cu->is_debug_types ? "type" : "comp",
4446                         this_cu->offset.sect_off);
4447
4448   if (use_existing_cu)
4449     gdb_assert (keep);
4450
4451   cleanups = make_cleanup (null_cleanup, NULL);
4452
4453   /* This is cheap if the section is already read in.  */
4454   dwarf2_read_section (objfile, section);
4455
4456   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4457
4458   abbrev_section = get_abbrev_section_for_cu (this_cu);
4459
4460   if (use_existing_cu && this_cu->cu != NULL)
4461     {
4462       cu = this_cu->cu;
4463
4464       /* If this CU is from a DWO file we need to start over, we need to
4465          refetch the attributes from the skeleton CU.
4466          This could be optimized by retrieving those attributes from when we
4467          were here the first time: the previous comp_unit_die was stored in
4468          comp_unit_obstack.  But there's no data yet that we need this
4469          optimization.  */
4470       if (cu->dwo_unit != NULL)
4471         rereading_dwo_cu = 1;
4472     }
4473   else
4474     {
4475       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4476       gdb_assert (this_cu->cu == NULL);
4477
4478       cu = xmalloc (sizeof (*cu));
4479       init_one_comp_unit (cu, this_cu);
4480
4481       /* If an error occurs while loading, release our storage.  */
4482       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4483     }
4484
4485   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4486     {
4487       /* We already have the header, there's no need to read it in again.  */
4488       info_ptr += cu->header.first_die_offset.cu_off;
4489     }
4490   else
4491     {
4492       if (this_cu->is_debug_types)
4493         {
4494           ULONGEST signature;
4495           cu_offset type_offset_in_tu;
4496
4497           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4498                                                     abbrev_section, info_ptr,
4499                                                     &signature,
4500                                                     &type_offset_in_tu);
4501
4502           /* Since per_cu is the first member of struct signatured_type,
4503              we can go from a pointer to one to a pointer to the other.  */
4504           sig_type = (struct signatured_type *) this_cu;
4505           gdb_assert (sig_type->signature == signature);
4506           gdb_assert (sig_type->type_offset_in_tu.cu_off
4507                       == type_offset_in_tu.cu_off);
4508           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4509
4510           /* LENGTH has not been set yet for type units if we're
4511              using .gdb_index.  */
4512           this_cu->length = get_cu_length (&cu->header);
4513
4514           /* Establish the type offset that can be used to lookup the type.  */
4515           sig_type->type_offset_in_section.sect_off =
4516             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4517         }
4518       else
4519         {
4520           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4521                                                     abbrev_section,
4522                                                     info_ptr, 0);
4523
4524           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4525           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4526         }
4527     }
4528
4529   /* Skip dummy compilation units.  */
4530   if (info_ptr >= begin_info_ptr + this_cu->length
4531       || peek_abbrev_code (abfd, info_ptr) == 0)
4532     {
4533       do_cleanups (cleanups);
4534       return;
4535     }
4536
4537   /* If we don't have them yet, read the abbrevs for this compilation unit.
4538      And if we need to read them now, make sure they're freed when we're
4539      done.  Note that it's important that if the CU had an abbrev table
4540      on entry we don't free it when we're done: Somewhere up the call stack
4541      it may be in use.  */
4542   if (abbrev_table != NULL)
4543     {
4544       gdb_assert (cu->abbrev_table == NULL);
4545       gdb_assert (cu->header.abbrev_offset.sect_off
4546                   == abbrev_table->offset.sect_off);
4547       cu->abbrev_table = abbrev_table;
4548     }
4549   else if (cu->abbrev_table == NULL)
4550     {
4551       dwarf2_read_abbrevs (cu, abbrev_section);
4552       make_cleanup (dwarf2_free_abbrev_table, cu);
4553     }
4554   else if (rereading_dwo_cu)
4555     {
4556       dwarf2_free_abbrev_table (cu);
4557       dwarf2_read_abbrevs (cu, abbrev_section);
4558     }
4559
4560   /* Read the top level CU/TU die.  */
4561   init_cu_die_reader (&reader, cu, section, NULL);
4562   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4563
4564   /* If we have a DWO stub, process it and then read in the DWO file.
4565      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4566      a DWO CU, that this test will fail.  */
4567   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4568   if (attr)
4569     {
4570       const char *dwo_name = DW_STRING (attr);
4571       const char *comp_dir_string;
4572       struct dwo_unit *dwo_unit;
4573       ULONGEST signature; /* Or dwo_id.  */
4574       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4575       int i,num_extra_attrs;
4576       struct dwarf2_section_info *dwo_abbrev_section;
4577
4578       if (has_children)
4579         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4580                  " has children (offset 0x%x) [in module %s]"),
4581                this_cu->offset.sect_off, bfd_get_filename (abfd));
4582
4583       /* These attributes aren't processed until later:
4584          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4585          However, the attribute is found in the stub which we won't have later.
4586          In order to not impose this complication on the rest of the code,
4587          we read them here and copy them to the DWO CU/TU die.  */
4588
4589       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4590          DWO file.  */
4591       stmt_list = NULL;
4592       if (! this_cu->is_debug_types)
4593         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4594       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4595       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4596       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4597       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4598
4599       /* There should be a DW_AT_addr_base attribute here (if needed).
4600          We need the value before we can process DW_FORM_GNU_addr_index.  */
4601       cu->addr_base = 0;
4602       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4603       if (attr)
4604         cu->addr_base = DW_UNSND (attr);
4605
4606       /* There should be a DW_AT_ranges_base attribute here (if needed).
4607          We need the value before we can process DW_AT_ranges.  */
4608       cu->ranges_base = 0;
4609       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4610       if (attr)
4611         cu->ranges_base = DW_UNSND (attr);
4612
4613       if (this_cu->is_debug_types)
4614         {
4615           gdb_assert (sig_type != NULL);
4616           signature = sig_type->signature;
4617         }
4618       else
4619         {
4620           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4621           if (! attr)
4622             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4623                    dwo_name);
4624           signature = DW_UNSND (attr);
4625         }
4626
4627       /* We may need the comp_dir in order to find the DWO file.  */
4628       comp_dir_string = NULL;
4629       if (comp_dir)
4630         comp_dir_string = DW_STRING (comp_dir);
4631
4632       if (this_cu->is_debug_types)
4633         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4634       else
4635         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4636                                          signature);
4637
4638       if (dwo_unit == NULL)
4639         {
4640           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4641                    " with ID %s [in module %s]"),
4642                  this_cu->offset.sect_off,
4643                  phex (signature, sizeof (signature)),
4644                  objfile->name);
4645         }
4646
4647       /* Set up for reading the DWO CU/TU.  */
4648       cu->dwo_unit = dwo_unit;
4649       section = dwo_unit->info_or_types_section;
4650       dwarf2_read_section (objfile, section);
4651       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4652       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4653       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4654
4655       if (this_cu->is_debug_types)
4656         {
4657           ULONGEST signature;
4658           cu_offset type_offset_in_tu;
4659
4660           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4661                                                     dwo_abbrev_section,
4662                                                     info_ptr,
4663                                                     &signature,
4664                                                     &type_offset_in_tu);
4665           gdb_assert (sig_type->signature == signature);
4666           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4667           /* For DWOs coming from DWP files, we don't know the CU length
4668              nor the type's offset in the TU until now.  */
4669           dwo_unit->length = get_cu_length (&cu->header);
4670           dwo_unit->type_offset_in_tu = type_offset_in_tu;
4671
4672           /* Establish the type offset that can be used to lookup the type.
4673              For DWO files, we don't know it until now.  */
4674           sig_type->type_offset_in_section.sect_off =
4675             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4676         }
4677       else
4678         {
4679           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4680                                                     dwo_abbrev_section,
4681                                                     info_ptr, 0);
4682           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4683           /* For DWOs coming from DWP files, we don't know the CU length
4684              until now.  */
4685           dwo_unit->length = get_cu_length (&cu->header);
4686         }
4687
4688       /* Discard the original CU's abbrev table, and read the DWO's.  */
4689       if (abbrev_table == NULL)
4690         {
4691           dwarf2_free_abbrev_table (cu);
4692           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4693         }
4694       else
4695         {
4696           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4697           make_cleanup (dwarf2_free_abbrev_table, cu);
4698         }
4699
4700       /* Read in the die, but leave space to copy over the attributes
4701          from the stub.  This has the benefit of simplifying the rest of
4702          the code - all the real work is done here.  */
4703       num_extra_attrs = ((stmt_list != NULL)
4704                          + (low_pc != NULL)
4705                          + (high_pc != NULL)
4706                          + (ranges != NULL)
4707                          + (comp_dir != NULL));
4708       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4709                                   &has_children, num_extra_attrs);
4710
4711       /* Copy over the attributes from the stub to the DWO die.  */
4712       i = comp_unit_die->num_attrs;
4713       if (stmt_list != NULL)
4714         comp_unit_die->attrs[i++] = *stmt_list;
4715       if (low_pc != NULL)
4716         comp_unit_die->attrs[i++] = *low_pc;
4717       if (high_pc != NULL)
4718         comp_unit_die->attrs[i++] = *high_pc;
4719       if (ranges != NULL)
4720         comp_unit_die->attrs[i++] = *ranges;
4721       if (comp_dir != NULL)
4722         comp_unit_die->attrs[i++] = *comp_dir;
4723       comp_unit_die->num_attrs += num_extra_attrs;
4724
4725       /* Skip dummy compilation units.  */
4726       if (info_ptr >= begin_info_ptr + dwo_unit->length
4727           || peek_abbrev_code (abfd, info_ptr) == 0)
4728         {
4729           do_cleanups (cleanups);
4730           return;
4731         }
4732     }
4733
4734   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4735
4736   if (free_cu_cleanup != NULL)
4737     {
4738       if (keep)
4739         {
4740           /* We've successfully allocated this compilation unit.  Let our
4741              caller clean it up when finished with it.  */
4742           discard_cleanups (free_cu_cleanup);
4743
4744           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4745              So we have to manually free the abbrev table.  */
4746           dwarf2_free_abbrev_table (cu);
4747
4748           /* Link this CU into read_in_chain.  */
4749           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4750           dwarf2_per_objfile->read_in_chain = this_cu;
4751         }
4752       else
4753         do_cleanups (free_cu_cleanup);
4754     }
4755
4756   do_cleanups (cleanups);
4757 }
4758
4759 /* Read CU/TU THIS_CU in section SECTION,
4760    but do not follow DW_AT_GNU_dwo_name if present.
4761    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4762    to have already done the lookup to find the DWO/DWP file).
4763
4764    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4765    THIS_CU->is_debug_types, but nothing else.
4766
4767    We fill in THIS_CU->length.
4768
4769    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4770    linker) then DIE_READER_FUNC will not get called.
4771
4772    THIS_CU->cu is always freed when done.
4773    This is done in order to not leave THIS_CU->cu in a state where we have
4774    to care whether it refers to the "main" CU or the DWO CU.  */
4775
4776 static void
4777 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4778                                    struct dwarf2_section_info *abbrev_section,
4779                                    struct dwo_file *dwo_file,
4780                                    die_reader_func_ftype *die_reader_func,
4781                                    void *data)
4782 {
4783   struct objfile *objfile = dwarf2_per_objfile->objfile;
4784   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4785   bfd *abfd = section->asection->owner;
4786   struct dwarf2_cu cu;
4787   gdb_byte *begin_info_ptr, *info_ptr;
4788   struct die_reader_specs reader;
4789   struct cleanup *cleanups;
4790   struct die_info *comp_unit_die;
4791   int has_children;
4792
4793   if (dwarf2_die_debug)
4794     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4795                         this_cu->is_debug_types ? "type" : "comp",
4796                         this_cu->offset.sect_off);
4797
4798   gdb_assert (this_cu->cu == NULL);
4799
4800   /* This is cheap if the section is already read in.  */
4801   dwarf2_read_section (objfile, section);
4802
4803   init_one_comp_unit (&cu, this_cu);
4804
4805   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4806
4807   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4808   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4809                                             abbrev_section, info_ptr,
4810                                             this_cu->is_debug_types);
4811
4812   this_cu->length = get_cu_length (&cu.header);
4813
4814   /* Skip dummy compilation units.  */
4815   if (info_ptr >= begin_info_ptr + this_cu->length
4816       || peek_abbrev_code (abfd, info_ptr) == 0)
4817     {
4818       do_cleanups (cleanups);
4819       return;
4820     }
4821
4822   dwarf2_read_abbrevs (&cu, abbrev_section);
4823   make_cleanup (dwarf2_free_abbrev_table, &cu);
4824
4825   init_cu_die_reader (&reader, &cu, section, dwo_file);
4826   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4827
4828   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4829
4830   do_cleanups (cleanups);
4831 }
4832
4833 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4834    does not lookup the specified DWO file.
4835    This cannot be used to read DWO files.
4836
4837    THIS_CU->cu is always freed when done.
4838    This is done in order to not leave THIS_CU->cu in a state where we have
4839    to care whether it refers to the "main" CU or the DWO CU.
4840    We can revisit this if the data shows there's a performance issue.  */
4841
4842 static void
4843 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4844                                 die_reader_func_ftype *die_reader_func,
4845                                 void *data)
4846 {
4847   init_cutu_and_read_dies_no_follow (this_cu,
4848                                      get_abbrev_section_for_cu (this_cu),
4849                                      NULL,
4850                                      die_reader_func, data);
4851 }
4852
4853 /* Create a psymtab named NAME and assign it to PER_CU.
4854
4855    The caller must fill in the following details:
4856    dirname, textlow, texthigh.  */
4857
4858 static struct partial_symtab *
4859 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4860 {
4861   struct objfile *objfile = per_cu->objfile;
4862   struct partial_symtab *pst;
4863
4864   pst = start_psymtab_common (objfile, objfile->section_offsets,
4865                               name, 0,
4866                               objfile->global_psymbols.next,
4867                               objfile->static_psymbols.next);
4868
4869   pst->psymtabs_addrmap_supported = 1;
4870
4871   /* This is the glue that links PST into GDB's symbol API.  */
4872   pst->read_symtab_private = per_cu;
4873   pst->read_symtab = dwarf2_read_symtab;
4874   per_cu->v.psymtab = pst;
4875
4876   return pst;
4877 }
4878
4879 /* die_reader_func for process_psymtab_comp_unit.  */
4880
4881 static void
4882 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4883                                   gdb_byte *info_ptr,
4884                                   struct die_info *comp_unit_die,
4885                                   int has_children,
4886                                   void *data)
4887 {
4888   struct dwarf2_cu *cu = reader->cu;
4889   struct objfile *objfile = cu->objfile;
4890   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4891   struct attribute *attr;
4892   CORE_ADDR baseaddr;
4893   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4894   struct partial_symtab *pst;
4895   int has_pc_info;
4896   const char *filename;
4897   int *want_partial_unit_ptr = data;
4898
4899   if (comp_unit_die->tag == DW_TAG_partial_unit
4900       && (want_partial_unit_ptr == NULL
4901           || !*want_partial_unit_ptr))
4902     return;
4903
4904   gdb_assert (! per_cu->is_debug_types);
4905
4906   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4907
4908   cu->list_in_scope = &file_symbols;
4909
4910   /* Allocate a new partial symbol table structure.  */
4911   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4912   if (attr == NULL || !DW_STRING (attr))
4913     filename = "";
4914   else
4915     filename = DW_STRING (attr);
4916
4917   pst = create_partial_symtab (per_cu, filename);
4918
4919   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4920   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4921   if (attr != NULL)
4922     pst->dirname = DW_STRING (attr);
4923
4924   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4925
4926   dwarf2_find_base_address (comp_unit_die, cu);
4927
4928   /* Possibly set the default values of LOWPC and HIGHPC from
4929      `DW_AT_ranges'.  */
4930   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4931                                       &best_highpc, cu, pst);
4932   if (has_pc_info == 1 && best_lowpc < best_highpc)
4933     /* Store the contiguous range if it is not empty; it can be empty for
4934        CUs with no code.  */
4935     addrmap_set_empty (objfile->psymtabs_addrmap,
4936                        best_lowpc + baseaddr,
4937                        best_highpc + baseaddr - 1, pst);
4938
4939   /* Check if comp unit has_children.
4940      If so, read the rest of the partial symbols from this comp unit.
4941      If not, there's no more debug_info for this comp unit.  */
4942   if (has_children)
4943     {
4944       struct partial_die_info *first_die;
4945       CORE_ADDR lowpc, highpc;
4946
4947       lowpc = ((CORE_ADDR) -1);
4948       highpc = ((CORE_ADDR) 0);
4949
4950       first_die = load_partial_dies (reader, info_ptr, 1);
4951
4952       scan_partial_symbols (first_die, &lowpc, &highpc,
4953                             ! has_pc_info, cu);
4954
4955       /* If we didn't find a lowpc, set it to highpc to avoid
4956          complaints from `maint check'.  */
4957       if (lowpc == ((CORE_ADDR) -1))
4958         lowpc = highpc;
4959
4960       /* If the compilation unit didn't have an explicit address range,
4961          then use the information extracted from its child dies.  */
4962       if (! has_pc_info)
4963         {
4964           best_lowpc = lowpc;
4965           best_highpc = highpc;
4966         }
4967     }
4968   pst->textlow = best_lowpc + baseaddr;
4969   pst->texthigh = best_highpc + baseaddr;
4970
4971   pst->n_global_syms = objfile->global_psymbols.next -
4972     (objfile->global_psymbols.list + pst->globals_offset);
4973   pst->n_static_syms = objfile->static_psymbols.next -
4974     (objfile->static_psymbols.list + pst->statics_offset);
4975   sort_pst_symbols (objfile, pst);
4976
4977   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
4978     {
4979       int i;
4980       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4981       struct dwarf2_per_cu_data *iter;
4982
4983       /* Fill in 'dependencies' here; we fill in 'users' in a
4984          post-pass.  */
4985       pst->number_of_dependencies = len;
4986       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4987                                          len * sizeof (struct symtab *));
4988       for (i = 0;
4989            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4990                         i, iter);
4991            ++i)
4992         pst->dependencies[i] = iter->v.psymtab;
4993
4994       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4995     }
4996
4997   /* Get the list of files included in the current compilation unit,
4998      and build a psymtab for each of them.  */
4999   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5000
5001   if (dwarf2_read_debug)
5002     {
5003       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5004
5005       fprintf_unfiltered (gdb_stdlog,
5006                           "Psymtab for %s unit @0x%x: %s - %s"
5007                           ", %d global, %d static syms\n",
5008                           per_cu->is_debug_types ? "type" : "comp",
5009                           per_cu->offset.sect_off,
5010                           paddress (gdbarch, pst->textlow),
5011                           paddress (gdbarch, pst->texthigh),
5012                           pst->n_global_syms, pst->n_static_syms);
5013     }
5014 }
5015
5016 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5017    Process compilation unit THIS_CU for a psymtab.  */
5018
5019 static void
5020 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5021                            int want_partial_unit)
5022 {
5023   /* If this compilation unit was already read in, free the
5024      cached copy in order to read it in again.  This is
5025      necessary because we skipped some symbols when we first
5026      read in the compilation unit (see load_partial_dies).
5027      This problem could be avoided, but the benefit is unclear.  */
5028   if (this_cu->cu != NULL)
5029     free_one_cached_comp_unit (this_cu);
5030
5031   gdb_assert (! this_cu->is_debug_types);
5032   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5033                            process_psymtab_comp_unit_reader,
5034                            &want_partial_unit);
5035
5036   /* Age out any secondary CUs.  */
5037   age_cached_comp_units ();
5038 }
5039
5040 static hashval_t
5041 hash_type_unit_group (const void *item)
5042 {
5043   const struct type_unit_group *tu_group = item;
5044
5045   return hash_stmt_list_entry (&tu_group->hash);
5046 }
5047
5048 static int
5049 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5050 {
5051   const struct type_unit_group *lhs = item_lhs;
5052   const struct type_unit_group *rhs = item_rhs;
5053
5054   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5055 }
5056
5057 /* Allocate a hash table for type unit groups.  */
5058
5059 static htab_t
5060 allocate_type_unit_groups_table (void)
5061 {
5062   return htab_create_alloc_ex (3,
5063                                hash_type_unit_group,
5064                                eq_type_unit_group,
5065                                NULL,
5066                                &dwarf2_per_objfile->objfile->objfile_obstack,
5067                                hashtab_obstack_allocate,
5068                                dummy_obstack_deallocate);
5069 }
5070
5071 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5072    partial symtabs.  We combine several TUs per psymtab to not let the size
5073    of any one psymtab grow too big.  */
5074 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5075 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5076
5077 /* Helper routine for get_type_unit_group.
5078    Create the type_unit_group object used to hold one or more TUs.  */
5079
5080 static struct type_unit_group *
5081 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5082 {
5083   struct objfile *objfile = dwarf2_per_objfile->objfile;
5084   struct dwarf2_per_cu_data *per_cu;
5085   struct type_unit_group *tu_group;
5086
5087   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5088                              struct type_unit_group);
5089   per_cu = &tu_group->per_cu;
5090   per_cu->objfile = objfile;
5091   per_cu->is_debug_types = 1;
5092   per_cu->type_unit_group = tu_group;
5093
5094   if (dwarf2_per_objfile->using_index)
5095     {
5096       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5097                                         struct dwarf2_per_cu_quick_data);
5098       tu_group->t.first_tu = cu->per_cu;
5099     }
5100   else
5101     {
5102       unsigned int line_offset = line_offset_struct.sect_off;
5103       struct partial_symtab *pst;
5104       char *name;
5105
5106       /* Give the symtab a useful name for debug purposes.  */
5107       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5108         name = xstrprintf ("<type_units_%d>",
5109                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5110       else
5111         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5112
5113       pst = create_partial_symtab (per_cu, name);
5114       pst->anonymous = 1;
5115
5116       xfree (name);
5117     }
5118
5119   tu_group->hash.dwo_unit = cu->dwo_unit;
5120   tu_group->hash.line_offset = line_offset_struct;
5121
5122   return tu_group;
5123 }
5124
5125 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5126    STMT_LIST is a DW_AT_stmt_list attribute.  */
5127
5128 static struct type_unit_group *
5129 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5130 {
5131   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5132   struct type_unit_group *tu_group;
5133   void **slot;
5134   unsigned int line_offset;
5135   struct type_unit_group type_unit_group_for_lookup;
5136
5137   if (dwarf2_per_objfile->type_unit_groups == NULL)
5138     {
5139       dwarf2_per_objfile->type_unit_groups =
5140         allocate_type_unit_groups_table ();
5141     }
5142
5143   /* Do we need to create a new group, or can we use an existing one?  */
5144
5145   if (stmt_list)
5146     {
5147       line_offset = DW_UNSND (stmt_list);
5148       ++tu_stats->nr_symtab_sharers;
5149     }
5150   else
5151     {
5152       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5153          We can do various things here like create one group per TU or
5154          spread them over multiple groups to split up the expansion work.
5155          To avoid worst case scenarios (too many groups or too large groups)
5156          we, umm, group them in bunches.  */
5157       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5158                      | (tu_stats->nr_stmt_less_type_units
5159                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5160       ++tu_stats->nr_stmt_less_type_units;
5161     }
5162
5163   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5164   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5165   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5166                          &type_unit_group_for_lookup, INSERT);
5167   if (*slot != NULL)
5168     {
5169       tu_group = *slot;
5170       gdb_assert (tu_group != NULL);
5171     }
5172   else
5173     {
5174       sect_offset line_offset_struct;
5175
5176       line_offset_struct.sect_off = line_offset;
5177       tu_group = create_type_unit_group (cu, line_offset_struct);
5178       *slot = tu_group;
5179       ++tu_stats->nr_symtabs;
5180     }
5181
5182   return tu_group;
5183 }
5184
5185 /* Struct used to sort TUs by their abbreviation table offset.  */
5186
5187 struct tu_abbrev_offset
5188 {
5189   struct signatured_type *sig_type;
5190   sect_offset abbrev_offset;
5191 };
5192
5193 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5194
5195 static int
5196 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5197 {
5198   const struct tu_abbrev_offset * const *a = ap;
5199   const struct tu_abbrev_offset * const *b = bp;
5200   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5201   unsigned int boff = (*b)->abbrev_offset.sect_off;
5202
5203   return (aoff > boff) - (aoff < boff);
5204 }
5205
5206 /* A helper function to add a type_unit_group to a table.  */
5207
5208 static int
5209 add_type_unit_group_to_table (void **slot, void *datum)
5210 {
5211   struct type_unit_group *tu_group = *slot;
5212   struct type_unit_group ***datap = datum;
5213
5214   **datap = tu_group;
5215   ++*datap;
5216
5217   return 1;
5218 }
5219
5220 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5221    each one passing FUNC,DATA.
5222
5223    The efficiency is because we sort TUs by the abbrev table they use and
5224    only read each abbrev table once.  In one program there are 200K TUs
5225    sharing 8K abbrev tables.
5226
5227    The main purpose of this function is to support building the
5228    dwarf2_per_objfile->type_unit_groups table.
5229    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5230    can collapse the search space by grouping them by stmt_list.
5231    The savings can be significant, in the same program from above the 200K TUs
5232    share 8K stmt_list tables.
5233
5234    FUNC is expected to call get_type_unit_group, which will create the
5235    struct type_unit_group if necessary and add it to
5236    dwarf2_per_objfile->type_unit_groups.  */
5237
5238 static void
5239 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5240 {
5241   struct objfile *objfile = dwarf2_per_objfile->objfile;
5242   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5243   struct cleanup *cleanups;
5244   struct abbrev_table *abbrev_table;
5245   sect_offset abbrev_offset;
5246   struct tu_abbrev_offset *sorted_by_abbrev;
5247   struct type_unit_group **iter;
5248   int i;
5249
5250   /* It's up to the caller to not call us multiple times.  */
5251   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5252
5253   if (dwarf2_per_objfile->n_type_units == 0)
5254     return;
5255
5256   /* TUs typically share abbrev tables, and there can be way more TUs than
5257      abbrev tables.  Sort by abbrev table to reduce the number of times we
5258      read each abbrev table in.
5259      Alternatives are to punt or to maintain a cache of abbrev tables.
5260      This is simpler and efficient enough for now.
5261
5262      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5263      symtab to use).  Typically TUs with the same abbrev offset have the same
5264      stmt_list value too so in practice this should work well.
5265
5266      The basic algorithm here is:
5267
5268       sort TUs by abbrev table
5269       for each TU with same abbrev table:
5270         read abbrev table if first user
5271         read TU top level DIE
5272           [IWBN if DWO skeletons had DW_AT_stmt_list]
5273         call FUNC  */
5274
5275   if (dwarf2_read_debug)
5276     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5277
5278   /* Sort in a separate table to maintain the order of all_type_units
5279      for .gdb_index: TU indices directly index all_type_units.  */
5280   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5281                               dwarf2_per_objfile->n_type_units);
5282   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5283     {
5284       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5285
5286       sorted_by_abbrev[i].sig_type = sig_type;
5287       sorted_by_abbrev[i].abbrev_offset =
5288         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
5289                             sig_type->per_cu.offset);
5290     }
5291   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5292   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5293          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5294
5295   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5296      called any number of times, so we don't reset tu_stats here.  */
5297
5298   abbrev_offset.sect_off = ~(unsigned) 0;
5299   abbrev_table = NULL;
5300   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5301
5302   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5303     {
5304       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5305
5306       /* Switch to the next abbrev table if necessary.  */
5307       if (abbrev_table == NULL
5308           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5309         {
5310           if (abbrev_table != NULL)
5311             {
5312               abbrev_table_free (abbrev_table);
5313               /* Reset to NULL in case abbrev_table_read_table throws
5314                  an error: abbrev_table_free_cleanup will get called.  */
5315               abbrev_table = NULL;
5316             }
5317           abbrev_offset = tu->abbrev_offset;
5318           abbrev_table =
5319             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5320                                      abbrev_offset);
5321           ++tu_stats->nr_uniq_abbrev_tables;
5322         }
5323
5324       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5325                                func, data);
5326     }
5327
5328   /* Create a vector of pointers to primary type units to make it easy to
5329      iterate over them and CUs.  See dw2_get_primary_cu.  */
5330   dwarf2_per_objfile->n_type_unit_groups =
5331     htab_elements (dwarf2_per_objfile->type_unit_groups);
5332   dwarf2_per_objfile->all_type_unit_groups =
5333     obstack_alloc (&objfile->objfile_obstack,
5334                    dwarf2_per_objfile->n_type_unit_groups
5335                    * sizeof (struct type_unit_group *));
5336   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5337   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5338                           add_type_unit_group_to_table, &iter);
5339   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5340               == dwarf2_per_objfile->n_type_unit_groups);
5341
5342   do_cleanups (cleanups);
5343
5344   if (dwarf2_read_debug)
5345     {
5346       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5347       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5348                           dwarf2_per_objfile->n_type_units);
5349       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5350                           tu_stats->nr_uniq_abbrev_tables);
5351       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5352                           tu_stats->nr_symtabs);
5353       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5354                           tu_stats->nr_symtab_sharers);
5355       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5356                           tu_stats->nr_stmt_less_type_units);
5357     }
5358 }
5359
5360 /* Reader function for build_type_psymtabs.  */
5361
5362 static void
5363 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5364                             gdb_byte *info_ptr,
5365                             struct die_info *type_unit_die,
5366                             int has_children,
5367                             void *data)
5368 {
5369   struct objfile *objfile = dwarf2_per_objfile->objfile;
5370   struct dwarf2_cu *cu = reader->cu;
5371   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5372   struct type_unit_group *tu_group;
5373   struct attribute *attr;
5374   struct partial_die_info *first_die;
5375   CORE_ADDR lowpc, highpc;
5376   struct partial_symtab *pst;
5377
5378   gdb_assert (data == NULL);
5379
5380   if (! has_children)
5381     return;
5382
5383   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5384   tu_group = get_type_unit_group (cu, attr);
5385
5386   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5387
5388   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5389   cu->list_in_scope = &file_symbols;
5390   pst = create_partial_symtab (per_cu, "");
5391   pst->anonymous = 1;
5392
5393   first_die = load_partial_dies (reader, info_ptr, 1);
5394
5395   lowpc = (CORE_ADDR) -1;
5396   highpc = (CORE_ADDR) 0;
5397   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5398
5399   pst->n_global_syms = objfile->global_psymbols.next -
5400     (objfile->global_psymbols.list + pst->globals_offset);
5401   pst->n_static_syms = objfile->static_psymbols.next -
5402     (objfile->static_psymbols.list + pst->statics_offset);
5403   sort_pst_symbols (objfile, pst);
5404 }
5405
5406 /* Traversal function for build_type_psymtabs.  */
5407
5408 static int
5409 build_type_psymtab_dependencies (void **slot, void *info)
5410 {
5411   struct objfile *objfile = dwarf2_per_objfile->objfile;
5412   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5413   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5414   struct partial_symtab *pst = per_cu->v.psymtab;
5415   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5416   struct dwarf2_per_cu_data *iter;
5417   int i;
5418
5419   gdb_assert (len > 0);
5420
5421   pst->number_of_dependencies = len;
5422   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5423                                      len * sizeof (struct psymtab *));
5424   for (i = 0;
5425        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5426        ++i)
5427     {
5428       pst->dependencies[i] = iter->v.psymtab;
5429       iter->type_unit_group = tu_group;
5430     }
5431
5432   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5433
5434   return 1;
5435 }
5436
5437 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5438    Build partial symbol tables for the .debug_types comp-units.  */
5439
5440 static void
5441 build_type_psymtabs (struct objfile *objfile)
5442 {
5443   if (! create_all_type_units (objfile))
5444     return;
5445
5446   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5447
5448   /* Now that all TUs have been processed we can fill in the dependencies.  */
5449   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5450                           build_type_psymtab_dependencies, NULL);
5451 }
5452
5453 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5454
5455 static void
5456 psymtabs_addrmap_cleanup (void *o)
5457 {
5458   struct objfile *objfile = o;
5459
5460   objfile->psymtabs_addrmap = NULL;
5461 }
5462
5463 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5464
5465 static void
5466 set_partial_user (struct objfile *objfile)
5467 {
5468   int i;
5469
5470   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5471     {
5472       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5473       struct partial_symtab *pst = per_cu->v.psymtab;
5474       int j;
5475
5476       if (pst == NULL)
5477         continue;
5478
5479       for (j = 0; j < pst->number_of_dependencies; ++j)
5480         {
5481           /* Set the 'user' field only if it is not already set.  */
5482           if (pst->dependencies[j]->user == NULL)
5483             pst->dependencies[j]->user = pst;
5484         }
5485     }
5486 }
5487
5488 /* Build the partial symbol table by doing a quick pass through the
5489    .debug_info and .debug_abbrev sections.  */
5490
5491 static void
5492 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5493 {
5494   struct cleanup *back_to, *addrmap_cleanup;
5495   struct obstack temp_obstack;
5496   int i;
5497
5498   if (dwarf2_read_debug)
5499     {
5500       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5501                           objfile->name);
5502     }
5503
5504   dwarf2_per_objfile->reading_partial_symbols = 1;
5505
5506   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5507
5508   /* Any cached compilation units will be linked by the per-objfile
5509      read_in_chain.  Make sure to free them when we're done.  */
5510   back_to = make_cleanup (free_cached_comp_units, NULL);
5511
5512   build_type_psymtabs (objfile);
5513
5514   create_all_comp_units (objfile);
5515
5516   /* Create a temporary address map on a temporary obstack.  We later
5517      copy this to the final obstack.  */
5518   obstack_init (&temp_obstack);
5519   make_cleanup_obstack_free (&temp_obstack);
5520   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5521   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5522
5523   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5524     {
5525       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5526
5527       process_psymtab_comp_unit (per_cu, 0);
5528     }
5529
5530   set_partial_user (objfile);
5531
5532   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5533                                                     &objfile->objfile_obstack);
5534   discard_cleanups (addrmap_cleanup);
5535
5536   do_cleanups (back_to);
5537
5538   if (dwarf2_read_debug)
5539     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5540                         objfile->name);
5541 }
5542
5543 /* die_reader_func for load_partial_comp_unit.  */
5544
5545 static void
5546 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5547                                gdb_byte *info_ptr,
5548                                struct die_info *comp_unit_die,
5549                                int has_children,
5550                                void *data)
5551 {
5552   struct dwarf2_cu *cu = reader->cu;
5553
5554   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5555
5556   /* Check if comp unit has_children.
5557      If so, read the rest of the partial symbols from this comp unit.
5558      If not, there's no more debug_info for this comp unit.  */
5559   if (has_children)
5560     load_partial_dies (reader, info_ptr, 0);
5561 }
5562
5563 /* Load the partial DIEs for a secondary CU into memory.
5564    This is also used when rereading a primary CU with load_all_dies.  */
5565
5566 static void
5567 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5568 {
5569   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5570                            load_partial_comp_unit_reader, NULL);
5571 }
5572
5573 static void
5574 read_comp_units_from_section (struct objfile *objfile,
5575                               struct dwarf2_section_info *section,
5576                               unsigned int is_dwz,
5577                               int *n_allocated,
5578                               int *n_comp_units,
5579                               struct dwarf2_per_cu_data ***all_comp_units)
5580 {
5581   gdb_byte *info_ptr;
5582   bfd *abfd = section->asection->owner;
5583
5584   dwarf2_read_section (objfile, section);
5585
5586   info_ptr = section->buffer;
5587
5588   while (info_ptr < section->buffer + section->size)
5589     {
5590       unsigned int length, initial_length_size;
5591       struct dwarf2_per_cu_data *this_cu;
5592       sect_offset offset;
5593
5594       offset.sect_off = info_ptr - section->buffer;
5595
5596       /* Read just enough information to find out where the next
5597          compilation unit is.  */
5598       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5599
5600       /* Save the compilation unit for later lookup.  */
5601       this_cu = obstack_alloc (&objfile->objfile_obstack,
5602                                sizeof (struct dwarf2_per_cu_data));
5603       memset (this_cu, 0, sizeof (*this_cu));
5604       this_cu->offset = offset;
5605       this_cu->length = length + initial_length_size;
5606       this_cu->is_dwz = is_dwz;
5607       this_cu->objfile = objfile;
5608       this_cu->info_or_types_section = section;
5609
5610       if (*n_comp_units == *n_allocated)
5611         {
5612           *n_allocated *= 2;
5613           *all_comp_units = xrealloc (*all_comp_units,
5614                                       *n_allocated
5615                                       * sizeof (struct dwarf2_per_cu_data *));
5616         }
5617       (*all_comp_units)[*n_comp_units] = this_cu;
5618       ++*n_comp_units;
5619
5620       info_ptr = info_ptr + this_cu->length;
5621     }
5622 }
5623
5624 /* Create a list of all compilation units in OBJFILE.
5625    This is only done for -readnow and building partial symtabs.  */
5626
5627 static void
5628 create_all_comp_units (struct objfile *objfile)
5629 {
5630   int n_allocated;
5631   int n_comp_units;
5632   struct dwarf2_per_cu_data **all_comp_units;
5633
5634   n_comp_units = 0;
5635   n_allocated = 10;
5636   all_comp_units = xmalloc (n_allocated
5637                             * sizeof (struct dwarf2_per_cu_data *));
5638
5639   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5640                                 &n_allocated, &n_comp_units, &all_comp_units);
5641
5642   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5643     {
5644       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5645
5646       read_comp_units_from_section (objfile, &dwz->info, 1,
5647                                     &n_allocated, &n_comp_units,
5648                                     &all_comp_units);
5649     }
5650
5651   dwarf2_per_objfile->all_comp_units
5652     = obstack_alloc (&objfile->objfile_obstack,
5653                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5654   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5655           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5656   xfree (all_comp_units);
5657   dwarf2_per_objfile->n_comp_units = n_comp_units;
5658 }
5659
5660 /* Process all loaded DIEs for compilation unit CU, starting at
5661    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5662    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5663    DW_AT_ranges).  If NEED_PC is set, then this function will set
5664    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5665    and record the covered ranges in the addrmap.  */
5666
5667 static void
5668 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5669                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5670 {
5671   struct partial_die_info *pdi;
5672
5673   /* Now, march along the PDI's, descending into ones which have
5674      interesting children but skipping the children of the other ones,
5675      until we reach the end of the compilation unit.  */
5676
5677   pdi = first_die;
5678
5679   while (pdi != NULL)
5680     {
5681       fixup_partial_die (pdi, cu);
5682
5683       /* Anonymous namespaces or modules have no name but have interesting
5684          children, so we need to look at them.  Ditto for anonymous
5685          enums.  */
5686
5687       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5688           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5689           || pdi->tag == DW_TAG_imported_unit)
5690         {
5691           switch (pdi->tag)
5692             {
5693             case DW_TAG_subprogram:
5694               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5695               break;
5696             case DW_TAG_constant:
5697             case DW_TAG_variable:
5698             case DW_TAG_typedef:
5699             case DW_TAG_union_type:
5700               if (!pdi->is_declaration)
5701                 {
5702                   add_partial_symbol (pdi, cu);
5703                 }
5704               break;
5705             case DW_TAG_class_type:
5706             case DW_TAG_interface_type:
5707             case DW_TAG_structure_type:
5708               if (!pdi->is_declaration)
5709                 {
5710                   add_partial_symbol (pdi, cu);
5711                 }
5712               break;
5713             case DW_TAG_enumeration_type:
5714               if (!pdi->is_declaration)
5715                 add_partial_enumeration (pdi, cu);
5716               break;
5717             case DW_TAG_base_type:
5718             case DW_TAG_subrange_type:
5719               /* File scope base type definitions are added to the partial
5720                  symbol table.  */
5721               add_partial_symbol (pdi, cu);
5722               break;
5723             case DW_TAG_namespace:
5724               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5725               break;
5726             case DW_TAG_module:
5727               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5728               break;
5729             case DW_TAG_imported_unit:
5730               {
5731                 struct dwarf2_per_cu_data *per_cu;
5732
5733                 /* For now we don't handle imported units in type units.  */
5734                 if (cu->per_cu->is_debug_types)
5735                   {
5736                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5737                              " supported in type units [in module %s]"),
5738                            cu->objfile->name);
5739                   }
5740
5741                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5742                                                            pdi->is_dwz,
5743                                                            cu->objfile);
5744
5745                 /* Go read the partial unit, if needed.  */
5746                 if (per_cu->v.psymtab == NULL)
5747                   process_psymtab_comp_unit (per_cu, 1);
5748
5749                 VEC_safe_push (dwarf2_per_cu_ptr,
5750                                cu->per_cu->imported_symtabs, per_cu);
5751               }
5752               break;
5753             default:
5754               break;
5755             }
5756         }
5757
5758       /* If the die has a sibling, skip to the sibling.  */
5759
5760       pdi = pdi->die_sibling;
5761     }
5762 }
5763
5764 /* Functions used to compute the fully scoped name of a partial DIE.
5765
5766    Normally, this is simple.  For C++, the parent DIE's fully scoped
5767    name is concatenated with "::" and the partial DIE's name.  For
5768    Java, the same thing occurs except that "." is used instead of "::".
5769    Enumerators are an exception; they use the scope of their parent
5770    enumeration type, i.e. the name of the enumeration type is not
5771    prepended to the enumerator.
5772
5773    There are two complexities.  One is DW_AT_specification; in this
5774    case "parent" means the parent of the target of the specification,
5775    instead of the direct parent of the DIE.  The other is compilers
5776    which do not emit DW_TAG_namespace; in this case we try to guess
5777    the fully qualified name of structure types from their members'
5778    linkage names.  This must be done using the DIE's children rather
5779    than the children of any DW_AT_specification target.  We only need
5780    to do this for structures at the top level, i.e. if the target of
5781    any DW_AT_specification (if any; otherwise the DIE itself) does not
5782    have a parent.  */
5783
5784 /* Compute the scope prefix associated with PDI's parent, in
5785    compilation unit CU.  The result will be allocated on CU's
5786    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5787    field.  NULL is returned if no prefix is necessary.  */
5788 static const char *
5789 partial_die_parent_scope (struct partial_die_info *pdi,
5790                           struct dwarf2_cu *cu)
5791 {
5792   const char *grandparent_scope;
5793   struct partial_die_info *parent, *real_pdi;
5794
5795   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5796      then this means the parent of the specification DIE.  */
5797
5798   real_pdi = pdi;
5799   while (real_pdi->has_specification)
5800     real_pdi = find_partial_die (real_pdi->spec_offset,
5801                                  real_pdi->spec_is_dwz, cu);
5802
5803   parent = real_pdi->die_parent;
5804   if (parent == NULL)
5805     return NULL;
5806
5807   if (parent->scope_set)
5808     return parent->scope;
5809
5810   fixup_partial_die (parent, cu);
5811
5812   grandparent_scope = partial_die_parent_scope (parent, cu);
5813
5814   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5815      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5816      Work around this problem here.  */
5817   if (cu->language == language_cplus
5818       && parent->tag == DW_TAG_namespace
5819       && strcmp (parent->name, "::") == 0
5820       && grandparent_scope == NULL)
5821     {
5822       parent->scope = NULL;
5823       parent->scope_set = 1;
5824       return NULL;
5825     }
5826
5827   if (pdi->tag == DW_TAG_enumerator)
5828     /* Enumerators should not get the name of the enumeration as a prefix.  */
5829     parent->scope = grandparent_scope;
5830   else if (parent->tag == DW_TAG_namespace
5831       || parent->tag == DW_TAG_module
5832       || parent->tag == DW_TAG_structure_type
5833       || parent->tag == DW_TAG_class_type
5834       || parent->tag == DW_TAG_interface_type
5835       || parent->tag == DW_TAG_union_type
5836       || parent->tag == DW_TAG_enumeration_type)
5837     {
5838       if (grandparent_scope == NULL)
5839         parent->scope = parent->name;
5840       else
5841         parent->scope = typename_concat (&cu->comp_unit_obstack,
5842                                          grandparent_scope,
5843                                          parent->name, 0, cu);
5844     }
5845   else
5846     {
5847       /* FIXME drow/2004-04-01: What should we be doing with
5848          function-local names?  For partial symbols, we should probably be
5849          ignoring them.  */
5850       complaint (&symfile_complaints,
5851                  _("unhandled containing DIE tag %d for DIE at %d"),
5852                  parent->tag, pdi->offset.sect_off);
5853       parent->scope = grandparent_scope;
5854     }
5855
5856   parent->scope_set = 1;
5857   return parent->scope;
5858 }
5859
5860 /* Return the fully scoped name associated with PDI, from compilation unit
5861    CU.  The result will be allocated with malloc.  */
5862
5863 static char *
5864 partial_die_full_name (struct partial_die_info *pdi,
5865                        struct dwarf2_cu *cu)
5866 {
5867   const char *parent_scope;
5868
5869   /* If this is a template instantiation, we can not work out the
5870      template arguments from partial DIEs.  So, unfortunately, we have
5871      to go through the full DIEs.  At least any work we do building
5872      types here will be reused if full symbols are loaded later.  */
5873   if (pdi->has_template_arguments)
5874     {
5875       fixup_partial_die (pdi, cu);
5876
5877       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5878         {
5879           struct die_info *die;
5880           struct attribute attr;
5881           struct dwarf2_cu *ref_cu = cu;
5882
5883           /* DW_FORM_ref_addr is using section offset.  */
5884           attr.name = 0;
5885           attr.form = DW_FORM_ref_addr;
5886           attr.u.unsnd = pdi->offset.sect_off;
5887           die = follow_die_ref (NULL, &attr, &ref_cu);
5888
5889           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5890         }
5891     }
5892
5893   parent_scope = partial_die_parent_scope (pdi, cu);
5894   if (parent_scope == NULL)
5895     return NULL;
5896   else
5897     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5898 }
5899
5900 static void
5901 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5902 {
5903   struct objfile *objfile = cu->objfile;
5904   CORE_ADDR addr = 0;
5905   const char *actual_name = NULL;
5906   CORE_ADDR baseaddr;
5907   char *built_actual_name;
5908
5909   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5910
5911   built_actual_name = partial_die_full_name (pdi, cu);
5912   if (built_actual_name != NULL)
5913     actual_name = built_actual_name;
5914
5915   if (actual_name == NULL)
5916     actual_name = pdi->name;
5917
5918   switch (pdi->tag)
5919     {
5920     case DW_TAG_subprogram:
5921       if (pdi->is_external || cu->language == language_ada)
5922         {
5923           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5924              of the global scope.  But in Ada, we want to be able to access
5925              nested procedures globally.  So all Ada subprograms are stored
5926              in the global scope.  */
5927           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5928              mst_text, objfile); */
5929           add_psymbol_to_list (actual_name, strlen (actual_name),
5930                                built_actual_name != NULL,
5931                                VAR_DOMAIN, LOC_BLOCK,
5932                                &objfile->global_psymbols,
5933                                0, pdi->lowpc + baseaddr,
5934                                cu->language, objfile);
5935         }
5936       else
5937         {
5938           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5939              mst_file_text, objfile); */
5940           add_psymbol_to_list (actual_name, strlen (actual_name),
5941                                built_actual_name != NULL,
5942                                VAR_DOMAIN, LOC_BLOCK,
5943                                &objfile->static_psymbols,
5944                                0, pdi->lowpc + baseaddr,
5945                                cu->language, objfile);
5946         }
5947       break;
5948     case DW_TAG_constant:
5949       {
5950         struct psymbol_allocation_list *list;
5951
5952         if (pdi->is_external)
5953           list = &objfile->global_psymbols;
5954         else
5955           list = &objfile->static_psymbols;
5956         add_psymbol_to_list (actual_name, strlen (actual_name),
5957                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
5958                              list, 0, 0, cu->language, objfile);
5959       }
5960       break;
5961     case DW_TAG_variable:
5962       if (pdi->d.locdesc)
5963         addr = decode_locdesc (pdi->d.locdesc, cu);
5964
5965       if (pdi->d.locdesc
5966           && addr == 0
5967           && !dwarf2_per_objfile->has_section_at_zero)
5968         {
5969           /* A global or static variable may also have been stripped
5970              out by the linker if unused, in which case its address
5971              will be nullified; do not add such variables into partial
5972              symbol table then.  */
5973         }
5974       else if (pdi->is_external)
5975         {
5976           /* Global Variable.
5977              Don't enter into the minimal symbol tables as there is
5978              a minimal symbol table entry from the ELF symbols already.
5979              Enter into partial symbol table if it has a location
5980              descriptor or a type.
5981              If the location descriptor is missing, new_symbol will create
5982              a LOC_UNRESOLVED symbol, the address of the variable will then
5983              be determined from the minimal symbol table whenever the variable
5984              is referenced.
5985              The address for the partial symbol table entry is not
5986              used by GDB, but it comes in handy for debugging partial symbol
5987              table building.  */
5988
5989           if (pdi->d.locdesc || pdi->has_type)
5990             add_psymbol_to_list (actual_name, strlen (actual_name),
5991                                  built_actual_name != NULL,
5992                                  VAR_DOMAIN, LOC_STATIC,
5993                                  &objfile->global_psymbols,
5994                                  0, addr + baseaddr,
5995                                  cu->language, objfile);
5996         }
5997       else
5998         {
5999           /* Static Variable.  Skip symbols without location descriptors.  */
6000           if (pdi->d.locdesc == NULL)
6001             {
6002               xfree (built_actual_name);
6003               return;
6004             }
6005           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6006              mst_file_data, objfile); */
6007           add_psymbol_to_list (actual_name, strlen (actual_name),
6008                                built_actual_name != NULL,
6009                                VAR_DOMAIN, LOC_STATIC,
6010                                &objfile->static_psymbols,
6011                                0, addr + baseaddr,
6012                                cu->language, objfile);
6013         }
6014       break;
6015     case DW_TAG_typedef:
6016     case DW_TAG_base_type:
6017     case DW_TAG_subrange_type:
6018       add_psymbol_to_list (actual_name, strlen (actual_name),
6019                            built_actual_name != NULL,
6020                            VAR_DOMAIN, LOC_TYPEDEF,
6021                            &objfile->static_psymbols,
6022                            0, (CORE_ADDR) 0, cu->language, objfile);
6023       break;
6024     case DW_TAG_namespace:
6025       add_psymbol_to_list (actual_name, strlen (actual_name),
6026                            built_actual_name != NULL,
6027                            VAR_DOMAIN, LOC_TYPEDEF,
6028                            &objfile->global_psymbols,
6029                            0, (CORE_ADDR) 0, cu->language, objfile);
6030       break;
6031     case DW_TAG_class_type:
6032     case DW_TAG_interface_type:
6033     case DW_TAG_structure_type:
6034     case DW_TAG_union_type:
6035     case DW_TAG_enumeration_type:
6036       /* Skip external references.  The DWARF standard says in the section
6037          about "Structure, Union, and Class Type Entries": "An incomplete
6038          structure, union or class type is represented by a structure,
6039          union or class entry that does not have a byte size attribute
6040          and that has a DW_AT_declaration attribute."  */
6041       if (!pdi->has_byte_size && pdi->is_declaration)
6042         {
6043           xfree (built_actual_name);
6044           return;
6045         }
6046
6047       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6048          static vs. global.  */
6049       add_psymbol_to_list (actual_name, strlen (actual_name),
6050                            built_actual_name != NULL,
6051                            STRUCT_DOMAIN, LOC_TYPEDEF,
6052                            (cu->language == language_cplus
6053                             || cu->language == language_java)
6054                            ? &objfile->global_psymbols
6055                            : &objfile->static_psymbols,
6056                            0, (CORE_ADDR) 0, cu->language, objfile);
6057
6058       break;
6059     case DW_TAG_enumerator:
6060       add_psymbol_to_list (actual_name, strlen (actual_name),
6061                            built_actual_name != NULL,
6062                            VAR_DOMAIN, LOC_CONST,
6063                            (cu->language == language_cplus
6064                             || cu->language == language_java)
6065                            ? &objfile->global_psymbols
6066                            : &objfile->static_psymbols,
6067                            0, (CORE_ADDR) 0, cu->language, objfile);
6068       break;
6069     default:
6070       break;
6071     }
6072
6073   xfree (built_actual_name);
6074 }
6075
6076 /* Read a partial die corresponding to a namespace; also, add a symbol
6077    corresponding to that namespace to the symbol table.  NAMESPACE is
6078    the name of the enclosing namespace.  */
6079
6080 static void
6081 add_partial_namespace (struct partial_die_info *pdi,
6082                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6083                        int need_pc, struct dwarf2_cu *cu)
6084 {
6085   /* Add a symbol for the namespace.  */
6086
6087   add_partial_symbol (pdi, cu);
6088
6089   /* Now scan partial symbols in that namespace.  */
6090
6091   if (pdi->has_children)
6092     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6093 }
6094
6095 /* Read a partial die corresponding to a Fortran module.  */
6096
6097 static void
6098 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6099                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6100 {
6101   /* Now scan partial symbols in that module.  */
6102
6103   if (pdi->has_children)
6104     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6105 }
6106
6107 /* Read a partial die corresponding to a subprogram and create a partial
6108    symbol for that subprogram.  When the CU language allows it, this
6109    routine also defines a partial symbol for each nested subprogram
6110    that this subprogram contains.
6111
6112    DIE my also be a lexical block, in which case we simply search
6113    recursively for suprograms defined inside that lexical block.
6114    Again, this is only performed when the CU language allows this
6115    type of definitions.  */
6116
6117 static void
6118 add_partial_subprogram (struct partial_die_info *pdi,
6119                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6120                         int need_pc, struct dwarf2_cu *cu)
6121 {
6122   if (pdi->tag == DW_TAG_subprogram)
6123     {
6124       if (pdi->has_pc_info)
6125         {
6126           if (pdi->lowpc < *lowpc)
6127             *lowpc = pdi->lowpc;
6128           if (pdi->highpc > *highpc)
6129             *highpc = pdi->highpc;
6130           if (need_pc)
6131             {
6132               CORE_ADDR baseaddr;
6133               struct objfile *objfile = cu->objfile;
6134
6135               baseaddr = ANOFFSET (objfile->section_offsets,
6136                                    SECT_OFF_TEXT (objfile));
6137               addrmap_set_empty (objfile->psymtabs_addrmap,
6138                                  pdi->lowpc + baseaddr,
6139                                  pdi->highpc - 1 + baseaddr,
6140                                  cu->per_cu->v.psymtab);
6141             }
6142         }
6143
6144       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6145         {
6146           if (!pdi->is_declaration)
6147             /* Ignore subprogram DIEs that do not have a name, they are
6148                illegal.  Do not emit a complaint at this point, we will
6149                do so when we convert this psymtab into a symtab.  */
6150             if (pdi->name)
6151               add_partial_symbol (pdi, cu);
6152         }
6153     }
6154
6155   if (! pdi->has_children)
6156     return;
6157
6158   if (cu->language == language_ada)
6159     {
6160       pdi = pdi->die_child;
6161       while (pdi != NULL)
6162         {
6163           fixup_partial_die (pdi, cu);
6164           if (pdi->tag == DW_TAG_subprogram
6165               || pdi->tag == DW_TAG_lexical_block)
6166             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6167           pdi = pdi->die_sibling;
6168         }
6169     }
6170 }
6171
6172 /* Read a partial die corresponding to an enumeration type.  */
6173
6174 static void
6175 add_partial_enumeration (struct partial_die_info *enum_pdi,
6176                          struct dwarf2_cu *cu)
6177 {
6178   struct partial_die_info *pdi;
6179
6180   if (enum_pdi->name != NULL)
6181     add_partial_symbol (enum_pdi, cu);
6182
6183   pdi = enum_pdi->die_child;
6184   while (pdi)
6185     {
6186       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6187         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6188       else
6189         add_partial_symbol (pdi, cu);
6190       pdi = pdi->die_sibling;
6191     }
6192 }
6193
6194 /* Return the initial uleb128 in the die at INFO_PTR.  */
6195
6196 static unsigned int
6197 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
6198 {
6199   unsigned int bytes_read;
6200
6201   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6202 }
6203
6204 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6205    Return the corresponding abbrev, or NULL if the number is zero (indicating
6206    an empty DIE).  In either case *BYTES_READ will be set to the length of
6207    the initial number.  */
6208
6209 static struct abbrev_info *
6210 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
6211                  struct dwarf2_cu *cu)
6212 {
6213   bfd *abfd = cu->objfile->obfd;
6214   unsigned int abbrev_number;
6215   struct abbrev_info *abbrev;
6216
6217   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6218
6219   if (abbrev_number == 0)
6220     return NULL;
6221
6222   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6223   if (!abbrev)
6224     {
6225       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6226              abbrev_number, bfd_get_filename (abfd));
6227     }
6228
6229   return abbrev;
6230 }
6231
6232 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6233    Returns a pointer to the end of a series of DIEs, terminated by an empty
6234    DIE.  Any children of the skipped DIEs will also be skipped.  */
6235
6236 static gdb_byte *
6237 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
6238 {
6239   struct dwarf2_cu *cu = reader->cu;
6240   struct abbrev_info *abbrev;
6241   unsigned int bytes_read;
6242
6243   while (1)
6244     {
6245       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6246       if (abbrev == NULL)
6247         return info_ptr + bytes_read;
6248       else
6249         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6250     }
6251 }
6252
6253 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6254    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6255    abbrev corresponding to that skipped uleb128 should be passed in
6256    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6257    children.  */
6258
6259 static gdb_byte *
6260 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
6261               struct abbrev_info *abbrev)
6262 {
6263   unsigned int bytes_read;
6264   struct attribute attr;
6265   bfd *abfd = reader->abfd;
6266   struct dwarf2_cu *cu = reader->cu;
6267   gdb_byte *buffer = reader->buffer;
6268   const gdb_byte *buffer_end = reader->buffer_end;
6269   gdb_byte *start_info_ptr = info_ptr;
6270   unsigned int form, i;
6271
6272   for (i = 0; i < abbrev->num_attrs; i++)
6273     {
6274       /* The only abbrev we care about is DW_AT_sibling.  */
6275       if (abbrev->attrs[i].name == DW_AT_sibling)
6276         {
6277           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6278           if (attr.form == DW_FORM_ref_addr)
6279             complaint (&symfile_complaints,
6280                        _("ignoring absolute DW_AT_sibling"));
6281           else
6282             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6283         }
6284
6285       /* If it isn't DW_AT_sibling, skip this attribute.  */
6286       form = abbrev->attrs[i].form;
6287     skip_attribute:
6288       switch (form)
6289         {
6290         case DW_FORM_ref_addr:
6291           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6292              and later it is offset sized.  */
6293           if (cu->header.version == 2)
6294             info_ptr += cu->header.addr_size;
6295           else
6296             info_ptr += cu->header.offset_size;
6297           break;
6298         case DW_FORM_GNU_ref_alt:
6299           info_ptr += cu->header.offset_size;
6300           break;
6301         case DW_FORM_addr:
6302           info_ptr += cu->header.addr_size;
6303           break;
6304         case DW_FORM_data1:
6305         case DW_FORM_ref1:
6306         case DW_FORM_flag:
6307           info_ptr += 1;
6308           break;
6309         case DW_FORM_flag_present:
6310           break;
6311         case DW_FORM_data2:
6312         case DW_FORM_ref2:
6313           info_ptr += 2;
6314           break;
6315         case DW_FORM_data4:
6316         case DW_FORM_ref4:
6317           info_ptr += 4;
6318           break;
6319         case DW_FORM_data8:
6320         case DW_FORM_ref8:
6321         case DW_FORM_ref_sig8:
6322           info_ptr += 8;
6323           break;
6324         case DW_FORM_string:
6325           read_direct_string (abfd, info_ptr, &bytes_read);
6326           info_ptr += bytes_read;
6327           break;
6328         case DW_FORM_sec_offset:
6329         case DW_FORM_strp:
6330         case DW_FORM_GNU_strp_alt:
6331           info_ptr += cu->header.offset_size;
6332           break;
6333         case DW_FORM_exprloc:
6334         case DW_FORM_block:
6335           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6336           info_ptr += bytes_read;
6337           break;
6338         case DW_FORM_block1:
6339           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6340           break;
6341         case DW_FORM_block2:
6342           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6343           break;
6344         case DW_FORM_block4:
6345           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6346           break;
6347         case DW_FORM_sdata:
6348         case DW_FORM_udata:
6349         case DW_FORM_ref_udata:
6350         case DW_FORM_GNU_addr_index:
6351         case DW_FORM_GNU_str_index:
6352           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6353           break;
6354         case DW_FORM_indirect:
6355           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6356           info_ptr += bytes_read;
6357           /* We need to continue parsing from here, so just go back to
6358              the top.  */
6359           goto skip_attribute;
6360
6361         default:
6362           error (_("Dwarf Error: Cannot handle %s "
6363                    "in DWARF reader [in module %s]"),
6364                  dwarf_form_name (form),
6365                  bfd_get_filename (abfd));
6366         }
6367     }
6368
6369   if (abbrev->has_children)
6370     return skip_children (reader, info_ptr);
6371   else
6372     return info_ptr;
6373 }
6374
6375 /* Locate ORIG_PDI's sibling.
6376    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6377
6378 static gdb_byte *
6379 locate_pdi_sibling (const struct die_reader_specs *reader,
6380                     struct partial_die_info *orig_pdi,
6381                     gdb_byte *info_ptr)
6382 {
6383   /* Do we know the sibling already?  */
6384
6385   if (orig_pdi->sibling)
6386     return orig_pdi->sibling;
6387
6388   /* Are there any children to deal with?  */
6389
6390   if (!orig_pdi->has_children)
6391     return info_ptr;
6392
6393   /* Skip the children the long way.  */
6394
6395   return skip_children (reader, info_ptr);
6396 }
6397
6398 /* Expand this partial symbol table into a full symbol table.  SELF is
6399    not NULL.  */
6400
6401 static void
6402 dwarf2_read_symtab (struct partial_symtab *self,
6403                     struct objfile *objfile)
6404 {
6405   if (self->readin)
6406     {
6407       warning (_("bug: psymtab for %s is already read in."),
6408                self->filename);
6409     }
6410   else
6411     {
6412       if (info_verbose)
6413         {
6414           printf_filtered (_("Reading in symbols for %s..."),
6415                            self->filename);
6416           gdb_flush (gdb_stdout);
6417         }
6418
6419       /* Restore our global data.  */
6420       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6421
6422       /* If this psymtab is constructed from a debug-only objfile, the
6423          has_section_at_zero flag will not necessarily be correct.  We
6424          can get the correct value for this flag by looking at the data
6425          associated with the (presumably stripped) associated objfile.  */
6426       if (objfile->separate_debug_objfile_backlink)
6427         {
6428           struct dwarf2_per_objfile *dpo_backlink
6429             = objfile_data (objfile->separate_debug_objfile_backlink,
6430                             dwarf2_objfile_data_key);
6431
6432           dwarf2_per_objfile->has_section_at_zero
6433             = dpo_backlink->has_section_at_zero;
6434         }
6435
6436       dwarf2_per_objfile->reading_partial_symbols = 0;
6437
6438       psymtab_to_symtab_1 (self);
6439
6440       /* Finish up the debug error message.  */
6441       if (info_verbose)
6442         printf_filtered (_("done.\n"));
6443     }
6444
6445   process_cu_includes ();
6446 }
6447 \f
6448 /* Reading in full CUs.  */
6449
6450 /* Add PER_CU to the queue.  */
6451
6452 static void
6453 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6454                  enum language pretend_language)
6455 {
6456   struct dwarf2_queue_item *item;
6457
6458   per_cu->queued = 1;
6459   item = xmalloc (sizeof (*item));
6460   item->per_cu = per_cu;
6461   item->pretend_language = pretend_language;
6462   item->next = NULL;
6463
6464   if (dwarf2_queue == NULL)
6465     dwarf2_queue = item;
6466   else
6467     dwarf2_queue_tail->next = item;
6468
6469   dwarf2_queue_tail = item;
6470 }
6471
6472 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6473    unit and add it to our queue.
6474    The result is non-zero if PER_CU was queued, otherwise the result is zero
6475    meaning either PER_CU is already queued or it is already loaded.  */
6476
6477 static int
6478 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6479                        struct dwarf2_per_cu_data *per_cu,
6480                        enum language pretend_language)
6481 {
6482   /* We may arrive here during partial symbol reading, if we need full
6483      DIEs to process an unusual case (e.g. template arguments).  Do
6484      not queue PER_CU, just tell our caller to load its DIEs.  */
6485   if (dwarf2_per_objfile->reading_partial_symbols)
6486     {
6487       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6488         return 1;
6489       return 0;
6490     }
6491
6492   /* Mark the dependence relation so that we don't flush PER_CU
6493      too early.  */
6494   dwarf2_add_dependence (this_cu, per_cu);
6495
6496   /* If it's already on the queue, we have nothing to do.  */
6497   if (per_cu->queued)
6498     return 0;
6499
6500   /* If the compilation unit is already loaded, just mark it as
6501      used.  */
6502   if (per_cu->cu != NULL)
6503     {
6504       per_cu->cu->last_used = 0;
6505       return 0;
6506     }
6507
6508   /* Add it to the queue.  */
6509   queue_comp_unit (per_cu, pretend_language);
6510
6511   return 1;
6512 }
6513
6514 /* Process the queue.  */
6515
6516 static void
6517 process_queue (void)
6518 {
6519   struct dwarf2_queue_item *item, *next_item;
6520
6521   if (dwarf2_read_debug)
6522     {
6523       fprintf_unfiltered (gdb_stdlog,
6524                           "Expanding one or more symtabs of objfile %s ...\n",
6525                           dwarf2_per_objfile->objfile->name);
6526     }
6527
6528   /* The queue starts out with one item, but following a DIE reference
6529      may load a new CU, adding it to the end of the queue.  */
6530   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6531     {
6532       if (dwarf2_per_objfile->using_index
6533           ? !item->per_cu->v.quick->symtab
6534           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6535         {
6536           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6537
6538           if (dwarf2_read_debug)
6539             {
6540               fprintf_unfiltered (gdb_stdlog,
6541                                   "Expanding symtab of %s at offset 0x%x\n",
6542                                   per_cu->is_debug_types ? "TU" : "CU",
6543                                   per_cu->offset.sect_off);
6544             }
6545
6546           if (per_cu->is_debug_types)
6547             process_full_type_unit (per_cu, item->pretend_language);
6548           else
6549             process_full_comp_unit (per_cu, item->pretend_language);
6550
6551           if (dwarf2_read_debug)
6552             {
6553               fprintf_unfiltered (gdb_stdlog,
6554                                   "Done expanding %s at offset 0x%x\n",
6555                                   per_cu->is_debug_types ? "TU" : "CU",
6556                                   per_cu->offset.sect_off);
6557             }
6558         }
6559
6560       item->per_cu->queued = 0;
6561       next_item = item->next;
6562       xfree (item);
6563     }
6564
6565   dwarf2_queue_tail = NULL;
6566
6567   if (dwarf2_read_debug)
6568     {
6569       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6570                           dwarf2_per_objfile->objfile->name);
6571     }
6572 }
6573
6574 /* Free all allocated queue entries.  This function only releases anything if
6575    an error was thrown; if the queue was processed then it would have been
6576    freed as we went along.  */
6577
6578 static void
6579 dwarf2_release_queue (void *dummy)
6580 {
6581   struct dwarf2_queue_item *item, *last;
6582
6583   item = dwarf2_queue;
6584   while (item)
6585     {
6586       /* Anything still marked queued is likely to be in an
6587          inconsistent state, so discard it.  */
6588       if (item->per_cu->queued)
6589         {
6590           if (item->per_cu->cu != NULL)
6591             free_one_cached_comp_unit (item->per_cu);
6592           item->per_cu->queued = 0;
6593         }
6594
6595       last = item;
6596       item = item->next;
6597       xfree (last);
6598     }
6599
6600   dwarf2_queue = dwarf2_queue_tail = NULL;
6601 }
6602
6603 /* Read in full symbols for PST, and anything it depends on.  */
6604
6605 static void
6606 psymtab_to_symtab_1 (struct partial_symtab *pst)
6607 {
6608   struct dwarf2_per_cu_data *per_cu;
6609   int i;
6610
6611   if (pst->readin)
6612     return;
6613
6614   for (i = 0; i < pst->number_of_dependencies; i++)
6615     if (!pst->dependencies[i]->readin
6616         && pst->dependencies[i]->user == NULL)
6617       {
6618         /* Inform about additional files that need to be read in.  */
6619         if (info_verbose)
6620           {
6621             /* FIXME: i18n: Need to make this a single string.  */
6622             fputs_filtered (" ", gdb_stdout);
6623             wrap_here ("");
6624             fputs_filtered ("and ", gdb_stdout);
6625             wrap_here ("");
6626             printf_filtered ("%s...", pst->dependencies[i]->filename);
6627             wrap_here ("");     /* Flush output.  */
6628             gdb_flush (gdb_stdout);
6629           }
6630         psymtab_to_symtab_1 (pst->dependencies[i]);
6631       }
6632
6633   per_cu = pst->read_symtab_private;
6634
6635   if (per_cu == NULL)
6636     {
6637       /* It's an include file, no symbols to read for it.
6638          Everything is in the parent symtab.  */
6639       pst->readin = 1;
6640       return;
6641     }
6642
6643   dw2_do_instantiate_symtab (per_cu);
6644 }
6645
6646 /* Trivial hash function for die_info: the hash value of a DIE
6647    is its offset in .debug_info for this objfile.  */
6648
6649 static hashval_t
6650 die_hash (const void *item)
6651 {
6652   const struct die_info *die = item;
6653
6654   return die->offset.sect_off;
6655 }
6656
6657 /* Trivial comparison function for die_info structures: two DIEs
6658    are equal if they have the same offset.  */
6659
6660 static int
6661 die_eq (const void *item_lhs, const void *item_rhs)
6662 {
6663   const struct die_info *die_lhs = item_lhs;
6664   const struct die_info *die_rhs = item_rhs;
6665
6666   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6667 }
6668
6669 /* die_reader_func for load_full_comp_unit.
6670    This is identical to read_signatured_type_reader,
6671    but is kept separate for now.  */
6672
6673 static void
6674 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6675                             gdb_byte *info_ptr,
6676                             struct die_info *comp_unit_die,
6677                             int has_children,
6678                             void *data)
6679 {
6680   struct dwarf2_cu *cu = reader->cu;
6681   enum language *language_ptr = data;
6682
6683   gdb_assert (cu->die_hash == NULL);
6684   cu->die_hash =
6685     htab_create_alloc_ex (cu->header.length / 12,
6686                           die_hash,
6687                           die_eq,
6688                           NULL,
6689                           &cu->comp_unit_obstack,
6690                           hashtab_obstack_allocate,
6691                           dummy_obstack_deallocate);
6692
6693   if (has_children)
6694     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6695                                                   &info_ptr, comp_unit_die);
6696   cu->dies = comp_unit_die;
6697   /* comp_unit_die is not stored in die_hash, no need.  */
6698
6699   /* We try not to read any attributes in this function, because not
6700      all CUs needed for references have been loaded yet, and symbol
6701      table processing isn't initialized.  But we have to set the CU language,
6702      or we won't be able to build types correctly.
6703      Similarly, if we do not read the producer, we can not apply
6704      producer-specific interpretation.  */
6705   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6706 }
6707
6708 /* Load the DIEs associated with PER_CU into memory.  */
6709
6710 static void
6711 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6712                      enum language pretend_language)
6713 {
6714   gdb_assert (! this_cu->is_debug_types);
6715
6716   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6717                            load_full_comp_unit_reader, &pretend_language);
6718 }
6719
6720 /* Add a DIE to the delayed physname list.  */
6721
6722 static void
6723 add_to_method_list (struct type *type, int fnfield_index, int index,
6724                     const char *name, struct die_info *die,
6725                     struct dwarf2_cu *cu)
6726 {
6727   struct delayed_method_info mi;
6728   mi.type = type;
6729   mi.fnfield_index = fnfield_index;
6730   mi.index = index;
6731   mi.name = name;
6732   mi.die = die;
6733   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6734 }
6735
6736 /* A cleanup for freeing the delayed method list.  */
6737
6738 static void
6739 free_delayed_list (void *ptr)
6740 {
6741   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6742   if (cu->method_list != NULL)
6743     {
6744       VEC_free (delayed_method_info, cu->method_list);
6745       cu->method_list = NULL;
6746     }
6747 }
6748
6749 /* Compute the physnames of any methods on the CU's method list.
6750
6751    The computation of method physnames is delayed in order to avoid the
6752    (bad) condition that one of the method's formal parameters is of an as yet
6753    incomplete type.  */
6754
6755 static void
6756 compute_delayed_physnames (struct dwarf2_cu *cu)
6757 {
6758   int i;
6759   struct delayed_method_info *mi;
6760   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6761     {
6762       const char *physname;
6763       struct fn_fieldlist *fn_flp
6764         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6765       physname = dwarf2_physname (mi->name, mi->die, cu);
6766       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6767     }
6768 }
6769
6770 /* Go objects should be embedded in a DW_TAG_module DIE,
6771    and it's not clear if/how imported objects will appear.
6772    To keep Go support simple until that's worked out,
6773    go back through what we've read and create something usable.
6774    We could do this while processing each DIE, and feels kinda cleaner,
6775    but that way is more invasive.
6776    This is to, for example, allow the user to type "p var" or "b main"
6777    without having to specify the package name, and allow lookups
6778    of module.object to work in contexts that use the expression
6779    parser.  */
6780
6781 static void
6782 fixup_go_packaging (struct dwarf2_cu *cu)
6783 {
6784   char *package_name = NULL;
6785   struct pending *list;
6786   int i;
6787
6788   for (list = global_symbols; list != NULL; list = list->next)
6789     {
6790       for (i = 0; i < list->nsyms; ++i)
6791         {
6792           struct symbol *sym = list->symbol[i];
6793
6794           if (SYMBOL_LANGUAGE (sym) == language_go
6795               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6796             {
6797               char *this_package_name = go_symbol_package_name (sym);
6798
6799               if (this_package_name == NULL)
6800                 continue;
6801               if (package_name == NULL)
6802                 package_name = this_package_name;
6803               else
6804                 {
6805                   if (strcmp (package_name, this_package_name) != 0)
6806                     complaint (&symfile_complaints,
6807                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6808                                (SYMBOL_SYMTAB (sym)
6809                                 ? SYMBOL_SYMTAB (sym)->filename
6810                                 : cu->objfile->name),
6811                                this_package_name, package_name);
6812                   xfree (this_package_name);
6813                 }
6814             }
6815         }
6816     }
6817
6818   if (package_name != NULL)
6819     {
6820       struct objfile *objfile = cu->objfile;
6821       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6822                                                       package_name,
6823                                                       strlen (package_name));
6824       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6825                                      saved_package_name, objfile);
6826       struct symbol *sym;
6827
6828       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6829
6830       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6831       SYMBOL_SET_LANGUAGE (sym, language_go);
6832       SYMBOL_SET_NAMES (sym, saved_package_name,
6833                         strlen (saved_package_name), 0, objfile);
6834       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6835          e.g., "main" finds the "main" module and not C's main().  */
6836       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6837       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
6838       SYMBOL_TYPE (sym) = type;
6839
6840       add_symbol_to_list (sym, &global_symbols);
6841
6842       xfree (package_name);
6843     }
6844 }
6845
6846 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
6847
6848 /* Return the symtab for PER_CU.  This works properly regardless of
6849    whether we're using the index or psymtabs.  */
6850
6851 static struct symtab *
6852 get_symtab (struct dwarf2_per_cu_data *per_cu)
6853 {
6854   return (dwarf2_per_objfile->using_index
6855           ? per_cu->v.quick->symtab
6856           : per_cu->v.psymtab->symtab);
6857 }
6858
6859 /* A helper function for computing the list of all symbol tables
6860    included by PER_CU.  */
6861
6862 static void
6863 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6864                                 htab_t all_children,
6865                                 struct dwarf2_per_cu_data *per_cu)
6866 {
6867   void **slot;
6868   int ix;
6869   struct dwarf2_per_cu_data *iter;
6870
6871   slot = htab_find_slot (all_children, per_cu, INSERT);
6872   if (*slot != NULL)
6873     {
6874       /* This inclusion and its children have been processed.  */
6875       return;
6876     }
6877
6878   *slot = per_cu;
6879   /* Only add a CU if it has a symbol table.  */
6880   if (get_symtab (per_cu) != NULL)
6881     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6882
6883   for (ix = 0;
6884        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
6885        ++ix)
6886     recursively_compute_inclusions (result, all_children, iter);
6887 }
6888
6889 /* Compute the symtab 'includes' fields for the symtab related to
6890    PER_CU.  */
6891
6892 static void
6893 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6894 {
6895   gdb_assert (! per_cu->is_debug_types);
6896
6897   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
6898     {
6899       int ix, len;
6900       struct dwarf2_per_cu_data *iter;
6901       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6902       htab_t all_children;
6903       struct symtab *symtab = get_symtab (per_cu);
6904
6905       /* If we don't have a symtab, we can just skip this case.  */
6906       if (symtab == NULL)
6907         return;
6908
6909       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6910                                         NULL, xcalloc, xfree);
6911
6912       for (ix = 0;
6913            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
6914                         ix, iter);
6915            ++ix)
6916         recursively_compute_inclusions (&result_children, all_children, iter);
6917
6918       /* Now we have a transitive closure of all the included CUs, and
6919          for .gdb_index version 7 the included TUs, so we can convert it
6920          to a list of symtabs.  */
6921       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6922       symtab->includes
6923         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6924                          (len + 1) * sizeof (struct symtab *));
6925       for (ix = 0;
6926            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6927            ++ix)
6928         symtab->includes[ix] = get_symtab (iter);
6929       symtab->includes[len] = NULL;
6930
6931       VEC_free (dwarf2_per_cu_ptr, result_children);
6932       htab_delete (all_children);
6933     }
6934 }
6935
6936 /* Compute the 'includes' field for the symtabs of all the CUs we just
6937    read.  */
6938
6939 static void
6940 process_cu_includes (void)
6941 {
6942   int ix;
6943   struct dwarf2_per_cu_data *iter;
6944
6945   for (ix = 0;
6946        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6947                     ix, iter);
6948        ++ix)
6949     {
6950       if (! iter->is_debug_types)
6951         compute_symtab_includes (iter);
6952     }
6953
6954   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6955 }
6956
6957 /* Generate full symbol information for PER_CU, whose DIEs have
6958    already been loaded into memory.  */
6959
6960 static void
6961 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6962                         enum language pretend_language)
6963 {
6964   struct dwarf2_cu *cu = per_cu->cu;
6965   struct objfile *objfile = per_cu->objfile;
6966   CORE_ADDR lowpc, highpc;
6967   struct symtab *symtab;
6968   struct cleanup *back_to, *delayed_list_cleanup;
6969   CORE_ADDR baseaddr;
6970   struct block *static_block;
6971
6972   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6973
6974   buildsym_init ();
6975   back_to = make_cleanup (really_free_pendings, NULL);
6976   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6977
6978   cu->list_in_scope = &file_symbols;
6979
6980   cu->language = pretend_language;
6981   cu->language_defn = language_def (cu->language);
6982
6983   /* Do line number decoding in read_file_scope () */
6984   process_die (cu->dies, cu);
6985
6986   /* For now fudge the Go package.  */
6987   if (cu->language == language_go)
6988     fixup_go_packaging (cu);
6989
6990   /* Now that we have processed all the DIEs in the CU, all the types 
6991      should be complete, and it should now be safe to compute all of the
6992      physnames.  */
6993   compute_delayed_physnames (cu);
6994   do_cleanups (delayed_list_cleanup);
6995
6996   /* Some compilers don't define a DW_AT_high_pc attribute for the
6997      compilation unit.  If the DW_AT_high_pc is missing, synthesize
6998      it, by scanning the DIE's below the compilation unit.  */
6999   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7000
7001   static_block
7002     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
7003                                    per_cu->imported_symtabs != NULL);
7004
7005   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7006      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7007      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7008      addrmap to help ensure it has an accurate map of pc values belonging to
7009      this comp unit.  */
7010   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7011
7012   symtab = end_symtab_from_static_block (static_block, objfile,
7013                                          SECT_OFF_TEXT (objfile), 0);
7014
7015   if (symtab != NULL)
7016     {
7017       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7018
7019       /* Set symtab language to language from DW_AT_language.  If the
7020          compilation is from a C file generated by language preprocessors, do
7021          not set the language if it was already deduced by start_subfile.  */
7022       if (!(cu->language == language_c && symtab->language != language_c))
7023         symtab->language = cu->language;
7024
7025       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7026          produce DW_AT_location with location lists but it can be possibly
7027          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7028          there were bugs in prologue debug info, fixed later in GCC-4.5
7029          by "unwind info for epilogues" patch (which is not directly related).
7030
7031          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7032          needed, it would be wrong due to missing DW_AT_producer there.
7033
7034          Still one can confuse GDB by using non-standard GCC compilation
7035          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7036          */ 
7037       if (cu->has_loclist && gcc_4_minor >= 5)
7038         symtab->locations_valid = 1;
7039
7040       if (gcc_4_minor >= 5)
7041         symtab->epilogue_unwind_valid = 1;
7042
7043       symtab->call_site_htab = cu->call_site_htab;
7044     }
7045
7046   if (dwarf2_per_objfile->using_index)
7047     per_cu->v.quick->symtab = symtab;
7048   else
7049     {
7050       struct partial_symtab *pst = per_cu->v.psymtab;
7051       pst->symtab = symtab;
7052       pst->readin = 1;
7053     }
7054
7055   /* Push it for inclusion processing later.  */
7056   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7057
7058   do_cleanups (back_to);
7059 }
7060
7061 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7062    already been loaded into memory.  */
7063
7064 static void
7065 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7066                         enum language pretend_language)
7067 {
7068   struct dwarf2_cu *cu = per_cu->cu;
7069   struct objfile *objfile = per_cu->objfile;
7070   struct symtab *symtab;
7071   struct cleanup *back_to, *delayed_list_cleanup;
7072
7073   buildsym_init ();
7074   back_to = make_cleanup (really_free_pendings, NULL);
7075   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7076
7077   cu->list_in_scope = &file_symbols;
7078
7079   cu->language = pretend_language;
7080   cu->language_defn = language_def (cu->language);
7081
7082   /* The symbol tables are set up in read_type_unit_scope.  */
7083   process_die (cu->dies, cu);
7084
7085   /* For now fudge the Go package.  */
7086   if (cu->language == language_go)
7087     fixup_go_packaging (cu);
7088
7089   /* Now that we have processed all the DIEs in the CU, all the types 
7090      should be complete, and it should now be safe to compute all of the
7091      physnames.  */
7092   compute_delayed_physnames (cu);
7093   do_cleanups (delayed_list_cleanup);
7094
7095   /* TUs share symbol tables.
7096      If this is the first TU to use this symtab, complete the construction
7097      of it with end_expandable_symtab.  Otherwise, complete the addition of
7098      this TU's symbols to the existing symtab.  */
7099   if (per_cu->type_unit_group->primary_symtab == NULL)
7100     {
7101       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7102       per_cu->type_unit_group->primary_symtab = symtab;
7103
7104       if (symtab != NULL)
7105         {
7106           /* Set symtab language to language from DW_AT_language.  If the
7107              compilation is from a C file generated by language preprocessors,
7108              do not set the language if it was already deduced by
7109              start_subfile.  */
7110           if (!(cu->language == language_c && symtab->language != language_c))
7111             symtab->language = cu->language;
7112         }
7113     }
7114   else
7115     {
7116       augment_type_symtab (objfile,
7117                            per_cu->type_unit_group->primary_symtab);
7118       symtab = per_cu->type_unit_group->primary_symtab;
7119     }
7120
7121   if (dwarf2_per_objfile->using_index)
7122     per_cu->v.quick->symtab = symtab;
7123   else
7124     {
7125       struct partial_symtab *pst = per_cu->v.psymtab;
7126       pst->symtab = symtab;
7127       pst->readin = 1;
7128     }
7129
7130   do_cleanups (back_to);
7131 }
7132
7133 /* Process an imported unit DIE.  */
7134
7135 static void
7136 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7137 {
7138   struct attribute *attr;
7139
7140   /* For now we don't handle imported units in type units.  */
7141   if (cu->per_cu->is_debug_types)
7142     {
7143       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7144                " supported in type units [in module %s]"),
7145              cu->objfile->name);
7146     }
7147
7148   attr = dwarf2_attr (die, DW_AT_import, cu);
7149   if (attr != NULL)
7150     {
7151       struct dwarf2_per_cu_data *per_cu;
7152       struct symtab *imported_symtab;
7153       sect_offset offset;
7154       int is_dwz;
7155
7156       offset = dwarf2_get_ref_die_offset (attr);
7157       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7158       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7159
7160       /* Queue the unit, if needed.  */
7161       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7162         load_full_comp_unit (per_cu, cu->language);
7163
7164       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7165                      per_cu);
7166     }
7167 }
7168
7169 /* Process a die and its children.  */
7170
7171 static void
7172 process_die (struct die_info *die, struct dwarf2_cu *cu)
7173 {
7174   switch (die->tag)
7175     {
7176     case DW_TAG_padding:
7177       break;
7178     case DW_TAG_compile_unit:
7179     case DW_TAG_partial_unit:
7180       read_file_scope (die, cu);
7181       break;
7182     case DW_TAG_type_unit:
7183       read_type_unit_scope (die, cu);
7184       break;
7185     case DW_TAG_subprogram:
7186     case DW_TAG_inlined_subroutine:
7187       read_func_scope (die, cu);
7188       break;
7189     case DW_TAG_lexical_block:
7190     case DW_TAG_try_block:
7191     case DW_TAG_catch_block:
7192       read_lexical_block_scope (die, cu);
7193       break;
7194     case DW_TAG_GNU_call_site:
7195       read_call_site_scope (die, cu);
7196       break;
7197     case DW_TAG_class_type:
7198     case DW_TAG_interface_type:
7199     case DW_TAG_structure_type:
7200     case DW_TAG_union_type:
7201       process_structure_scope (die, cu);
7202       break;
7203     case DW_TAG_enumeration_type:
7204       process_enumeration_scope (die, cu);
7205       break;
7206
7207     /* These dies have a type, but processing them does not create
7208        a symbol or recurse to process the children.  Therefore we can
7209        read them on-demand through read_type_die.  */
7210     case DW_TAG_subroutine_type:
7211     case DW_TAG_set_type:
7212     case DW_TAG_array_type:
7213     case DW_TAG_pointer_type:
7214     case DW_TAG_ptr_to_member_type:
7215     case DW_TAG_reference_type:
7216     case DW_TAG_string_type:
7217       break;
7218
7219     case DW_TAG_base_type:
7220     case DW_TAG_subrange_type:
7221     case DW_TAG_typedef:
7222       /* Add a typedef symbol for the type definition, if it has a
7223          DW_AT_name.  */
7224       new_symbol (die, read_type_die (die, cu), cu);
7225       break;
7226     case DW_TAG_common_block:
7227       read_common_block (die, cu);
7228       break;
7229     case DW_TAG_common_inclusion:
7230       break;
7231     case DW_TAG_namespace:
7232       cu->processing_has_namespace_info = 1;
7233       read_namespace (die, cu);
7234       break;
7235     case DW_TAG_module:
7236       cu->processing_has_namespace_info = 1;
7237       read_module (die, cu);
7238       break;
7239     case DW_TAG_imported_declaration:
7240     case DW_TAG_imported_module:
7241       cu->processing_has_namespace_info = 1;
7242       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7243                                  || cu->language != language_fortran))
7244         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7245                    dwarf_tag_name (die->tag));
7246       read_import_statement (die, cu);
7247       break;
7248
7249     case DW_TAG_imported_unit:
7250       process_imported_unit_die (die, cu);
7251       break;
7252
7253     default:
7254       new_symbol (die, NULL, cu);
7255       break;
7256     }
7257 }
7258
7259 /* A helper function for dwarf2_compute_name which determines whether DIE
7260    needs to have the name of the scope prepended to the name listed in the
7261    die.  */
7262
7263 static int
7264 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7265 {
7266   struct attribute *attr;
7267
7268   switch (die->tag)
7269     {
7270     case DW_TAG_namespace:
7271     case DW_TAG_typedef:
7272     case DW_TAG_class_type:
7273     case DW_TAG_interface_type:
7274     case DW_TAG_structure_type:
7275     case DW_TAG_union_type:
7276     case DW_TAG_enumeration_type:
7277     case DW_TAG_enumerator:
7278     case DW_TAG_subprogram:
7279     case DW_TAG_member:
7280       return 1;
7281
7282     case DW_TAG_variable:
7283     case DW_TAG_constant:
7284       /* We only need to prefix "globally" visible variables.  These include
7285          any variable marked with DW_AT_external or any variable that
7286          lives in a namespace.  [Variables in anonymous namespaces
7287          require prefixing, but they are not DW_AT_external.]  */
7288
7289       if (dwarf2_attr (die, DW_AT_specification, cu))
7290         {
7291           struct dwarf2_cu *spec_cu = cu;
7292
7293           return die_needs_namespace (die_specification (die, &spec_cu),
7294                                       spec_cu);
7295         }
7296
7297       attr = dwarf2_attr (die, DW_AT_external, cu);
7298       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7299           && die->parent->tag != DW_TAG_module)
7300         return 0;
7301       /* A variable in a lexical block of some kind does not need a
7302          namespace, even though in C++ such variables may be external
7303          and have a mangled name.  */
7304       if (die->parent->tag ==  DW_TAG_lexical_block
7305           || die->parent->tag ==  DW_TAG_try_block
7306           || die->parent->tag ==  DW_TAG_catch_block
7307           || die->parent->tag == DW_TAG_subprogram)
7308         return 0;
7309       return 1;
7310
7311     default:
7312       return 0;
7313     }
7314 }
7315
7316 /* Retrieve the last character from a mem_file.  */
7317
7318 static void
7319 do_ui_file_peek_last (void *object, const char *buffer, long length)
7320 {
7321   char *last_char_p = (char *) object;
7322
7323   if (length > 0)
7324     *last_char_p = buffer[length - 1];
7325 }
7326
7327 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7328    compute the physname for the object, which include a method's:
7329    - formal parameters (C++/Java),
7330    - receiver type (Go),
7331    - return type (Java).
7332
7333    The term "physname" is a bit confusing.
7334    For C++, for example, it is the demangled name.
7335    For Go, for example, it's the mangled name.
7336
7337    For Ada, return the DIE's linkage name rather than the fully qualified
7338    name.  PHYSNAME is ignored..
7339
7340    The result is allocated on the objfile_obstack and canonicalized.  */
7341
7342 static const char *
7343 dwarf2_compute_name (const char *name,
7344                      struct die_info *die, struct dwarf2_cu *cu,
7345                      int physname)
7346 {
7347   struct objfile *objfile = cu->objfile;
7348
7349   if (name == NULL)
7350     name = dwarf2_name (die, cu);
7351
7352   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7353      compute it by typename_concat inside GDB.  */
7354   if (cu->language == language_ada
7355       || (cu->language == language_fortran && physname))
7356     {
7357       /* For Ada unit, we prefer the linkage name over the name, as
7358          the former contains the exported name, which the user expects
7359          to be able to reference.  Ideally, we want the user to be able
7360          to reference this entity using either natural or linkage name,
7361          but we haven't started looking at this enhancement yet.  */
7362       struct attribute *attr;
7363
7364       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7365       if (attr == NULL)
7366         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7367       if (attr && DW_STRING (attr))
7368         return DW_STRING (attr);
7369     }
7370
7371   /* These are the only languages we know how to qualify names in.  */
7372   if (name != NULL
7373       && (cu->language == language_cplus || cu->language == language_java
7374           || cu->language == language_fortran))
7375     {
7376       if (die_needs_namespace (die, cu))
7377         {
7378           long length;
7379           const char *prefix;
7380           struct ui_file *buf;
7381
7382           prefix = determine_prefix (die, cu);
7383           buf = mem_fileopen ();
7384           if (*prefix != '\0')
7385             {
7386               char *prefixed_name = typename_concat (NULL, prefix, name,
7387                                                      physname, cu);
7388
7389               fputs_unfiltered (prefixed_name, buf);
7390               xfree (prefixed_name);
7391             }
7392           else
7393             fputs_unfiltered (name, buf);
7394
7395           /* Template parameters may be specified in the DIE's DW_AT_name, or
7396              as children with DW_TAG_template_type_param or
7397              DW_TAG_value_type_param.  If the latter, add them to the name
7398              here.  If the name already has template parameters, then
7399              skip this step; some versions of GCC emit both, and
7400              it is more efficient to use the pre-computed name.
7401
7402              Something to keep in mind about this process: it is very
7403              unlikely, or in some cases downright impossible, to produce
7404              something that will match the mangled name of a function.
7405              If the definition of the function has the same debug info,
7406              we should be able to match up with it anyway.  But fallbacks
7407              using the minimal symbol, for instance to find a method
7408              implemented in a stripped copy of libstdc++, will not work.
7409              If we do not have debug info for the definition, we will have to
7410              match them up some other way.
7411
7412              When we do name matching there is a related problem with function
7413              templates; two instantiated function templates are allowed to
7414              differ only by their return types, which we do not add here.  */
7415
7416           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7417             {
7418               struct attribute *attr;
7419               struct die_info *child;
7420               int first = 1;
7421
7422               die->building_fullname = 1;
7423
7424               for (child = die->child; child != NULL; child = child->sibling)
7425                 {
7426                   struct type *type;
7427                   LONGEST value;
7428                   gdb_byte *bytes;
7429                   struct dwarf2_locexpr_baton *baton;
7430                   struct value *v;
7431
7432                   if (child->tag != DW_TAG_template_type_param
7433                       && child->tag != DW_TAG_template_value_param)
7434                     continue;
7435
7436                   if (first)
7437                     {
7438                       fputs_unfiltered ("<", buf);
7439                       first = 0;
7440                     }
7441                   else
7442                     fputs_unfiltered (", ", buf);
7443
7444                   attr = dwarf2_attr (child, DW_AT_type, cu);
7445                   if (attr == NULL)
7446                     {
7447                       complaint (&symfile_complaints,
7448                                  _("template parameter missing DW_AT_type"));
7449                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7450                       continue;
7451                     }
7452                   type = die_type (child, cu);
7453
7454                   if (child->tag == DW_TAG_template_type_param)
7455                     {
7456                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7457                       continue;
7458                     }
7459
7460                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7461                   if (attr == NULL)
7462                     {
7463                       complaint (&symfile_complaints,
7464                                  _("template parameter missing "
7465                                    "DW_AT_const_value"));
7466                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7467                       continue;
7468                     }
7469
7470                   dwarf2_const_value_attr (attr, type, name,
7471                                            &cu->comp_unit_obstack, cu,
7472                                            &value, &bytes, &baton);
7473
7474                   if (TYPE_NOSIGN (type))
7475                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7476                        changed, this can use value_print instead.  */
7477                     c_printchar (value, type, buf);
7478                   else
7479                     {
7480                       struct value_print_options opts;
7481
7482                       if (baton != NULL)
7483                         v = dwarf2_evaluate_loc_desc (type, NULL,
7484                                                       baton->data,
7485                                                       baton->size,
7486                                                       baton->per_cu);
7487                       else if (bytes != NULL)
7488                         {
7489                           v = allocate_value (type);
7490                           memcpy (value_contents_writeable (v), bytes,
7491                                   TYPE_LENGTH (type));
7492                         }
7493                       else
7494                         v = value_from_longest (type, value);
7495
7496                       /* Specify decimal so that we do not depend on
7497                          the radix.  */
7498                       get_formatted_print_options (&opts, 'd');
7499                       opts.raw = 1;
7500                       value_print (v, buf, &opts);
7501                       release_value (v);
7502                       value_free (v);
7503                     }
7504                 }
7505
7506               die->building_fullname = 0;
7507
7508               if (!first)
7509                 {
7510                   /* Close the argument list, with a space if necessary
7511                      (nested templates).  */
7512                   char last_char = '\0';
7513                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7514                   if (last_char == '>')
7515                     fputs_unfiltered (" >", buf);
7516                   else
7517                     fputs_unfiltered (">", buf);
7518                 }
7519             }
7520
7521           /* For Java and C++ methods, append formal parameter type
7522              information, if PHYSNAME.  */
7523
7524           if (physname && die->tag == DW_TAG_subprogram
7525               && (cu->language == language_cplus
7526                   || cu->language == language_java))
7527             {
7528               struct type *type = read_type_die (die, cu);
7529
7530               c_type_print_args (type, buf, 1, cu->language,
7531                                  &type_print_raw_options);
7532
7533               if (cu->language == language_java)
7534                 {
7535                   /* For java, we must append the return type to method
7536                      names.  */
7537                   if (die->tag == DW_TAG_subprogram)
7538                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7539                                      0, 0, &type_print_raw_options);
7540                 }
7541               else if (cu->language == language_cplus)
7542                 {
7543                   /* Assume that an artificial first parameter is
7544                      "this", but do not crash if it is not.  RealView
7545                      marks unnamed (and thus unused) parameters as
7546                      artificial; there is no way to differentiate
7547                      the two cases.  */
7548                   if (TYPE_NFIELDS (type) > 0
7549                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7550                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7551                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7552                                                                         0))))
7553                     fputs_unfiltered (" const", buf);
7554                 }
7555             }
7556
7557           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7558                                        &length);
7559           ui_file_delete (buf);
7560
7561           if (cu->language == language_cplus)
7562             {
7563               const char *cname
7564                 = dwarf2_canonicalize_name (name, cu,
7565                                             &objfile->objfile_obstack);
7566
7567               if (cname != NULL)
7568                 name = cname;
7569             }
7570         }
7571     }
7572
7573   return name;
7574 }
7575
7576 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7577    If scope qualifiers are appropriate they will be added.  The result
7578    will be allocated on the objfile_obstack, or NULL if the DIE does
7579    not have a name.  NAME may either be from a previous call to
7580    dwarf2_name or NULL.
7581
7582    The output string will be canonicalized (if C++/Java).  */
7583
7584 static const char *
7585 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7586 {
7587   return dwarf2_compute_name (name, die, cu, 0);
7588 }
7589
7590 /* Construct a physname for the given DIE in CU.  NAME may either be
7591    from a previous call to dwarf2_name or NULL.  The result will be
7592    allocated on the objfile_objstack or NULL if the DIE does not have a
7593    name.
7594
7595    The output string will be canonicalized (if C++/Java).  */
7596
7597 static const char *
7598 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7599 {
7600   struct objfile *objfile = cu->objfile;
7601   struct attribute *attr;
7602   const char *retval, *mangled = NULL, *canon = NULL;
7603   struct cleanup *back_to;
7604   int need_copy = 1;
7605
7606   /* In this case dwarf2_compute_name is just a shortcut not building anything
7607      on its own.  */
7608   if (!die_needs_namespace (die, cu))
7609     return dwarf2_compute_name (name, die, cu, 1);
7610
7611   back_to = make_cleanup (null_cleanup, NULL);
7612
7613   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7614   if (!attr)
7615     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7616
7617   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7618      has computed.  */
7619   if (attr && DW_STRING (attr))
7620     {
7621       char *demangled;
7622
7623       mangled = DW_STRING (attr);
7624
7625       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7626          type.  It is easier for GDB users to search for such functions as
7627          `name(params)' than `long name(params)'.  In such case the minimal
7628          symbol names do not match the full symbol names but for template
7629          functions there is never a need to look up their definition from their
7630          declaration so the only disadvantage remains the minimal symbol
7631          variant `long name(params)' does not have the proper inferior type.
7632          */
7633
7634       if (cu->language == language_go)
7635         {
7636           /* This is a lie, but we already lie to the caller new_symbol_full.
7637              new_symbol_full assumes we return the mangled name.
7638              This just undoes that lie until things are cleaned up.  */
7639           demangled = NULL;
7640         }
7641       else
7642         {
7643           demangled = cplus_demangle (mangled,
7644                                       (DMGL_PARAMS | DMGL_ANSI
7645                                        | (cu->language == language_java
7646                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7647                                           : DMGL_RET_DROP)));
7648         }
7649       if (demangled)
7650         {
7651           make_cleanup (xfree, demangled);
7652           canon = demangled;
7653         }
7654       else
7655         {
7656           canon = mangled;
7657           need_copy = 0;
7658         }
7659     }
7660
7661   if (canon == NULL || check_physname)
7662     {
7663       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7664
7665       if (canon != NULL && strcmp (physname, canon) != 0)
7666         {
7667           /* It may not mean a bug in GDB.  The compiler could also
7668              compute DW_AT_linkage_name incorrectly.  But in such case
7669              GDB would need to be bug-to-bug compatible.  */
7670
7671           complaint (&symfile_complaints,
7672                      _("Computed physname <%s> does not match demangled <%s> "
7673                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7674                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7675
7676           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7677              is available here - over computed PHYSNAME.  It is safer
7678              against both buggy GDB and buggy compilers.  */
7679
7680           retval = canon;
7681         }
7682       else
7683         {
7684           retval = physname;
7685           need_copy = 0;
7686         }
7687     }
7688   else
7689     retval = canon;
7690
7691   if (need_copy)
7692     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7693
7694   do_cleanups (back_to);
7695   return retval;
7696 }
7697
7698 /* Read the import statement specified by the given die and record it.  */
7699
7700 static void
7701 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7702 {
7703   struct objfile *objfile = cu->objfile;
7704   struct attribute *import_attr;
7705   struct die_info *imported_die, *child_die;
7706   struct dwarf2_cu *imported_cu;
7707   const char *imported_name;
7708   const char *imported_name_prefix;
7709   const char *canonical_name;
7710   const char *import_alias;
7711   const char *imported_declaration = NULL;
7712   const char *import_prefix;
7713   VEC (const_char_ptr) *excludes = NULL;
7714   struct cleanup *cleanups;
7715
7716   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7717   if (import_attr == NULL)
7718     {
7719       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7720                  dwarf_tag_name (die->tag));
7721       return;
7722     }
7723
7724   imported_cu = cu;
7725   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7726   imported_name = dwarf2_name (imported_die, imported_cu);
7727   if (imported_name == NULL)
7728     {
7729       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7730
7731         The import in the following code:
7732         namespace A
7733           {
7734             typedef int B;
7735           }
7736
7737         int main ()
7738           {
7739             using A::B;
7740             B b;
7741             return b;
7742           }
7743
7744         ...
7745          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7746             <52>   DW_AT_decl_file   : 1
7747             <53>   DW_AT_decl_line   : 6
7748             <54>   DW_AT_import      : <0x75>
7749          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7750             <59>   DW_AT_name        : B
7751             <5b>   DW_AT_decl_file   : 1
7752             <5c>   DW_AT_decl_line   : 2
7753             <5d>   DW_AT_type        : <0x6e>
7754         ...
7755          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7756             <76>   DW_AT_byte_size   : 4
7757             <77>   DW_AT_encoding    : 5        (signed)
7758
7759         imports the wrong die ( 0x75 instead of 0x58 ).
7760         This case will be ignored until the gcc bug is fixed.  */
7761       return;
7762     }
7763
7764   /* Figure out the local name after import.  */
7765   import_alias = dwarf2_name (die, cu);
7766
7767   /* Figure out where the statement is being imported to.  */
7768   import_prefix = determine_prefix (die, cu);
7769
7770   /* Figure out what the scope of the imported die is and prepend it
7771      to the name of the imported die.  */
7772   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7773
7774   if (imported_die->tag != DW_TAG_namespace
7775       && imported_die->tag != DW_TAG_module)
7776     {
7777       imported_declaration = imported_name;
7778       canonical_name = imported_name_prefix;
7779     }
7780   else if (strlen (imported_name_prefix) > 0)
7781     canonical_name = obconcat (&objfile->objfile_obstack,
7782                                imported_name_prefix, "::", imported_name,
7783                                (char *) NULL);
7784   else
7785     canonical_name = imported_name;
7786
7787   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7788
7789   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7790     for (child_die = die->child; child_die && child_die->tag;
7791          child_die = sibling_die (child_die))
7792       {
7793         /* DWARF-4: A Fortran use statement with a “rename list” may be
7794            represented by an imported module entry with an import attribute
7795            referring to the module and owned entries corresponding to those
7796            entities that are renamed as part of being imported.  */
7797
7798         if (child_die->tag != DW_TAG_imported_declaration)
7799           {
7800             complaint (&symfile_complaints,
7801                        _("child DW_TAG_imported_declaration expected "
7802                          "- DIE at 0x%x [in module %s]"),
7803                        child_die->offset.sect_off, objfile->name);
7804             continue;
7805           }
7806
7807         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7808         if (import_attr == NULL)
7809           {
7810             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7811                        dwarf_tag_name (child_die->tag));
7812             continue;
7813           }
7814
7815         imported_cu = cu;
7816         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7817                                               &imported_cu);
7818         imported_name = dwarf2_name (imported_die, imported_cu);
7819         if (imported_name == NULL)
7820           {
7821             complaint (&symfile_complaints,
7822                        _("child DW_TAG_imported_declaration has unknown "
7823                          "imported name - DIE at 0x%x [in module %s]"),
7824                        child_die->offset.sect_off, objfile->name);
7825             continue;
7826           }
7827
7828         VEC_safe_push (const_char_ptr, excludes, imported_name);
7829
7830         process_die (child_die, cu);
7831       }
7832
7833   cp_add_using_directive (import_prefix,
7834                           canonical_name,
7835                           import_alias,
7836                           imported_declaration,
7837                           excludes,
7838                           0,
7839                           &objfile->objfile_obstack);
7840
7841   do_cleanups (cleanups);
7842 }
7843
7844 /* Cleanup function for handle_DW_AT_stmt_list.  */
7845
7846 static void
7847 free_cu_line_header (void *arg)
7848 {
7849   struct dwarf2_cu *cu = arg;
7850
7851   free_line_header (cu->line_header);
7852   cu->line_header = NULL;
7853 }
7854
7855 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7856    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7857    this, it was first present in GCC release 4.3.0.  */
7858
7859 static int
7860 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7861 {
7862   if (!cu->checked_producer)
7863     check_producer (cu);
7864
7865   return cu->producer_is_gcc_lt_4_3;
7866 }
7867
7868 static void
7869 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7870                          const char **name, const char **comp_dir)
7871 {
7872   struct attribute *attr;
7873
7874   *name = NULL;
7875   *comp_dir = NULL;
7876
7877   /* Find the filename.  Do not use dwarf2_name here, since the filename
7878      is not a source language identifier.  */
7879   attr = dwarf2_attr (die, DW_AT_name, cu);
7880   if (attr)
7881     {
7882       *name = DW_STRING (attr);
7883     }
7884
7885   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7886   if (attr)
7887     *comp_dir = DW_STRING (attr);
7888   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
7889            && IS_ABSOLUTE_PATH (*name))
7890     {
7891       char *d = ldirname (*name);
7892
7893       *comp_dir = d;
7894       if (d != NULL)
7895         make_cleanup (xfree, d);
7896     }
7897   if (*comp_dir != NULL)
7898     {
7899       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7900          directory, get rid of it.  */
7901       char *cp = strchr (*comp_dir, ':');
7902
7903       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7904         *comp_dir = cp + 1;
7905     }
7906
7907   if (*name == NULL)
7908     *name = "<unknown>";
7909 }
7910
7911 /* Handle DW_AT_stmt_list for a compilation unit.
7912    DIE is the DW_TAG_compile_unit die for CU.
7913    COMP_DIR is the compilation directory.
7914    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7915
7916 static void
7917 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7918                         const char *comp_dir)
7919 {
7920   struct attribute *attr;
7921
7922   gdb_assert (! cu->per_cu->is_debug_types);
7923
7924   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7925   if (attr)
7926     {
7927       unsigned int line_offset = DW_UNSND (attr);
7928       struct line_header *line_header
7929         = dwarf_decode_line_header (line_offset, cu);
7930
7931       if (line_header)
7932         {
7933           cu->line_header = line_header;
7934           make_cleanup (free_cu_line_header, cu);
7935           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7936         }
7937     }
7938 }
7939
7940 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7941
7942 static void
7943 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7944 {
7945   struct objfile *objfile = dwarf2_per_objfile->objfile;
7946   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7947   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7948   CORE_ADDR highpc = ((CORE_ADDR) 0);
7949   struct attribute *attr;
7950   const char *name = NULL;
7951   const char *comp_dir = NULL;
7952   struct die_info *child_die;
7953   bfd *abfd = objfile->obfd;
7954   CORE_ADDR baseaddr;
7955
7956   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7957
7958   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7959
7960   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7961      from finish_block.  */
7962   if (lowpc == ((CORE_ADDR) -1))
7963     lowpc = highpc;
7964   lowpc += baseaddr;
7965   highpc += baseaddr;
7966
7967   find_file_and_directory (die, cu, &name, &comp_dir);
7968
7969   prepare_one_comp_unit (cu, die, cu->language);
7970
7971   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7972      standardised yet.  As a workaround for the language detection we fall
7973      back to the DW_AT_producer string.  */
7974   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7975     cu->language = language_opencl;
7976
7977   /* Similar hack for Go.  */
7978   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
7979     set_cu_language (DW_LANG_Go, cu);
7980
7981   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
7982
7983   /* Decode line number information if present.  We do this before
7984      processing child DIEs, so that the line header table is available
7985      for DW_AT_decl_file.  */
7986   handle_DW_AT_stmt_list (die, cu, comp_dir);
7987
7988   /* Process all dies in compilation unit.  */
7989   if (die->child != NULL)
7990     {
7991       child_die = die->child;
7992       while (child_die && child_die->tag)
7993         {
7994           process_die (child_die, cu);
7995           child_die = sibling_die (child_die);
7996         }
7997     }
7998
7999   /* Decode macro information, if present.  Dwarf 2 macro information
8000      refers to information in the line number info statement program
8001      header, so we can only read it if we've read the header
8002      successfully.  */
8003   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8004   if (attr && cu->line_header)
8005     {
8006       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8007         complaint (&symfile_complaints,
8008                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8009
8010       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8011     }
8012   else
8013     {
8014       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8015       if (attr && cu->line_header)
8016         {
8017           unsigned int macro_offset = DW_UNSND (attr);
8018
8019           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8020         }
8021     }
8022
8023   do_cleanups (back_to);
8024 }
8025
8026 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8027    Create the set of symtabs used by this TU, or if this TU is sharing
8028    symtabs with another TU and the symtabs have already been created
8029    then restore those symtabs in the line header.
8030    We don't need the pc/line-number mapping for type units.  */
8031
8032 static void
8033 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8034 {
8035   struct objfile *objfile = dwarf2_per_objfile->objfile;
8036   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8037   struct type_unit_group *tu_group;
8038   int first_time;
8039   struct line_header *lh;
8040   struct attribute *attr;
8041   unsigned int i, line_offset;
8042
8043   gdb_assert (per_cu->is_debug_types);
8044
8045   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8046
8047   /* If we're using .gdb_index (includes -readnow) then
8048      per_cu->s.type_unit_group may not have been set up yet.  */
8049   if (per_cu->type_unit_group == NULL)
8050     per_cu->type_unit_group = get_type_unit_group (cu, attr);
8051   tu_group = per_cu->type_unit_group;
8052
8053   /* If we've already processed this stmt_list there's no real need to
8054      do it again, we could fake it and just recreate the part we need
8055      (file name,index -> symtab mapping).  If data shows this optimization
8056      is useful we can do it then.  */
8057   first_time = tu_group->primary_symtab == NULL;
8058
8059   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8060      debug info.  */
8061   lh = NULL;
8062   if (attr != NULL)
8063     {
8064       line_offset = DW_UNSND (attr);
8065       lh = dwarf_decode_line_header (line_offset, cu);
8066     }
8067   if (lh == NULL)
8068     {
8069       if (first_time)
8070         dwarf2_start_symtab (cu, "", NULL, 0);
8071       else
8072         {
8073           gdb_assert (tu_group->symtabs == NULL);
8074           restart_symtab (0);
8075         }
8076       /* Note: The primary symtab will get allocated at the end.  */
8077       return;
8078     }
8079
8080   cu->line_header = lh;
8081   make_cleanup (free_cu_line_header, cu);
8082
8083   if (first_time)
8084     {
8085       dwarf2_start_symtab (cu, "", NULL, 0);
8086
8087       tu_group->num_symtabs = lh->num_file_names;
8088       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8089
8090       for (i = 0; i < lh->num_file_names; ++i)
8091         {
8092           char *dir = NULL;
8093           struct file_entry *fe = &lh->file_names[i];
8094
8095           if (fe->dir_index)
8096             dir = lh->include_dirs[fe->dir_index - 1];
8097           dwarf2_start_subfile (fe->name, dir, NULL);
8098
8099           /* Note: We don't have to watch for the main subfile here, type units
8100              don't have DW_AT_name.  */
8101
8102           if (current_subfile->symtab == NULL)
8103             {
8104               /* NOTE: start_subfile will recognize when it's been passed
8105                  a file it has already seen.  So we can't assume there's a
8106                  simple mapping from lh->file_names to subfiles,
8107                  lh->file_names may contain dups.  */
8108               current_subfile->symtab = allocate_symtab (current_subfile->name,
8109                                                          objfile);
8110             }
8111
8112           fe->symtab = current_subfile->symtab;
8113           tu_group->symtabs[i] = fe->symtab;
8114         }
8115     }
8116   else
8117     {
8118       restart_symtab (0);
8119
8120       for (i = 0; i < lh->num_file_names; ++i)
8121         {
8122           struct file_entry *fe = &lh->file_names[i];
8123
8124           fe->symtab = tu_group->symtabs[i];
8125         }
8126     }
8127
8128   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8129      so they don't have a "real" (so to speak) symtab anyway.
8130      There is later code that will assign the main symtab to all symbols
8131      that don't have one.  We need to handle the case of a symbol with a
8132      missing symtab (DW_AT_decl_file) anyway.  */
8133 }
8134
8135 /* Process DW_TAG_type_unit.
8136    For TUs we want to skip the first top level sibling if it's not the
8137    actual type being defined by this TU.  In this case the first top
8138    level sibling is there to provide context only.  */
8139
8140 static void
8141 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8142 {
8143   struct die_info *child_die;
8144
8145   prepare_one_comp_unit (cu, die, language_minimal);
8146
8147   /* Initialize (or reinitialize) the machinery for building symtabs.
8148      We do this before processing child DIEs, so that the line header table
8149      is available for DW_AT_decl_file.  */
8150   setup_type_unit_groups (die, cu);
8151
8152   if (die->child != NULL)
8153     {
8154       child_die = die->child;
8155       while (child_die && child_die->tag)
8156         {
8157           process_die (child_die, cu);
8158           child_die = sibling_die (child_die);
8159         }
8160     }
8161 }
8162 \f
8163 /* DWO/DWP files.
8164
8165    http://gcc.gnu.org/wiki/DebugFission
8166    http://gcc.gnu.org/wiki/DebugFissionDWP
8167
8168    To simplify handling of both DWO files ("object" files with the DWARF info)
8169    and DWP files (a file with the DWOs packaged up into one file), we treat
8170    DWP files as having a collection of virtual DWO files.  */
8171
8172 static hashval_t
8173 hash_dwo_file (const void *item)
8174 {
8175   const struct dwo_file *dwo_file = item;
8176
8177   return htab_hash_string (dwo_file->name);
8178 }
8179
8180 static int
8181 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8182 {
8183   const struct dwo_file *lhs = item_lhs;
8184   const struct dwo_file *rhs = item_rhs;
8185
8186   return strcmp (lhs->name, rhs->name) == 0;
8187 }
8188
8189 /* Allocate a hash table for DWO files.  */
8190
8191 static htab_t
8192 allocate_dwo_file_hash_table (void)
8193 {
8194   struct objfile *objfile = dwarf2_per_objfile->objfile;
8195
8196   return htab_create_alloc_ex (41,
8197                                hash_dwo_file,
8198                                eq_dwo_file,
8199                                NULL,
8200                                &objfile->objfile_obstack,
8201                                hashtab_obstack_allocate,
8202                                dummy_obstack_deallocate);
8203 }
8204
8205 /* Lookup DWO file DWO_NAME.  */
8206
8207 static void **
8208 lookup_dwo_file_slot (const char *dwo_name)
8209 {
8210   struct dwo_file find_entry;
8211   void **slot;
8212
8213   if (dwarf2_per_objfile->dwo_files == NULL)
8214     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8215
8216   memset (&find_entry, 0, sizeof (find_entry));
8217   find_entry.name = dwo_name;
8218   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8219
8220   return slot;
8221 }
8222
8223 static hashval_t
8224 hash_dwo_unit (const void *item)
8225 {
8226   const struct dwo_unit *dwo_unit = item;
8227
8228   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8229   return dwo_unit->signature;
8230 }
8231
8232 static int
8233 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8234 {
8235   const struct dwo_unit *lhs = item_lhs;
8236   const struct dwo_unit *rhs = item_rhs;
8237
8238   /* The signature is assumed to be unique within the DWO file.
8239      So while object file CU dwo_id's always have the value zero,
8240      that's OK, assuming each object file DWO file has only one CU,
8241      and that's the rule for now.  */
8242   return lhs->signature == rhs->signature;
8243 }
8244
8245 /* Allocate a hash table for DWO CUs,TUs.
8246    There is one of these tables for each of CUs,TUs for each DWO file.  */
8247
8248 static htab_t
8249 allocate_dwo_unit_table (struct objfile *objfile)
8250 {
8251   /* Start out with a pretty small number.
8252      Generally DWO files contain only one CU and maybe some TUs.  */
8253   return htab_create_alloc_ex (3,
8254                                hash_dwo_unit,
8255                                eq_dwo_unit,
8256                                NULL,
8257                                &objfile->objfile_obstack,
8258                                hashtab_obstack_allocate,
8259                                dummy_obstack_deallocate);
8260 }
8261
8262 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8263
8264 struct create_dwo_info_table_data
8265 {
8266   struct dwo_file *dwo_file;
8267   htab_t cu_htab;
8268 };
8269
8270 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8271
8272 static void
8273 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8274                                          gdb_byte *info_ptr,
8275                                          struct die_info *comp_unit_die,
8276                                          int has_children,
8277                                          void *datap)
8278 {
8279   struct dwarf2_cu *cu = reader->cu;
8280   struct objfile *objfile = dwarf2_per_objfile->objfile;
8281   sect_offset offset = cu->per_cu->offset;
8282   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
8283   struct create_dwo_info_table_data *data = datap;
8284   struct dwo_file *dwo_file = data->dwo_file;
8285   htab_t cu_htab = data->cu_htab;
8286   void **slot;
8287   struct attribute *attr;
8288   struct dwo_unit *dwo_unit;
8289
8290   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8291   if (attr == NULL)
8292     {
8293       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8294                " its dwo_id [in module %s]"),
8295              offset.sect_off, dwo_file->name);
8296       return;
8297     }
8298
8299   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8300   dwo_unit->dwo_file = dwo_file;
8301   dwo_unit->signature = DW_UNSND (attr);
8302   dwo_unit->info_or_types_section = section;
8303   dwo_unit->offset = offset;
8304   dwo_unit->length = cu->per_cu->length;
8305
8306   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8307   gdb_assert (slot != NULL);
8308   if (*slot != NULL)
8309     {
8310       const struct dwo_unit *dup_dwo_unit = *slot;
8311
8312       complaint (&symfile_complaints,
8313                  _("debug entry at offset 0x%x is duplicate to the entry at"
8314                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8315                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8316                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8317                  dwo_file->name);
8318     }
8319   else
8320     *slot = dwo_unit;
8321
8322   if (dwarf2_read_debug)
8323     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8324                         offset.sect_off,
8325                         phex (dwo_unit->signature,
8326                               sizeof (dwo_unit->signature)));
8327 }
8328
8329 /* Create a hash table to map DWO IDs to their CU entry in
8330    .debug_info.dwo in DWO_FILE.
8331    Note: This function processes DWO files only, not DWP files.  */
8332
8333 static htab_t
8334 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8335 {
8336   struct objfile *objfile = dwarf2_per_objfile->objfile;
8337   struct dwarf2_section_info *section = &dwo_file->sections.info;
8338   bfd *abfd;
8339   htab_t cu_htab;
8340   gdb_byte *info_ptr, *end_ptr;
8341   struct create_dwo_info_table_data create_dwo_info_table_data;
8342
8343   dwarf2_read_section (objfile, section);
8344   info_ptr = section->buffer;
8345
8346   if (info_ptr == NULL)
8347     return NULL;
8348
8349   /* We can't set abfd until now because the section may be empty or
8350      not present, in which case section->asection will be NULL.  */
8351   abfd = section->asection->owner;
8352
8353   if (dwarf2_read_debug)
8354     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8355                         bfd_get_filename (abfd));
8356
8357   cu_htab = allocate_dwo_unit_table (objfile);
8358
8359   create_dwo_info_table_data.dwo_file = dwo_file;
8360   create_dwo_info_table_data.cu_htab = cu_htab;
8361
8362   end_ptr = info_ptr + section->size;
8363   while (info_ptr < end_ptr)
8364     {
8365       struct dwarf2_per_cu_data per_cu;
8366
8367       memset (&per_cu, 0, sizeof (per_cu));
8368       per_cu.objfile = objfile;
8369       per_cu.is_debug_types = 0;
8370       per_cu.offset.sect_off = info_ptr - section->buffer;
8371       per_cu.info_or_types_section = section;
8372
8373       init_cutu_and_read_dies_no_follow (&per_cu,
8374                                          &dwo_file->sections.abbrev,
8375                                          dwo_file,
8376                                          create_dwo_debug_info_hash_table_reader,
8377                                          &create_dwo_info_table_data);
8378
8379       info_ptr += per_cu.length;
8380     }
8381
8382   return cu_htab;
8383 }
8384
8385 /* DWP file .debug_{cu,tu}_index section format:
8386    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8387
8388    Both index sections have the same format, and serve to map a 64-bit
8389    signature to a set of section numbers.  Each section begins with a header,
8390    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8391    indexes, and a pool of 32-bit section numbers.  The index sections will be
8392    aligned at 8-byte boundaries in the file.
8393
8394    The index section header contains two unsigned 32-bit values (using the
8395    byte order of the application binary):
8396
8397     N, the number of compilation units or type units in the index
8398     M, the number of slots in the hash table
8399
8400   (We assume that N and M will not exceed 2^32 - 1.)
8401
8402   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8403
8404   The hash table begins at offset 8 in the section, and consists of an array
8405   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8406   order of the application binary).  Unused slots in the hash table are 0.
8407   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8408
8409   The parallel table begins immediately after the hash table
8410   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8411   array of 32-bit indexes (using the byte order of the application binary),
8412   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8413   table contains a 32-bit index into the pool of section numbers.  For unused
8414   hash table slots, the corresponding entry in the parallel table will be 0.
8415
8416   Given a 64-bit compilation unit signature or a type signature S, an entry
8417   in the hash table is located as follows:
8418
8419   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8420      the low-order k bits all set to 1.
8421
8422   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8423
8424   3) If the hash table entry at index H matches the signature, use that
8425      entry.  If the hash table entry at index H is unused (all zeroes),
8426      terminate the search: the signature is not present in the table.
8427
8428   4) Let H = (H + H') modulo M. Repeat at Step 3.
8429
8430   Because M > N and H' and M are relatively prime, the search is guaranteed
8431   to stop at an unused slot or find the match.
8432
8433   The pool of section numbers begins immediately following the hash table
8434   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8435   section numbers consists of an array of 32-bit words (using the byte order
8436   of the application binary).  Each item in the array is indexed starting
8437   from 0.  The hash table entry provides the index of the first section
8438   number in the set.  Additional section numbers in the set follow, and the
8439   set is terminated by a 0 entry (section number 0 is not used in ELF).
8440
8441   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8442   section must be the first entry in the set, and the .debug_abbrev.dwo must
8443   be the second entry. Other members of the set may follow in any order.  */
8444
8445 /* Create a hash table to map DWO IDs to their CU/TU entry in
8446    .debug_{info,types}.dwo in DWP_FILE.
8447    Returns NULL if there isn't one.
8448    Note: This function processes DWP files only, not DWO files.  */
8449
8450 static struct dwp_hash_table *
8451 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8452 {
8453   struct objfile *objfile = dwarf2_per_objfile->objfile;
8454   bfd *dbfd = dwp_file->dbfd;
8455   char *index_ptr, *index_end;
8456   struct dwarf2_section_info *index;
8457   uint32_t version, nr_units, nr_slots;
8458   struct dwp_hash_table *htab;
8459
8460   if (is_debug_types)
8461     index = &dwp_file->sections.tu_index;
8462   else
8463     index = &dwp_file->sections.cu_index;
8464
8465   if (dwarf2_section_empty_p (index))
8466     return NULL;
8467   dwarf2_read_section (objfile, index);
8468
8469   index_ptr = index->buffer;
8470   index_end = index_ptr + index->size;
8471
8472   version = read_4_bytes (dbfd, index_ptr);
8473   index_ptr += 8; /* Skip the unused word.  */
8474   nr_units = read_4_bytes (dbfd, index_ptr);
8475   index_ptr += 4;
8476   nr_slots = read_4_bytes (dbfd, index_ptr);
8477   index_ptr += 4;
8478
8479   if (version != 1)
8480     {
8481       error (_("Dwarf Error: unsupported DWP file version (%u)"
8482                " [in module %s]"),
8483              version, dwp_file->name);
8484     }
8485   if (nr_slots != (nr_slots & -nr_slots))
8486     {
8487       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8488                " is not power of 2 [in module %s]"),
8489              nr_slots, dwp_file->name);
8490     }
8491
8492   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8493   htab->nr_units = nr_units;
8494   htab->nr_slots = nr_slots;
8495   htab->hash_table = index_ptr;
8496   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8497   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8498
8499   return htab;
8500 }
8501
8502 /* Update SECTIONS with the data from SECTP.
8503
8504    This function is like the other "locate" section routines that are
8505    passed to bfd_map_over_sections, but in this context the sections to
8506    read comes from the DWP hash table, not the full ELF section table.
8507
8508    The result is non-zero for success, or zero if an error was found.  */
8509
8510 static int
8511 locate_virtual_dwo_sections (asection *sectp,
8512                              struct virtual_dwo_sections *sections)
8513 {
8514   const struct dwop_section_names *names = &dwop_section_names;
8515
8516   if (section_is_p (sectp->name, &names->abbrev_dwo))
8517     {
8518       /* There can be only one.  */
8519       if (sections->abbrev.asection != NULL)
8520         return 0;
8521       sections->abbrev.asection = sectp;
8522       sections->abbrev.size = bfd_get_section_size (sectp);
8523     }
8524   else if (section_is_p (sectp->name, &names->info_dwo)
8525            || section_is_p (sectp->name, &names->types_dwo))
8526     {
8527       /* There can be only one.  */
8528       if (sections->info_or_types.asection != NULL)
8529         return 0;
8530       sections->info_or_types.asection = sectp;
8531       sections->info_or_types.size = bfd_get_section_size (sectp);
8532     }
8533   else if (section_is_p (sectp->name, &names->line_dwo))
8534     {
8535       /* There can be only one.  */
8536       if (sections->line.asection != NULL)
8537         return 0;
8538       sections->line.asection = sectp;
8539       sections->line.size = bfd_get_section_size (sectp);
8540     }
8541   else if (section_is_p (sectp->name, &names->loc_dwo))
8542     {
8543       /* There can be only one.  */
8544       if (sections->loc.asection != NULL)
8545         return 0;
8546       sections->loc.asection = sectp;
8547       sections->loc.size = bfd_get_section_size (sectp);
8548     }
8549   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8550     {
8551       /* There can be only one.  */
8552       if (sections->macinfo.asection != NULL)
8553         return 0;
8554       sections->macinfo.asection = sectp;
8555       sections->macinfo.size = bfd_get_section_size (sectp);
8556     }
8557   else if (section_is_p (sectp->name, &names->macro_dwo))
8558     {
8559       /* There can be only one.  */
8560       if (sections->macro.asection != NULL)
8561         return 0;
8562       sections->macro.asection = sectp;
8563       sections->macro.size = bfd_get_section_size (sectp);
8564     }
8565   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8566     {
8567       /* There can be only one.  */
8568       if (sections->str_offsets.asection != NULL)
8569         return 0;
8570       sections->str_offsets.asection = sectp;
8571       sections->str_offsets.size = bfd_get_section_size (sectp);
8572     }
8573   else
8574     {
8575       /* No other kind of section is valid.  */
8576       return 0;
8577     }
8578
8579   return 1;
8580 }
8581
8582 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8583    HTAB is the hash table from the DWP file.
8584    SECTION_INDEX is the index of the DWO in HTAB.  */
8585
8586 static struct dwo_unit *
8587 create_dwo_in_dwp (struct dwp_file *dwp_file,
8588                    const struct dwp_hash_table *htab,
8589                    uint32_t section_index,
8590                    ULONGEST signature, int is_debug_types)
8591 {
8592   struct objfile *objfile = dwarf2_per_objfile->objfile;
8593   bfd *dbfd = dwp_file->dbfd;
8594   const char *kind = is_debug_types ? "TU" : "CU";
8595   struct dwo_file *dwo_file;
8596   struct dwo_unit *dwo_unit;
8597   struct virtual_dwo_sections sections;
8598   void **dwo_file_slot;
8599   char *virtual_dwo_name;
8600   struct dwarf2_section_info *cutu;
8601   struct cleanup *cleanups;
8602   int i;
8603
8604   if (dwarf2_read_debug)
8605     {
8606       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8607                           kind,
8608                           section_index, phex (signature, sizeof (signature)),
8609                           dwp_file->name);
8610     }
8611
8612   /* Fetch the sections of this DWO.
8613      Put a limit on the number of sections we look for so that bad data
8614      doesn't cause us to loop forever.  */
8615
8616 #define MAX_NR_DWO_SECTIONS \
8617   (1 /* .debug_info or .debug_types */ \
8618    + 1 /* .debug_abbrev */ \
8619    + 1 /* .debug_line */ \
8620    + 1 /* .debug_loc */ \
8621    + 1 /* .debug_str_offsets */ \
8622    + 1 /* .debug_macro */ \
8623    + 1 /* .debug_macinfo */ \
8624    + 1 /* trailing zero */)
8625
8626   memset (&sections, 0, sizeof (sections));
8627   cleanups = make_cleanup (null_cleanup, 0);
8628
8629   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8630     {
8631       asection *sectp;
8632       uint32_t section_nr =
8633         read_4_bytes (dbfd,
8634                       htab->section_pool
8635                       + (section_index + i) * sizeof (uint32_t));
8636
8637       if (section_nr == 0)
8638         break;
8639       if (section_nr >= dwp_file->num_sections)
8640         {
8641           error (_("Dwarf Error: bad DWP hash table, section number too large"
8642                    " [in module %s]"),
8643                  dwp_file->name);
8644         }
8645
8646       sectp = dwp_file->elf_sections[section_nr];
8647       if (! locate_virtual_dwo_sections (sectp, &sections))
8648         {
8649           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8650                    " [in module %s]"),
8651                  dwp_file->name);
8652         }
8653     }
8654
8655   if (i < 2
8656       || sections.info_or_types.asection == NULL
8657       || sections.abbrev.asection == NULL)
8658     {
8659       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8660                " [in module %s]"),
8661              dwp_file->name);
8662     }
8663   if (i == MAX_NR_DWO_SECTIONS)
8664     {
8665       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8666                " [in module %s]"),
8667              dwp_file->name);
8668     }
8669
8670   /* It's easier for the rest of the code if we fake a struct dwo_file and
8671      have dwo_unit "live" in that.  At least for now.
8672
8673      The DWP file can be made up of a random collection of CUs and TUs.
8674      However, for each CU + set of TUs that came from the same original DWO
8675      file, we want to combine them back into a virtual DWO file to save space
8676      (fewer struct dwo_file objects to allocated).  Remember that for really
8677      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8678
8679   virtual_dwo_name =
8680     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8681                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8682                 sections.line.asection ? sections.line.asection->id : 0,
8683                 sections.loc.asection ? sections.loc.asection->id : 0,
8684                 (sections.str_offsets.asection
8685                 ? sections.str_offsets.asection->id
8686                 : 0));
8687   make_cleanup (xfree, virtual_dwo_name);
8688   /* Can we use an existing virtual DWO file?  */
8689   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name);
8690   /* Create one if necessary.  */
8691   if (*dwo_file_slot == NULL)
8692     {
8693       if (dwarf2_read_debug)
8694         {
8695           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8696                               virtual_dwo_name);
8697         }
8698       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8699       dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8700                                       virtual_dwo_name,
8701                                       strlen (virtual_dwo_name));
8702       dwo_file->sections.abbrev = sections.abbrev;
8703       dwo_file->sections.line = sections.line;
8704       dwo_file->sections.loc = sections.loc;
8705       dwo_file->sections.macinfo = sections.macinfo;
8706       dwo_file->sections.macro = sections.macro;
8707       dwo_file->sections.str_offsets = sections.str_offsets;
8708       /* The "str" section is global to the entire DWP file.  */
8709       dwo_file->sections.str = dwp_file->sections.str;
8710       /* The info or types section is assigned later to dwo_unit,
8711          there's no need to record it in dwo_file.
8712          Also, we can't simply record type sections in dwo_file because
8713          we record a pointer into the vector in dwo_unit.  As we collect more
8714          types we'll grow the vector and eventually have to reallocate space
8715          for it, invalidating all the pointers into the current copy.  */
8716       *dwo_file_slot = dwo_file;
8717     }
8718   else
8719     {
8720       if (dwarf2_read_debug)
8721         {
8722           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8723                               virtual_dwo_name);
8724         }
8725       dwo_file = *dwo_file_slot;
8726     }
8727   do_cleanups (cleanups);
8728
8729   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8730   dwo_unit->dwo_file = dwo_file;
8731   dwo_unit->signature = signature;
8732   dwo_unit->info_or_types_section =
8733     obstack_alloc (&objfile->objfile_obstack,
8734                    sizeof (struct dwarf2_section_info));
8735   *dwo_unit->info_or_types_section = sections.info_or_types;
8736   /* offset, length, type_offset_in_tu are set later.  */
8737
8738   return dwo_unit;
8739 }
8740
8741 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8742
8743 static struct dwo_unit *
8744 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8745                    const struct dwp_hash_table *htab,
8746                    ULONGEST signature, int is_debug_types)
8747 {
8748   bfd *dbfd = dwp_file->dbfd;
8749   uint32_t mask = htab->nr_slots - 1;
8750   uint32_t hash = signature & mask;
8751   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8752   unsigned int i;
8753   void **slot;
8754   struct dwo_unit find_dwo_cu, *dwo_cu;
8755
8756   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8757   find_dwo_cu.signature = signature;
8758   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8759
8760   if (*slot != NULL)
8761     return *slot;
8762
8763   /* Use a for loop so that we don't loop forever on bad debug info.  */
8764   for (i = 0; i < htab->nr_slots; ++i)
8765     {
8766       ULONGEST signature_in_table;
8767
8768       signature_in_table =
8769         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8770       if (signature_in_table == signature)
8771         {
8772           uint32_t section_index =
8773             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8774
8775           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8776                                      signature, is_debug_types);
8777           return *slot;
8778         }
8779       if (signature_in_table == 0)
8780         return NULL;
8781       hash = (hash + hash2) & mask;
8782     }
8783
8784   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8785            " [in module %s]"),
8786          dwp_file->name);
8787 }
8788
8789 /* Subroutine of open_dwop_file to simplify it.
8790    Open the file specified by FILE_NAME and hand it off to BFD for
8791    preliminary analysis.  Return a newly initialized bfd *, which
8792    includes a canonicalized copy of FILE_NAME.
8793    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8794    In case of trouble, return NULL.
8795    NOTE: This function is derived from symfile_bfd_open.  */
8796
8797 static bfd *
8798 try_open_dwop_file (const char *file_name, int is_dwp)
8799 {
8800   bfd *sym_bfd;
8801   int desc, flags;
8802   char *absolute_name;
8803
8804   flags = OPF_TRY_CWD_FIRST;
8805   if (is_dwp)
8806     flags |= OPF_SEARCH_IN_PATH;
8807   desc = openp (debug_file_directory, flags, file_name,
8808                 O_RDONLY | O_BINARY, &absolute_name);
8809   if (desc < 0)
8810     return NULL;
8811
8812   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8813   if (!sym_bfd)
8814     {
8815       xfree (absolute_name);
8816       return NULL;
8817     }
8818   xfree (absolute_name);
8819   bfd_set_cacheable (sym_bfd, 1);
8820
8821   if (!bfd_check_format (sym_bfd, bfd_object))
8822     {
8823       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8824       return NULL;
8825     }
8826
8827   return sym_bfd;
8828 }
8829
8830 /* Try to open DWO/DWP file FILE_NAME.
8831    COMP_DIR is the DW_AT_comp_dir attribute.
8832    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8833    The result is the bfd handle of the file.
8834    If there is a problem finding or opening the file, return NULL.
8835    Upon success, the canonicalized path of the file is stored in the bfd,
8836    same as symfile_bfd_open.  */
8837
8838 static bfd *
8839 open_dwop_file (const char *file_name, const char *comp_dir, int is_dwp)
8840 {
8841   bfd *abfd;
8842
8843   if (IS_ABSOLUTE_PATH (file_name))
8844     return try_open_dwop_file (file_name, is_dwp);
8845
8846   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8847
8848   if (comp_dir != NULL)
8849     {
8850       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8851
8852       /* NOTE: If comp_dir is a relative path, this will also try the
8853          search path, which seems useful.  */
8854       abfd = try_open_dwop_file (path_to_try, is_dwp);
8855       xfree (path_to_try);
8856       if (abfd != NULL)
8857         return abfd;
8858     }
8859
8860   /* That didn't work, try debug-file-directory, which, despite its name,
8861      is a list of paths.  */
8862
8863   if (*debug_file_directory == '\0')
8864     return NULL;
8865
8866   return try_open_dwop_file (file_name, is_dwp);
8867 }
8868
8869 /* This function is mapped across the sections and remembers the offset and
8870    size of each of the DWO debugging sections we are interested in.  */
8871
8872 static void
8873 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
8874 {
8875   struct dwo_sections *dwo_sections = dwo_sections_ptr;
8876   const struct dwop_section_names *names = &dwop_section_names;
8877
8878   if (section_is_p (sectp->name, &names->abbrev_dwo))
8879     {
8880       dwo_sections->abbrev.asection = sectp;
8881       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
8882     }
8883   else if (section_is_p (sectp->name, &names->info_dwo))
8884     {
8885       dwo_sections->info.asection = sectp;
8886       dwo_sections->info.size = bfd_get_section_size (sectp);
8887     }
8888   else if (section_is_p (sectp->name, &names->line_dwo))
8889     {
8890       dwo_sections->line.asection = sectp;
8891       dwo_sections->line.size = bfd_get_section_size (sectp);
8892     }
8893   else if (section_is_p (sectp->name, &names->loc_dwo))
8894     {
8895       dwo_sections->loc.asection = sectp;
8896       dwo_sections->loc.size = bfd_get_section_size (sectp);
8897     }
8898   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8899     {
8900       dwo_sections->macinfo.asection = sectp;
8901       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
8902     }
8903   else if (section_is_p (sectp->name, &names->macro_dwo))
8904     {
8905       dwo_sections->macro.asection = sectp;
8906       dwo_sections->macro.size = bfd_get_section_size (sectp);
8907     }
8908   else if (section_is_p (sectp->name, &names->str_dwo))
8909     {
8910       dwo_sections->str.asection = sectp;
8911       dwo_sections->str.size = bfd_get_section_size (sectp);
8912     }
8913   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8914     {
8915       dwo_sections->str_offsets.asection = sectp;
8916       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
8917     }
8918   else if (section_is_p (sectp->name, &names->types_dwo))
8919     {
8920       struct dwarf2_section_info type_section;
8921
8922       memset (&type_section, 0, sizeof (type_section));
8923       type_section.asection = sectp;
8924       type_section.size = bfd_get_section_size (sectp);
8925       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
8926                      &type_section);
8927     }
8928 }
8929
8930 /* Initialize the use of the DWO file specified by DWO_NAME.
8931    The result is NULL if DWO_NAME can't be found.  */
8932
8933 static struct dwo_file *
8934 open_and_init_dwo_file (const char *dwo_name, const char *comp_dir)
8935 {
8936   struct objfile *objfile = dwarf2_per_objfile->objfile;
8937   struct dwo_file *dwo_file;
8938   bfd *dbfd;
8939   struct cleanup *cleanups;
8940
8941   dbfd = open_dwop_file (dwo_name, comp_dir, 0);
8942   if (dbfd == NULL)
8943     {
8944       if (dwarf2_read_debug)
8945         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
8946       return NULL;
8947     }
8948   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8949   dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8950                                   dwo_name, strlen (dwo_name));
8951   dwo_file->dbfd = dbfd;
8952
8953   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8954
8955   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
8956
8957   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
8958
8959   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8960                                                  dwo_file->sections.types);
8961
8962   discard_cleanups (cleanups);
8963
8964   if (dwarf2_read_debug)
8965     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
8966
8967   return dwo_file;
8968 }
8969
8970 /* This function is mapped across the sections and remembers the offset and
8971    size of each of the DWP debugging sections we are interested in.  */
8972
8973 static void
8974 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
8975 {
8976   struct dwp_file *dwp_file = dwp_file_ptr;
8977   const struct dwop_section_names *names = &dwop_section_names;
8978   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
8979
8980   /* Record the ELF section number for later lookup: this is what the
8981      .debug_cu_index,.debug_tu_index tables use.  */
8982   gdb_assert (elf_section_nr < dwp_file->num_sections);
8983   dwp_file->elf_sections[elf_section_nr] = sectp;
8984
8985   /* Look for specific sections that we need.  */
8986   if (section_is_p (sectp->name, &names->str_dwo))
8987     {
8988       dwp_file->sections.str.asection = sectp;
8989       dwp_file->sections.str.size = bfd_get_section_size (sectp);
8990     }
8991   else if (section_is_p (sectp->name, &names->cu_index))
8992     {
8993       dwp_file->sections.cu_index.asection = sectp;
8994       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
8995     }
8996   else if (section_is_p (sectp->name, &names->tu_index))
8997     {
8998       dwp_file->sections.tu_index.asection = sectp;
8999       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9000     }
9001 }
9002
9003 /* Hash function for dwp_file loaded CUs/TUs.  */
9004
9005 static hashval_t
9006 hash_dwp_loaded_cutus (const void *item)
9007 {
9008   const struct dwo_unit *dwo_unit = item;
9009
9010   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9011   return dwo_unit->signature;
9012 }
9013
9014 /* Equality function for dwp_file loaded CUs/TUs.  */
9015
9016 static int
9017 eq_dwp_loaded_cutus (const void *a, const void *b)
9018 {
9019   const struct dwo_unit *dua = a;
9020   const struct dwo_unit *dub = b;
9021
9022   return dua->signature == dub->signature;
9023 }
9024
9025 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9026
9027 static htab_t
9028 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9029 {
9030   return htab_create_alloc_ex (3,
9031                                hash_dwp_loaded_cutus,
9032                                eq_dwp_loaded_cutus,
9033                                NULL,
9034                                &objfile->objfile_obstack,
9035                                hashtab_obstack_allocate,
9036                                dummy_obstack_deallocate);
9037 }
9038
9039 /* Initialize the use of the DWP file for the current objfile.
9040    By convention the name of the DWP file is ${objfile}.dwp.
9041    The result is NULL if it can't be found.  */
9042
9043 static struct dwp_file *
9044 open_and_init_dwp_file (const char *comp_dir)
9045 {
9046   struct objfile *objfile = dwarf2_per_objfile->objfile;
9047   struct dwp_file *dwp_file;
9048   char *dwp_name;
9049   bfd *dbfd;
9050   struct cleanup *cleanups;
9051
9052   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9053   cleanups = make_cleanup (xfree, dwp_name);
9054
9055   dbfd = open_dwop_file (dwp_name, comp_dir, 1);
9056   if (dbfd == NULL)
9057     {
9058       if (dwarf2_read_debug)
9059         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9060       do_cleanups (cleanups);
9061       return NULL;
9062     }
9063   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9064   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9065                                   dwp_name, strlen (dwp_name));
9066   dwp_file->dbfd = dbfd;
9067   do_cleanups (cleanups);
9068
9069   cleanups = make_cleanup (free_dwo_file_cleanup, dwp_file);
9070
9071   /* +1: section 0 is unused */
9072   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9073   dwp_file->elf_sections =
9074     OBSTACK_CALLOC (&objfile->objfile_obstack,
9075                     dwp_file->num_sections, asection *);
9076
9077   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9078
9079   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9080
9081   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9082
9083   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9084
9085   discard_cleanups (cleanups);
9086
9087   if (dwarf2_read_debug)
9088     {
9089       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9090       fprintf_unfiltered (gdb_stdlog,
9091                           "    %u CUs, %u TUs\n",
9092                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9093                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9094     }
9095
9096   return dwp_file;
9097 }
9098
9099 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9100    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9101    or in the DWP file for the objfile, referenced by THIS_UNIT.
9102    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9103    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9104
9105    This is called, for example, when wanting to read a variable with a
9106    complex location.  Therefore we don't want to do file i/o for every call.
9107    Therefore we don't want to look for a DWO file on every call.
9108    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9109    then we check if we've already seen DWO_NAME, and only THEN do we check
9110    for a DWO file.
9111
9112    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9113    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9114
9115 static struct dwo_unit *
9116 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9117                  const char *dwo_name, const char *comp_dir,
9118                  ULONGEST signature, int is_debug_types)
9119 {
9120   struct objfile *objfile = dwarf2_per_objfile->objfile;
9121   const char *kind = is_debug_types ? "TU" : "CU";
9122   void **dwo_file_slot;
9123   struct dwo_file *dwo_file;
9124   struct dwp_file *dwp_file;
9125
9126   /* Have we already read SIGNATURE from a DWP file?  */
9127
9128   if (! dwarf2_per_objfile->dwp_checked)
9129     {
9130       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file (comp_dir);
9131       dwarf2_per_objfile->dwp_checked = 1;
9132     }
9133   dwp_file = dwarf2_per_objfile->dwp_file;
9134
9135   if (dwp_file != NULL)
9136     {
9137       const struct dwp_hash_table *dwp_htab =
9138         is_debug_types ? dwp_file->tus : dwp_file->cus;
9139
9140       if (dwp_htab != NULL)
9141         {
9142           struct dwo_unit *dwo_cutu =
9143             lookup_dwo_in_dwp (dwp_file, dwp_htab, signature, is_debug_types);
9144
9145           if (dwo_cutu != NULL)
9146             {
9147               if (dwarf2_read_debug)
9148                 {
9149                   fprintf_unfiltered (gdb_stdlog,
9150                                       "Virtual DWO %s %s found: @%s\n",
9151                                       kind, hex_string (signature),
9152                                       host_address_to_string (dwo_cutu));
9153                 }
9154               return dwo_cutu;
9155             }
9156         }
9157     }
9158
9159   /* Have we already seen DWO_NAME?  */
9160
9161   dwo_file_slot = lookup_dwo_file_slot (dwo_name);
9162   if (*dwo_file_slot == NULL)
9163     {
9164       /* Read in the file and build a table of the DWOs it contains.  */
9165       *dwo_file_slot = open_and_init_dwo_file (dwo_name, comp_dir);
9166     }
9167   /* NOTE: This will be NULL if unable to open the file.  */
9168   dwo_file = *dwo_file_slot;
9169
9170   if (dwo_file != NULL)
9171     {
9172       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9173
9174       if (htab != NULL)
9175         {
9176           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9177
9178           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9179           find_dwo_cutu.signature = signature;
9180           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9181
9182           if (dwo_cutu != NULL)
9183             {
9184               if (dwarf2_read_debug)
9185                 {
9186                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9187                                       kind, dwo_name, hex_string (signature),
9188                                       host_address_to_string (dwo_cutu));
9189                 }
9190               return dwo_cutu;
9191             }
9192         }
9193     }
9194
9195   /* We didn't find it.  This could mean a dwo_id mismatch, or
9196      someone deleted the DWO/DWP file, or the search path isn't set up
9197      correctly to find the file.  */
9198
9199   if (dwarf2_read_debug)
9200     {
9201       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9202                           kind, dwo_name, hex_string (signature));
9203     }
9204
9205   complaint (&symfile_complaints,
9206              _("Could not find DWO CU referenced by CU at offset 0x%x"
9207                " [in module %s]"),
9208              this_unit->offset.sect_off, objfile->name);
9209   return NULL;
9210 }
9211
9212 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9213    See lookup_dwo_cutu_unit for details.  */
9214
9215 static struct dwo_unit *
9216 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9217                       const char *dwo_name, const char *comp_dir,
9218                       ULONGEST signature)
9219 {
9220   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9221 }
9222
9223 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9224    See lookup_dwo_cutu_unit for details.  */
9225
9226 static struct dwo_unit *
9227 lookup_dwo_type_unit (struct signatured_type *this_tu,
9228                       const char *dwo_name, const char *comp_dir)
9229 {
9230   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9231 }
9232
9233 /* Free all resources associated with DWO_FILE.
9234    Close the DWO file and munmap the sections.
9235    All memory should be on the objfile obstack.  */
9236
9237 static void
9238 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9239 {
9240   int ix;
9241   struct dwarf2_section_info *section;
9242
9243   gdb_bfd_unref (dwo_file->dbfd);
9244
9245   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9246 }
9247
9248 /* Wrapper for free_dwo_file for use in cleanups.  */
9249
9250 static void
9251 free_dwo_file_cleanup (void *arg)
9252 {
9253   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9254   struct objfile *objfile = dwarf2_per_objfile->objfile;
9255
9256   free_dwo_file (dwo_file, objfile);
9257 }
9258
9259 /* Traversal function for free_dwo_files.  */
9260
9261 static int
9262 free_dwo_file_from_slot (void **slot, void *info)
9263 {
9264   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9265   struct objfile *objfile = (struct objfile *) info;
9266
9267   free_dwo_file (dwo_file, objfile);
9268
9269   return 1;
9270 }
9271
9272 /* Free all resources associated with DWO_FILES.  */
9273
9274 static void
9275 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9276 {
9277   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9278 }
9279 \f
9280 /* Read in various DIEs.  */
9281
9282 /* qsort helper for inherit_abstract_dies.  */
9283
9284 static int
9285 unsigned_int_compar (const void *ap, const void *bp)
9286 {
9287   unsigned int a = *(unsigned int *) ap;
9288   unsigned int b = *(unsigned int *) bp;
9289
9290   return (a > b) - (b > a);
9291 }
9292
9293 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9294    Inherit only the children of the DW_AT_abstract_origin DIE not being
9295    already referenced by DW_AT_abstract_origin from the children of the
9296    current DIE.  */
9297
9298 static void
9299 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9300 {
9301   struct die_info *child_die;
9302   unsigned die_children_count;
9303   /* CU offsets which were referenced by children of the current DIE.  */
9304   sect_offset *offsets;
9305   sect_offset *offsets_end, *offsetp;
9306   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9307   struct die_info *origin_die;
9308   /* Iterator of the ORIGIN_DIE children.  */
9309   struct die_info *origin_child_die;
9310   struct cleanup *cleanups;
9311   struct attribute *attr;
9312   struct dwarf2_cu *origin_cu;
9313   struct pending **origin_previous_list_in_scope;
9314
9315   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9316   if (!attr)
9317     return;
9318
9319   /* Note that following die references may follow to a die in a
9320      different cu.  */
9321
9322   origin_cu = cu;
9323   origin_die = follow_die_ref (die, attr, &origin_cu);
9324
9325   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9326      symbols in.  */
9327   origin_previous_list_in_scope = origin_cu->list_in_scope;
9328   origin_cu->list_in_scope = cu->list_in_scope;
9329
9330   if (die->tag != origin_die->tag
9331       && !(die->tag == DW_TAG_inlined_subroutine
9332            && origin_die->tag == DW_TAG_subprogram))
9333     complaint (&symfile_complaints,
9334                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9335                die->offset.sect_off, origin_die->offset.sect_off);
9336
9337   child_die = die->child;
9338   die_children_count = 0;
9339   while (child_die && child_die->tag)
9340     {
9341       child_die = sibling_die (child_die);
9342       die_children_count++;
9343     }
9344   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9345   cleanups = make_cleanup (xfree, offsets);
9346
9347   offsets_end = offsets;
9348   child_die = die->child;
9349   while (child_die && child_die->tag)
9350     {
9351       /* For each CHILD_DIE, find the corresponding child of
9352          ORIGIN_DIE.  If there is more than one layer of
9353          DW_AT_abstract_origin, follow them all; there shouldn't be,
9354          but GCC versions at least through 4.4 generate this (GCC PR
9355          40573).  */
9356       struct die_info *child_origin_die = child_die;
9357       struct dwarf2_cu *child_origin_cu = cu;
9358
9359       while (1)
9360         {
9361           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9362                               child_origin_cu);
9363           if (attr == NULL)
9364             break;
9365           child_origin_die = follow_die_ref (child_origin_die, attr,
9366                                              &child_origin_cu);
9367         }
9368
9369       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9370          counterpart may exist.  */
9371       if (child_origin_die != child_die)
9372         {
9373           if (child_die->tag != child_origin_die->tag
9374               && !(child_die->tag == DW_TAG_inlined_subroutine
9375                    && child_origin_die->tag == DW_TAG_subprogram))
9376             complaint (&symfile_complaints,
9377                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9378                          "different tags"), child_die->offset.sect_off,
9379                        child_origin_die->offset.sect_off);
9380           if (child_origin_die->parent != origin_die)
9381             complaint (&symfile_complaints,
9382                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9383                          "different parents"), child_die->offset.sect_off,
9384                        child_origin_die->offset.sect_off);
9385           else
9386             *offsets_end++ = child_origin_die->offset;
9387         }
9388       child_die = sibling_die (child_die);
9389     }
9390   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9391          unsigned_int_compar);
9392   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9393     if (offsetp[-1].sect_off == offsetp->sect_off)
9394       complaint (&symfile_complaints,
9395                  _("Multiple children of DIE 0x%x refer "
9396                    "to DIE 0x%x as their abstract origin"),
9397                  die->offset.sect_off, offsetp->sect_off);
9398
9399   offsetp = offsets;
9400   origin_child_die = origin_die->child;
9401   while (origin_child_die && origin_child_die->tag)
9402     {
9403       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9404       while (offsetp < offsets_end
9405              && offsetp->sect_off < origin_child_die->offset.sect_off)
9406         offsetp++;
9407       if (offsetp >= offsets_end
9408           || offsetp->sect_off > origin_child_die->offset.sect_off)
9409         {
9410           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9411           process_die (origin_child_die, origin_cu);
9412         }
9413       origin_child_die = sibling_die (origin_child_die);
9414     }
9415   origin_cu->list_in_scope = origin_previous_list_in_scope;
9416
9417   do_cleanups (cleanups);
9418 }
9419
9420 static void
9421 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9422 {
9423   struct objfile *objfile = cu->objfile;
9424   struct context_stack *new;
9425   CORE_ADDR lowpc;
9426   CORE_ADDR highpc;
9427   struct die_info *child_die;
9428   struct attribute *attr, *call_line, *call_file;
9429   const char *name;
9430   CORE_ADDR baseaddr;
9431   struct block *block;
9432   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9433   VEC (symbolp) *template_args = NULL;
9434   struct template_symbol *templ_func = NULL;
9435
9436   if (inlined_func)
9437     {
9438       /* If we do not have call site information, we can't show the
9439          caller of this inlined function.  That's too confusing, so
9440          only use the scope for local variables.  */
9441       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9442       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9443       if (call_line == NULL || call_file == NULL)
9444         {
9445           read_lexical_block_scope (die, cu);
9446           return;
9447         }
9448     }
9449
9450   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9451
9452   name = dwarf2_name (die, cu);
9453
9454   /* Ignore functions with missing or empty names.  These are actually
9455      illegal according to the DWARF standard.  */
9456   if (name == NULL)
9457     {
9458       complaint (&symfile_complaints,
9459                  _("missing name for subprogram DIE at %d"),
9460                  die->offset.sect_off);
9461       return;
9462     }
9463
9464   /* Ignore functions with missing or invalid low and high pc attributes.  */
9465   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9466     {
9467       attr = dwarf2_attr (die, DW_AT_external, cu);
9468       if (!attr || !DW_UNSND (attr))
9469         complaint (&symfile_complaints,
9470                    _("cannot get low and high bounds "
9471                      "for subprogram DIE at %d"),
9472                    die->offset.sect_off);
9473       return;
9474     }
9475
9476   lowpc += baseaddr;
9477   highpc += baseaddr;
9478
9479   /* If we have any template arguments, then we must allocate a
9480      different sort of symbol.  */
9481   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9482     {
9483       if (child_die->tag == DW_TAG_template_type_param
9484           || child_die->tag == DW_TAG_template_value_param)
9485         {
9486           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9487                                        struct template_symbol);
9488           templ_func->base.is_cplus_template_function = 1;
9489           break;
9490         }
9491     }
9492
9493   new = push_context (0, lowpc);
9494   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9495                                (struct symbol *) templ_func);
9496
9497   /* If there is a location expression for DW_AT_frame_base, record
9498      it.  */
9499   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9500   if (attr)
9501     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
9502        expression is being recorded directly in the function's symbol
9503        and not in a separate frame-base object.  I guess this hack is
9504        to avoid adding some sort of frame-base adjunct/annex to the
9505        function's symbol :-(.  The problem with doing this is that it
9506        results in a function symbol with a location expression that
9507        has nothing to do with the location of the function, ouch!  The
9508        relationship should be: a function's symbol has-a frame base; a
9509        frame-base has-a location expression.  */
9510     dwarf2_symbol_mark_computed (attr, new->name, cu);
9511
9512   cu->list_in_scope = &local_symbols;
9513
9514   if (die->child != NULL)
9515     {
9516       child_die = die->child;
9517       while (child_die && child_die->tag)
9518         {
9519           if (child_die->tag == DW_TAG_template_type_param
9520               || child_die->tag == DW_TAG_template_value_param)
9521             {
9522               struct symbol *arg = new_symbol (child_die, NULL, cu);
9523
9524               if (arg != NULL)
9525                 VEC_safe_push (symbolp, template_args, arg);
9526             }
9527           else
9528             process_die (child_die, cu);
9529           child_die = sibling_die (child_die);
9530         }
9531     }
9532
9533   inherit_abstract_dies (die, cu);
9534
9535   /* If we have a DW_AT_specification, we might need to import using
9536      directives from the context of the specification DIE.  See the
9537      comment in determine_prefix.  */
9538   if (cu->language == language_cplus
9539       && dwarf2_attr (die, DW_AT_specification, cu))
9540     {
9541       struct dwarf2_cu *spec_cu = cu;
9542       struct die_info *spec_die = die_specification (die, &spec_cu);
9543
9544       while (spec_die)
9545         {
9546           child_die = spec_die->child;
9547           while (child_die && child_die->tag)
9548             {
9549               if (child_die->tag == DW_TAG_imported_module)
9550                 process_die (child_die, spec_cu);
9551               child_die = sibling_die (child_die);
9552             }
9553
9554           /* In some cases, GCC generates specification DIEs that
9555              themselves contain DW_AT_specification attributes.  */
9556           spec_die = die_specification (spec_die, &spec_cu);
9557         }
9558     }
9559
9560   new = pop_context ();
9561   /* Make a block for the local symbols within.  */
9562   block = finish_block (new->name, &local_symbols, new->old_blocks,
9563                         lowpc, highpc, objfile);
9564
9565   /* For C++, set the block's scope.  */
9566   if ((cu->language == language_cplus || cu->language == language_fortran)
9567       && cu->processing_has_namespace_info)
9568     block_set_scope (block, determine_prefix (die, cu),
9569                      &objfile->objfile_obstack);
9570
9571   /* If we have address ranges, record them.  */
9572   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9573
9574   /* Attach template arguments to function.  */
9575   if (! VEC_empty (symbolp, template_args))
9576     {
9577       gdb_assert (templ_func != NULL);
9578
9579       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9580       templ_func->template_arguments
9581         = obstack_alloc (&objfile->objfile_obstack,
9582                          (templ_func->n_template_arguments
9583                           * sizeof (struct symbol *)));
9584       memcpy (templ_func->template_arguments,
9585               VEC_address (symbolp, template_args),
9586               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9587       VEC_free (symbolp, template_args);
9588     }
9589
9590   /* In C++, we can have functions nested inside functions (e.g., when
9591      a function declares a class that has methods).  This means that
9592      when we finish processing a function scope, we may need to go
9593      back to building a containing block's symbol lists.  */
9594   local_symbols = new->locals;
9595   using_directives = new->using_directives;
9596
9597   /* If we've finished processing a top-level function, subsequent
9598      symbols go in the file symbol list.  */
9599   if (outermost_context_p ())
9600     cu->list_in_scope = &file_symbols;
9601 }
9602
9603 /* Process all the DIES contained within a lexical block scope.  Start
9604    a new scope, process the dies, and then close the scope.  */
9605
9606 static void
9607 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9608 {
9609   struct objfile *objfile = cu->objfile;
9610   struct context_stack *new;
9611   CORE_ADDR lowpc, highpc;
9612   struct die_info *child_die;
9613   CORE_ADDR baseaddr;
9614
9615   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9616
9617   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9618   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9619      as multiple lexical blocks?  Handling children in a sane way would
9620      be nasty.  Might be easier to properly extend generic blocks to
9621      describe ranges.  */
9622   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9623     return;
9624   lowpc += baseaddr;
9625   highpc += baseaddr;
9626
9627   push_context (0, lowpc);
9628   if (die->child != NULL)
9629     {
9630       child_die = die->child;
9631       while (child_die && child_die->tag)
9632         {
9633           process_die (child_die, cu);
9634           child_die = sibling_die (child_die);
9635         }
9636     }
9637   new = pop_context ();
9638
9639   if (local_symbols != NULL || using_directives != NULL)
9640     {
9641       struct block *block
9642         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9643                         highpc, objfile);
9644
9645       /* Note that recording ranges after traversing children, as we
9646          do here, means that recording a parent's ranges entails
9647          walking across all its children's ranges as they appear in
9648          the address map, which is quadratic behavior.
9649
9650          It would be nicer to record the parent's ranges before
9651          traversing its children, simply overriding whatever you find
9652          there.  But since we don't even decide whether to create a
9653          block until after we've traversed its children, that's hard
9654          to do.  */
9655       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9656     }
9657   local_symbols = new->locals;
9658   using_directives = new->using_directives;
9659 }
9660
9661 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9662
9663 static void
9664 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9665 {
9666   struct objfile *objfile = cu->objfile;
9667   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9668   CORE_ADDR pc, baseaddr;
9669   struct attribute *attr;
9670   struct call_site *call_site, call_site_local;
9671   void **slot;
9672   int nparams;
9673   struct die_info *child_die;
9674
9675   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9676
9677   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9678   if (!attr)
9679     {
9680       complaint (&symfile_complaints,
9681                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9682                    "DIE 0x%x [in module %s]"),
9683                  die->offset.sect_off, objfile->name);
9684       return;
9685     }
9686   pc = DW_ADDR (attr) + baseaddr;
9687
9688   if (cu->call_site_htab == NULL)
9689     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9690                                                NULL, &objfile->objfile_obstack,
9691                                                hashtab_obstack_allocate, NULL);
9692   call_site_local.pc = pc;
9693   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9694   if (*slot != NULL)
9695     {
9696       complaint (&symfile_complaints,
9697                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9698                    "DIE 0x%x [in module %s]"),
9699                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9700       return;
9701     }
9702
9703   /* Count parameters at the caller.  */
9704
9705   nparams = 0;
9706   for (child_die = die->child; child_die && child_die->tag;
9707        child_die = sibling_die (child_die))
9708     {
9709       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9710         {
9711           complaint (&symfile_complaints,
9712                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9713                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9714                      child_die->tag, child_die->offset.sect_off, objfile->name);
9715           continue;
9716         }
9717
9718       nparams++;
9719     }
9720
9721   call_site = obstack_alloc (&objfile->objfile_obstack,
9722                              (sizeof (*call_site)
9723                               + (sizeof (*call_site->parameter)
9724                                  * (nparams - 1))));
9725   *slot = call_site;
9726   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9727   call_site->pc = pc;
9728
9729   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9730     {
9731       struct die_info *func_die;
9732
9733       /* Skip also over DW_TAG_inlined_subroutine.  */
9734       for (func_die = die->parent;
9735            func_die && func_die->tag != DW_TAG_subprogram
9736            && func_die->tag != DW_TAG_subroutine_type;
9737            func_die = func_die->parent);
9738
9739       /* DW_AT_GNU_all_call_sites is a superset
9740          of DW_AT_GNU_all_tail_call_sites.  */
9741       if (func_die
9742           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9743           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9744         {
9745           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9746              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9747              both the initial caller containing the real return address PC and
9748              the final callee containing the current PC of a chain of tail
9749              calls do not need to have the tail call list complete.  But any
9750              function candidate for a virtual tail call frame searched via
9751              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9752              determined unambiguously.  */
9753         }
9754       else
9755         {
9756           struct type *func_type = NULL;
9757
9758           if (func_die)
9759             func_type = get_die_type (func_die, cu);
9760           if (func_type != NULL)
9761             {
9762               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9763
9764               /* Enlist this call site to the function.  */
9765               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9766               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9767             }
9768           else
9769             complaint (&symfile_complaints,
9770                        _("Cannot find function owning DW_TAG_GNU_call_site "
9771                          "DIE 0x%x [in module %s]"),
9772                        die->offset.sect_off, objfile->name);
9773         }
9774     }
9775
9776   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9777   if (attr == NULL)
9778     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9779   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9780   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9781     /* Keep NULL DWARF_BLOCK.  */;
9782   else if (attr_form_is_block (attr))
9783     {
9784       struct dwarf2_locexpr_baton *dlbaton;
9785
9786       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9787       dlbaton->data = DW_BLOCK (attr)->data;
9788       dlbaton->size = DW_BLOCK (attr)->size;
9789       dlbaton->per_cu = cu->per_cu;
9790
9791       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9792     }
9793   else if (is_ref_attr (attr))
9794     {
9795       struct dwarf2_cu *target_cu = cu;
9796       struct die_info *target_die;
9797
9798       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9799       gdb_assert (target_cu->objfile == objfile);
9800       if (die_is_declaration (target_die, target_cu))
9801         {
9802           const char *target_physname;
9803
9804           target_physname = dwarf2_physname (NULL, target_die, target_cu);
9805           if (target_physname == NULL)
9806             complaint (&symfile_complaints,
9807                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9808                          "physname, for referencing DIE 0x%x [in module %s]"),
9809                        die->offset.sect_off, objfile->name);
9810           else
9811             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9812         }
9813       else
9814         {
9815           CORE_ADDR lowpc;
9816
9817           /* DW_AT_entry_pc should be preferred.  */
9818           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9819             complaint (&symfile_complaints,
9820                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9821                          "low pc, for referencing DIE 0x%x [in module %s]"),
9822                        die->offset.sect_off, objfile->name);
9823           else
9824             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9825         }
9826     }
9827   else
9828     complaint (&symfile_complaints,
9829                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9830                  "block nor reference, for DIE 0x%x [in module %s]"),
9831                die->offset.sect_off, objfile->name);
9832
9833   call_site->per_cu = cu->per_cu;
9834
9835   for (child_die = die->child;
9836        child_die && child_die->tag;
9837        child_die = sibling_die (child_die))
9838     {
9839       struct call_site_parameter *parameter;
9840       struct attribute *loc, *origin;
9841
9842       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9843         {
9844           /* Already printed the complaint above.  */
9845           continue;
9846         }
9847
9848       gdb_assert (call_site->parameter_count < nparams);
9849       parameter = &call_site->parameter[call_site->parameter_count];
9850
9851       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
9852          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
9853          register is contained in DW_AT_GNU_call_site_value.  */
9854
9855       loc = dwarf2_attr (child_die, DW_AT_location, cu);
9856       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
9857       if (loc == NULL && origin != NULL && is_ref_attr (origin))
9858         {
9859           sect_offset offset;
9860
9861           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
9862           offset = dwarf2_get_ref_die_offset (origin);
9863           if (!offset_in_cu_p (&cu->header, offset))
9864             {
9865               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
9866                  binding can be done only inside one CU.  Such referenced DIE
9867                  therefore cannot be even moved to DW_TAG_partial_unit.  */
9868               complaint (&symfile_complaints,
9869                          _("DW_AT_abstract_origin offset is not in CU for "
9870                            "DW_TAG_GNU_call_site child DIE 0x%x "
9871                            "[in module %s]"),
9872                          child_die->offset.sect_off, objfile->name);
9873               continue;
9874             }
9875           parameter->u.param_offset.cu_off = (offset.sect_off
9876                                               - cu->header.offset.sect_off);
9877         }
9878       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
9879         {
9880           complaint (&symfile_complaints,
9881                      _("No DW_FORM_block* DW_AT_location for "
9882                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9883                      child_die->offset.sect_off, objfile->name);
9884           continue;
9885         }
9886       else
9887         {
9888           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
9889             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
9890           if (parameter->u.dwarf_reg != -1)
9891             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
9892           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
9893                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
9894                                              &parameter->u.fb_offset))
9895             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
9896           else
9897             {
9898               complaint (&symfile_complaints,
9899                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
9900                            "for DW_FORM_block* DW_AT_location is supported for "
9901                            "DW_TAG_GNU_call_site child DIE 0x%x "
9902                            "[in module %s]"),
9903                          child_die->offset.sect_off, objfile->name);
9904               continue;
9905             }
9906         }
9907
9908       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
9909       if (!attr_form_is_block (attr))
9910         {
9911           complaint (&symfile_complaints,
9912                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
9913                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9914                      child_die->offset.sect_off, objfile->name);
9915           continue;
9916         }
9917       parameter->value = DW_BLOCK (attr)->data;
9918       parameter->value_size = DW_BLOCK (attr)->size;
9919
9920       /* Parameters are not pre-cleared by memset above.  */
9921       parameter->data_value = NULL;
9922       parameter->data_value_size = 0;
9923       call_site->parameter_count++;
9924
9925       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
9926       if (attr)
9927         {
9928           if (!attr_form_is_block (attr))
9929             complaint (&symfile_complaints,
9930                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
9931                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9932                        child_die->offset.sect_off, objfile->name);
9933           else
9934             {
9935               parameter->data_value = DW_BLOCK (attr)->data;
9936               parameter->data_value_size = DW_BLOCK (attr)->size;
9937             }
9938         }
9939     }
9940 }
9941
9942 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
9943    Return 1 if the attributes are present and valid, otherwise, return 0.
9944    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
9945
9946 static int
9947 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
9948                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
9949                     struct partial_symtab *ranges_pst)
9950 {
9951   struct objfile *objfile = cu->objfile;
9952   struct comp_unit_head *cu_header = &cu->header;
9953   bfd *obfd = objfile->obfd;
9954   unsigned int addr_size = cu_header->addr_size;
9955   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9956   /* Base address selection entry.  */
9957   CORE_ADDR base;
9958   int found_base;
9959   unsigned int dummy;
9960   gdb_byte *buffer;
9961   CORE_ADDR marker;
9962   int low_set;
9963   CORE_ADDR low = 0;
9964   CORE_ADDR high = 0;
9965   CORE_ADDR baseaddr;
9966
9967   found_base = cu->base_known;
9968   base = cu->base_address;
9969
9970   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
9971   if (offset >= dwarf2_per_objfile->ranges.size)
9972     {
9973       complaint (&symfile_complaints,
9974                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
9975                  offset);
9976       return 0;
9977     }
9978   buffer = dwarf2_per_objfile->ranges.buffer + offset;
9979
9980   /* Read in the largest possible address.  */
9981   marker = read_address (obfd, buffer, cu, &dummy);
9982   if ((marker & mask) == mask)
9983     {
9984       /* If we found the largest possible address, then
9985          read the base address.  */
9986       base = read_address (obfd, buffer + addr_size, cu, &dummy);
9987       buffer += 2 * addr_size;
9988       offset += 2 * addr_size;
9989       found_base = 1;
9990     }
9991
9992   low_set = 0;
9993
9994   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9995
9996   while (1)
9997     {
9998       CORE_ADDR range_beginning, range_end;
9999
10000       range_beginning = read_address (obfd, buffer, cu, &dummy);
10001       buffer += addr_size;
10002       range_end = read_address (obfd, buffer, cu, &dummy);
10003       buffer += addr_size;
10004       offset += 2 * addr_size;
10005
10006       /* An end of list marker is a pair of zero addresses.  */
10007       if (range_beginning == 0 && range_end == 0)
10008         /* Found the end of list entry.  */
10009         break;
10010
10011       /* Each base address selection entry is a pair of 2 values.
10012          The first is the largest possible address, the second is
10013          the base address.  Check for a base address here.  */
10014       if ((range_beginning & mask) == mask)
10015         {
10016           /* If we found the largest possible address, then
10017              read the base address.  */
10018           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10019           found_base = 1;
10020           continue;
10021         }
10022
10023       if (!found_base)
10024         {
10025           /* We have no valid base address for the ranges
10026              data.  */
10027           complaint (&symfile_complaints,
10028                      _("Invalid .debug_ranges data (no base address)"));
10029           return 0;
10030         }
10031
10032       if (range_beginning > range_end)
10033         {
10034           /* Inverted range entries are invalid.  */
10035           complaint (&symfile_complaints,
10036                      _("Invalid .debug_ranges data (inverted range)"));
10037           return 0;
10038         }
10039
10040       /* Empty range entries have no effect.  */
10041       if (range_beginning == range_end)
10042         continue;
10043
10044       range_beginning += base;
10045       range_end += base;
10046
10047       /* A not-uncommon case of bad debug info.
10048          Don't pollute the addrmap with bad data.  */
10049       if (range_beginning + baseaddr == 0
10050           && !dwarf2_per_objfile->has_section_at_zero)
10051         {
10052           complaint (&symfile_complaints,
10053                      _(".debug_ranges entry has start address of zero"
10054                        " [in module %s]"), objfile->name);
10055           continue;
10056         }
10057
10058       if (ranges_pst != NULL)
10059         addrmap_set_empty (objfile->psymtabs_addrmap,
10060                            range_beginning + baseaddr,
10061                            range_end - 1 + baseaddr,
10062                            ranges_pst);
10063
10064       /* FIXME: This is recording everything as a low-high
10065          segment of consecutive addresses.  We should have a
10066          data structure for discontiguous block ranges
10067          instead.  */
10068       if (! low_set)
10069         {
10070           low = range_beginning;
10071           high = range_end;
10072           low_set = 1;
10073         }
10074       else
10075         {
10076           if (range_beginning < low)
10077             low = range_beginning;
10078           if (range_end > high)
10079             high = range_end;
10080         }
10081     }
10082
10083   if (! low_set)
10084     /* If the first entry is an end-of-list marker, the range
10085        describes an empty scope, i.e. no instructions.  */
10086     return 0;
10087
10088   if (low_return)
10089     *low_return = low;
10090   if (high_return)
10091     *high_return = high;
10092   return 1;
10093 }
10094
10095 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10096    are present and valid, otherwise, return 0.  Return -1 if the range is
10097    discontinuous, i.e. derived from DW_AT_ranges information.  */
10098
10099 static int
10100 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10101                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10102                       struct partial_symtab *pst)
10103 {
10104   struct attribute *attr;
10105   struct attribute *attr_high;
10106   CORE_ADDR low = 0;
10107   CORE_ADDR high = 0;
10108   int ret = 0;
10109
10110   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10111   if (attr_high)
10112     {
10113       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10114       if (attr)
10115         {
10116           low = DW_ADDR (attr);
10117           if (attr_high->form == DW_FORM_addr
10118               || attr_high->form == DW_FORM_GNU_addr_index)
10119             high = DW_ADDR (attr_high);
10120           else
10121             high = low + DW_UNSND (attr_high);
10122         }
10123       else
10124         /* Found high w/o low attribute.  */
10125         return 0;
10126
10127       /* Found consecutive range of addresses.  */
10128       ret = 1;
10129     }
10130   else
10131     {
10132       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10133       if (attr != NULL)
10134         {
10135           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10136              We take advantage of the fact that DW_AT_ranges does not appear
10137              in DW_TAG_compile_unit of DWO files.  */
10138           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10139           unsigned int ranges_offset = (DW_UNSND (attr)
10140                                         + (need_ranges_base
10141                                            ? cu->ranges_base
10142                                            : 0));
10143
10144           /* Value of the DW_AT_ranges attribute is the offset in the
10145              .debug_ranges section.  */
10146           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10147             return 0;
10148           /* Found discontinuous range of addresses.  */
10149           ret = -1;
10150         }
10151     }
10152
10153   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10154   if (high <= low)
10155     return 0;
10156
10157   /* When using the GNU linker, .gnu.linkonce. sections are used to
10158      eliminate duplicate copies of functions and vtables and such.
10159      The linker will arbitrarily choose one and discard the others.
10160      The AT_*_pc values for such functions refer to local labels in
10161      these sections.  If the section from that file was discarded, the
10162      labels are not in the output, so the relocs get a value of 0.
10163      If this is a discarded function, mark the pc bounds as invalid,
10164      so that GDB will ignore it.  */
10165   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10166     return 0;
10167
10168   *lowpc = low;
10169   if (highpc)
10170     *highpc = high;
10171   return ret;
10172 }
10173
10174 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10175    its low and high PC addresses.  Do nothing if these addresses could not
10176    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10177    and HIGHPC to the high address if greater than HIGHPC.  */
10178
10179 static void
10180 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10181                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10182                                  struct dwarf2_cu *cu)
10183 {
10184   CORE_ADDR low, high;
10185   struct die_info *child = die->child;
10186
10187   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10188     {
10189       *lowpc = min (*lowpc, low);
10190       *highpc = max (*highpc, high);
10191     }
10192
10193   /* If the language does not allow nested subprograms (either inside
10194      subprograms or lexical blocks), we're done.  */
10195   if (cu->language != language_ada)
10196     return;
10197
10198   /* Check all the children of the given DIE.  If it contains nested
10199      subprograms, then check their pc bounds.  Likewise, we need to
10200      check lexical blocks as well, as they may also contain subprogram
10201      definitions.  */
10202   while (child && child->tag)
10203     {
10204       if (child->tag == DW_TAG_subprogram
10205           || child->tag == DW_TAG_lexical_block)
10206         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10207       child = sibling_die (child);
10208     }
10209 }
10210
10211 /* Get the low and high pc's represented by the scope DIE, and store
10212    them in *LOWPC and *HIGHPC.  If the correct values can't be
10213    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10214
10215 static void
10216 get_scope_pc_bounds (struct die_info *die,
10217                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10218                      struct dwarf2_cu *cu)
10219 {
10220   CORE_ADDR best_low = (CORE_ADDR) -1;
10221   CORE_ADDR best_high = (CORE_ADDR) 0;
10222   CORE_ADDR current_low, current_high;
10223
10224   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10225     {
10226       best_low = current_low;
10227       best_high = current_high;
10228     }
10229   else
10230     {
10231       struct die_info *child = die->child;
10232
10233       while (child && child->tag)
10234         {
10235           switch (child->tag) {
10236           case DW_TAG_subprogram:
10237             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10238             break;
10239           case DW_TAG_namespace:
10240           case DW_TAG_module:
10241             /* FIXME: carlton/2004-01-16: Should we do this for
10242                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10243                that current GCC's always emit the DIEs corresponding
10244                to definitions of methods of classes as children of a
10245                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10246                the DIEs giving the declarations, which could be
10247                anywhere).  But I don't see any reason why the
10248                standards says that they have to be there.  */
10249             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10250
10251             if (current_low != ((CORE_ADDR) -1))
10252               {
10253                 best_low = min (best_low, current_low);
10254                 best_high = max (best_high, current_high);
10255               }
10256             break;
10257           default:
10258             /* Ignore.  */
10259             break;
10260           }
10261
10262           child = sibling_die (child);
10263         }
10264     }
10265
10266   *lowpc = best_low;
10267   *highpc = best_high;
10268 }
10269
10270 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10271    in DIE.  */
10272
10273 static void
10274 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10275                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10276 {
10277   struct objfile *objfile = cu->objfile;
10278   struct attribute *attr;
10279   struct attribute *attr_high;
10280
10281   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10282   if (attr_high)
10283     {
10284       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10285       if (attr)
10286         {
10287           CORE_ADDR low = DW_ADDR (attr);
10288           CORE_ADDR high;
10289           if (attr_high->form == DW_FORM_addr
10290               || attr_high->form == DW_FORM_GNU_addr_index)
10291             high = DW_ADDR (attr_high);
10292           else
10293             high = low + DW_UNSND (attr_high);
10294
10295           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10296         }
10297     }
10298
10299   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10300   if (attr)
10301     {
10302       bfd *obfd = objfile->obfd;
10303       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10304          We take advantage of the fact that DW_AT_ranges does not appear
10305          in DW_TAG_compile_unit of DWO files.  */
10306       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10307
10308       /* The value of the DW_AT_ranges attribute is the offset of the
10309          address range list in the .debug_ranges section.  */
10310       unsigned long offset = (DW_UNSND (attr)
10311                               + (need_ranges_base ? cu->ranges_base : 0));
10312       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10313
10314       /* For some target architectures, but not others, the
10315          read_address function sign-extends the addresses it returns.
10316          To recognize base address selection entries, we need a
10317          mask.  */
10318       unsigned int addr_size = cu->header.addr_size;
10319       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10320
10321       /* The base address, to which the next pair is relative.  Note
10322          that this 'base' is a DWARF concept: most entries in a range
10323          list are relative, to reduce the number of relocs against the
10324          debugging information.  This is separate from this function's
10325          'baseaddr' argument, which GDB uses to relocate debugging
10326          information from a shared library based on the address at
10327          which the library was loaded.  */
10328       CORE_ADDR base = cu->base_address;
10329       int base_known = cu->base_known;
10330
10331       gdb_assert (dwarf2_per_objfile->ranges.readin);
10332       if (offset >= dwarf2_per_objfile->ranges.size)
10333         {
10334           complaint (&symfile_complaints,
10335                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10336                      offset);
10337           return;
10338         }
10339
10340       for (;;)
10341         {
10342           unsigned int bytes_read;
10343           CORE_ADDR start, end;
10344
10345           start = read_address (obfd, buffer, cu, &bytes_read);
10346           buffer += bytes_read;
10347           end = read_address (obfd, buffer, cu, &bytes_read);
10348           buffer += bytes_read;
10349
10350           /* Did we find the end of the range list?  */
10351           if (start == 0 && end == 0)
10352             break;
10353
10354           /* Did we find a base address selection entry?  */
10355           else if ((start & base_select_mask) == base_select_mask)
10356             {
10357               base = end;
10358               base_known = 1;
10359             }
10360
10361           /* We found an ordinary address range.  */
10362           else
10363             {
10364               if (!base_known)
10365                 {
10366                   complaint (&symfile_complaints,
10367                              _("Invalid .debug_ranges data "
10368                                "(no base address)"));
10369                   return;
10370                 }
10371
10372               if (start > end)
10373                 {
10374                   /* Inverted range entries are invalid.  */
10375                   complaint (&symfile_complaints,
10376                              _("Invalid .debug_ranges data "
10377                                "(inverted range)"));
10378                   return;
10379                 }
10380
10381               /* Empty range entries have no effect.  */
10382               if (start == end)
10383                 continue;
10384
10385               start += base + baseaddr;
10386               end += base + baseaddr;
10387
10388               /* A not-uncommon case of bad debug info.
10389                  Don't pollute the addrmap with bad data.  */
10390               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10391                 {
10392                   complaint (&symfile_complaints,
10393                              _(".debug_ranges entry has start address of zero"
10394                                " [in module %s]"), objfile->name);
10395                   continue;
10396                 }
10397
10398               record_block_range (block, start, end - 1);
10399             }
10400         }
10401     }
10402 }
10403
10404 /* Check whether the producer field indicates either of GCC < 4.6, or the
10405    Intel C/C++ compiler, and cache the result in CU.  */
10406
10407 static void
10408 check_producer (struct dwarf2_cu *cu)
10409 {
10410   const char *cs;
10411   int major, minor, release;
10412
10413   if (cu->producer == NULL)
10414     {
10415       /* For unknown compilers expect their behavior is DWARF version
10416          compliant.
10417
10418          GCC started to support .debug_types sections by -gdwarf-4 since
10419          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10420          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10421          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10422          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10423     }
10424   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10425     {
10426       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10427
10428       cs = &cu->producer[strlen ("GNU ")];
10429       while (*cs && !isdigit (*cs))
10430         cs++;
10431       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10432         {
10433           /* Not recognized as GCC.  */
10434         }
10435       else
10436         {
10437           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10438           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10439         }
10440     }
10441   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10442     cu->producer_is_icc = 1;
10443   else
10444     {
10445       /* For other non-GCC compilers, expect their behavior is DWARF version
10446          compliant.  */
10447     }
10448
10449   cu->checked_producer = 1;
10450 }
10451
10452 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10453    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10454    during 4.6.0 experimental.  */
10455
10456 static int
10457 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10458 {
10459   if (!cu->checked_producer)
10460     check_producer (cu);
10461
10462   return cu->producer_is_gxx_lt_4_6;
10463 }
10464
10465 /* Return the default accessibility type if it is not overriden by
10466    DW_AT_accessibility.  */
10467
10468 static enum dwarf_access_attribute
10469 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10470 {
10471   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10472     {
10473       /* The default DWARF 2 accessibility for members is public, the default
10474          accessibility for inheritance is private.  */
10475
10476       if (die->tag != DW_TAG_inheritance)
10477         return DW_ACCESS_public;
10478       else
10479         return DW_ACCESS_private;
10480     }
10481   else
10482     {
10483       /* DWARF 3+ defines the default accessibility a different way.  The same
10484          rules apply now for DW_TAG_inheritance as for the members and it only
10485          depends on the container kind.  */
10486
10487       if (die->parent->tag == DW_TAG_class_type)
10488         return DW_ACCESS_private;
10489       else
10490         return DW_ACCESS_public;
10491     }
10492 }
10493
10494 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10495    offset.  If the attribute was not found return 0, otherwise return
10496    1.  If it was found but could not properly be handled, set *OFFSET
10497    to 0.  */
10498
10499 static int
10500 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10501                              LONGEST *offset)
10502 {
10503   struct attribute *attr;
10504
10505   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10506   if (attr != NULL)
10507     {
10508       *offset = 0;
10509
10510       /* Note that we do not check for a section offset first here.
10511          This is because DW_AT_data_member_location is new in DWARF 4,
10512          so if we see it, we can assume that a constant form is really
10513          a constant and not a section offset.  */
10514       if (attr_form_is_constant (attr))
10515         *offset = dwarf2_get_attr_constant_value (attr, 0);
10516       else if (attr_form_is_section_offset (attr))
10517         dwarf2_complex_location_expr_complaint ();
10518       else if (attr_form_is_block (attr))
10519         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10520       else
10521         dwarf2_complex_location_expr_complaint ();
10522
10523       return 1;
10524     }
10525
10526   return 0;
10527 }
10528
10529 /* Add an aggregate field to the field list.  */
10530
10531 static void
10532 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10533                   struct dwarf2_cu *cu)
10534 {
10535   struct objfile *objfile = cu->objfile;
10536   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10537   struct nextfield *new_field;
10538   struct attribute *attr;
10539   struct field *fp;
10540   const char *fieldname = "";
10541
10542   /* Allocate a new field list entry and link it in.  */
10543   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10544   make_cleanup (xfree, new_field);
10545   memset (new_field, 0, sizeof (struct nextfield));
10546
10547   if (die->tag == DW_TAG_inheritance)
10548     {
10549       new_field->next = fip->baseclasses;
10550       fip->baseclasses = new_field;
10551     }
10552   else
10553     {
10554       new_field->next = fip->fields;
10555       fip->fields = new_field;
10556     }
10557   fip->nfields++;
10558
10559   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10560   if (attr)
10561     new_field->accessibility = DW_UNSND (attr);
10562   else
10563     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10564   if (new_field->accessibility != DW_ACCESS_public)
10565     fip->non_public_fields = 1;
10566
10567   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10568   if (attr)
10569     new_field->virtuality = DW_UNSND (attr);
10570   else
10571     new_field->virtuality = DW_VIRTUALITY_none;
10572
10573   fp = &new_field->field;
10574
10575   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10576     {
10577       LONGEST offset;
10578
10579       /* Data member other than a C++ static data member.  */
10580
10581       /* Get type of field.  */
10582       fp->type = die_type (die, cu);
10583
10584       SET_FIELD_BITPOS (*fp, 0);
10585
10586       /* Get bit size of field (zero if none).  */
10587       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10588       if (attr)
10589         {
10590           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10591         }
10592       else
10593         {
10594           FIELD_BITSIZE (*fp) = 0;
10595         }
10596
10597       /* Get bit offset of field.  */
10598       if (handle_data_member_location (die, cu, &offset))
10599         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10600       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10601       if (attr)
10602         {
10603           if (gdbarch_bits_big_endian (gdbarch))
10604             {
10605               /* For big endian bits, the DW_AT_bit_offset gives the
10606                  additional bit offset from the MSB of the containing
10607                  anonymous object to the MSB of the field.  We don't
10608                  have to do anything special since we don't need to
10609                  know the size of the anonymous object.  */
10610               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10611             }
10612           else
10613             {
10614               /* For little endian bits, compute the bit offset to the
10615                  MSB of the anonymous object, subtract off the number of
10616                  bits from the MSB of the field to the MSB of the
10617                  object, and then subtract off the number of bits of
10618                  the field itself.  The result is the bit offset of
10619                  the LSB of the field.  */
10620               int anonymous_size;
10621               int bit_offset = DW_UNSND (attr);
10622
10623               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10624               if (attr)
10625                 {
10626                   /* The size of the anonymous object containing
10627                      the bit field is explicit, so use the
10628                      indicated size (in bytes).  */
10629                   anonymous_size = DW_UNSND (attr);
10630                 }
10631               else
10632                 {
10633                   /* The size of the anonymous object containing
10634                      the bit field must be inferred from the type
10635                      attribute of the data member containing the
10636                      bit field.  */
10637                   anonymous_size = TYPE_LENGTH (fp->type);
10638                 }
10639               SET_FIELD_BITPOS (*fp,
10640                                 (FIELD_BITPOS (*fp)
10641                                  + anonymous_size * bits_per_byte
10642                                  - bit_offset - FIELD_BITSIZE (*fp)));
10643             }
10644         }
10645
10646       /* Get name of field.  */
10647       fieldname = dwarf2_name (die, cu);
10648       if (fieldname == NULL)
10649         fieldname = "";
10650
10651       /* The name is already allocated along with this objfile, so we don't
10652          need to duplicate it for the type.  */
10653       fp->name = fieldname;
10654
10655       /* Change accessibility for artificial fields (e.g. virtual table
10656          pointer or virtual base class pointer) to private.  */
10657       if (dwarf2_attr (die, DW_AT_artificial, cu))
10658         {
10659           FIELD_ARTIFICIAL (*fp) = 1;
10660           new_field->accessibility = DW_ACCESS_private;
10661           fip->non_public_fields = 1;
10662         }
10663     }
10664   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10665     {
10666       /* C++ static member.  */
10667
10668       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10669          is a declaration, but all versions of G++ as of this writing
10670          (so through at least 3.2.1) incorrectly generate
10671          DW_TAG_variable tags.  */
10672
10673       const char *physname;
10674
10675       /* Get name of field.  */
10676       fieldname = dwarf2_name (die, cu);
10677       if (fieldname == NULL)
10678         return;
10679
10680       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10681       if (attr
10682           /* Only create a symbol if this is an external value.
10683              new_symbol checks this and puts the value in the global symbol
10684              table, which we want.  If it is not external, new_symbol
10685              will try to put the value in cu->list_in_scope which is wrong.  */
10686           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10687         {
10688           /* A static const member, not much different than an enum as far as
10689              we're concerned, except that we can support more types.  */
10690           new_symbol (die, NULL, cu);
10691         }
10692
10693       /* Get physical name.  */
10694       physname = dwarf2_physname (fieldname, die, cu);
10695
10696       /* The name is already allocated along with this objfile, so we don't
10697          need to duplicate it for the type.  */
10698       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10699       FIELD_TYPE (*fp) = die_type (die, cu);
10700       FIELD_NAME (*fp) = fieldname;
10701     }
10702   else if (die->tag == DW_TAG_inheritance)
10703     {
10704       LONGEST offset;
10705
10706       /* C++ base class field.  */
10707       if (handle_data_member_location (die, cu, &offset))
10708         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10709       FIELD_BITSIZE (*fp) = 0;
10710       FIELD_TYPE (*fp) = die_type (die, cu);
10711       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10712       fip->nbaseclasses++;
10713     }
10714 }
10715
10716 /* Add a typedef defined in the scope of the FIP's class.  */
10717
10718 static void
10719 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10720                     struct dwarf2_cu *cu)
10721 {
10722   struct objfile *objfile = cu->objfile;
10723   struct typedef_field_list *new_field;
10724   struct attribute *attr;
10725   struct typedef_field *fp;
10726   char *fieldname = "";
10727
10728   /* Allocate a new field list entry and link it in.  */
10729   new_field = xzalloc (sizeof (*new_field));
10730   make_cleanup (xfree, new_field);
10731
10732   gdb_assert (die->tag == DW_TAG_typedef);
10733
10734   fp = &new_field->field;
10735
10736   /* Get name of field.  */
10737   fp->name = dwarf2_name (die, cu);
10738   if (fp->name == NULL)
10739     return;
10740
10741   fp->type = read_type_die (die, cu);
10742
10743   new_field->next = fip->typedef_field_list;
10744   fip->typedef_field_list = new_field;
10745   fip->typedef_field_list_count++;
10746 }
10747
10748 /* Create the vector of fields, and attach it to the type.  */
10749
10750 static void
10751 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10752                               struct dwarf2_cu *cu)
10753 {
10754   int nfields = fip->nfields;
10755
10756   /* Record the field count, allocate space for the array of fields,
10757      and create blank accessibility bitfields if necessary.  */
10758   TYPE_NFIELDS (type) = nfields;
10759   TYPE_FIELDS (type) = (struct field *)
10760     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10761   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10762
10763   if (fip->non_public_fields && cu->language != language_ada)
10764     {
10765       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10766
10767       TYPE_FIELD_PRIVATE_BITS (type) =
10768         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10769       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10770
10771       TYPE_FIELD_PROTECTED_BITS (type) =
10772         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10773       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10774
10775       TYPE_FIELD_IGNORE_BITS (type) =
10776         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10777       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10778     }
10779
10780   /* If the type has baseclasses, allocate and clear a bit vector for
10781      TYPE_FIELD_VIRTUAL_BITS.  */
10782   if (fip->nbaseclasses && cu->language != language_ada)
10783     {
10784       int num_bytes = B_BYTES (fip->nbaseclasses);
10785       unsigned char *pointer;
10786
10787       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10788       pointer = TYPE_ALLOC (type, num_bytes);
10789       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10790       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10791       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10792     }
10793
10794   /* Copy the saved-up fields into the field vector.  Start from the head of
10795      the list, adding to the tail of the field array, so that they end up in
10796      the same order in the array in which they were added to the list.  */
10797   while (nfields-- > 0)
10798     {
10799       struct nextfield *fieldp;
10800
10801       if (fip->fields)
10802         {
10803           fieldp = fip->fields;
10804           fip->fields = fieldp->next;
10805         }
10806       else
10807         {
10808           fieldp = fip->baseclasses;
10809           fip->baseclasses = fieldp->next;
10810         }
10811
10812       TYPE_FIELD (type, nfields) = fieldp->field;
10813       switch (fieldp->accessibility)
10814         {
10815         case DW_ACCESS_private:
10816           if (cu->language != language_ada)
10817             SET_TYPE_FIELD_PRIVATE (type, nfields);
10818           break;
10819
10820         case DW_ACCESS_protected:
10821           if (cu->language != language_ada)
10822             SET_TYPE_FIELD_PROTECTED (type, nfields);
10823           break;
10824
10825         case DW_ACCESS_public:
10826           break;
10827
10828         default:
10829           /* Unknown accessibility.  Complain and treat it as public.  */
10830           {
10831             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10832                        fieldp->accessibility);
10833           }
10834           break;
10835         }
10836       if (nfields < fip->nbaseclasses)
10837         {
10838           switch (fieldp->virtuality)
10839             {
10840             case DW_VIRTUALITY_virtual:
10841             case DW_VIRTUALITY_pure_virtual:
10842               if (cu->language == language_ada)
10843                 error (_("unexpected virtuality in component of Ada type"));
10844               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10845               break;
10846             }
10847         }
10848     }
10849 }
10850
10851 /* Return true if this member function is a constructor, false
10852    otherwise.  */
10853
10854 static int
10855 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
10856 {
10857   const char *fieldname;
10858   const char *typename;
10859   int len;
10860
10861   if (die->parent == NULL)
10862     return 0;
10863
10864   if (die->parent->tag != DW_TAG_structure_type
10865       && die->parent->tag != DW_TAG_union_type
10866       && die->parent->tag != DW_TAG_class_type)
10867     return 0;
10868
10869   fieldname = dwarf2_name (die, cu);
10870   typename = dwarf2_name (die->parent, cu);
10871   if (fieldname == NULL || typename == NULL)
10872     return 0;
10873
10874   len = strlen (fieldname);
10875   return (strncmp (fieldname, typename, len) == 0
10876           && (typename[len] == '\0' || typename[len] == '<'));
10877 }
10878
10879 /* Add a member function to the proper fieldlist.  */
10880
10881 static void
10882 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
10883                       struct type *type, struct dwarf2_cu *cu)
10884 {
10885   struct objfile *objfile = cu->objfile;
10886   struct attribute *attr;
10887   struct fnfieldlist *flp;
10888   int i;
10889   struct fn_field *fnp;
10890   const char *fieldname;
10891   struct nextfnfield *new_fnfield;
10892   struct type *this_type;
10893   enum dwarf_access_attribute accessibility;
10894
10895   if (cu->language == language_ada)
10896     error (_("unexpected member function in Ada type"));
10897
10898   /* Get name of member function.  */
10899   fieldname = dwarf2_name (die, cu);
10900   if (fieldname == NULL)
10901     return;
10902
10903   /* Look up member function name in fieldlist.  */
10904   for (i = 0; i < fip->nfnfields; i++)
10905     {
10906       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
10907         break;
10908     }
10909
10910   /* Create new list element if necessary.  */
10911   if (i < fip->nfnfields)
10912     flp = &fip->fnfieldlists[i];
10913   else
10914     {
10915       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
10916         {
10917           fip->fnfieldlists = (struct fnfieldlist *)
10918             xrealloc (fip->fnfieldlists,
10919                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
10920                       * sizeof (struct fnfieldlist));
10921           if (fip->nfnfields == 0)
10922             make_cleanup (free_current_contents, &fip->fnfieldlists);
10923         }
10924       flp = &fip->fnfieldlists[fip->nfnfields];
10925       flp->name = fieldname;
10926       flp->length = 0;
10927       flp->head = NULL;
10928       i = fip->nfnfields++;
10929     }
10930
10931   /* Create a new member function field and chain it to the field list
10932      entry.  */
10933   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
10934   make_cleanup (xfree, new_fnfield);
10935   memset (new_fnfield, 0, sizeof (struct nextfnfield));
10936   new_fnfield->next = flp->head;
10937   flp->head = new_fnfield;
10938   flp->length++;
10939
10940   /* Fill in the member function field info.  */
10941   fnp = &new_fnfield->fnfield;
10942
10943   /* Delay processing of the physname until later.  */
10944   if (cu->language == language_cplus || cu->language == language_java)
10945     {
10946       add_to_method_list (type, i, flp->length - 1, fieldname,
10947                           die, cu);
10948     }
10949   else
10950     {
10951       const char *physname = dwarf2_physname (fieldname, die, cu);
10952       fnp->physname = physname ? physname : "";
10953     }
10954
10955   fnp->type = alloc_type (objfile);
10956   this_type = read_type_die (die, cu);
10957   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
10958     {
10959       int nparams = TYPE_NFIELDS (this_type);
10960
10961       /* TYPE is the domain of this method, and THIS_TYPE is the type
10962            of the method itself (TYPE_CODE_METHOD).  */
10963       smash_to_method_type (fnp->type, type,
10964                             TYPE_TARGET_TYPE (this_type),
10965                             TYPE_FIELDS (this_type),
10966                             TYPE_NFIELDS (this_type),
10967                             TYPE_VARARGS (this_type));
10968
10969       /* Handle static member functions.
10970          Dwarf2 has no clean way to discern C++ static and non-static
10971          member functions.  G++ helps GDB by marking the first
10972          parameter for non-static member functions (which is the this
10973          pointer) as artificial.  We obtain this information from
10974          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
10975       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
10976         fnp->voffset = VOFFSET_STATIC;
10977     }
10978   else
10979     complaint (&symfile_complaints, _("member function type missing for '%s'"),
10980                dwarf2_full_name (fieldname, die, cu));
10981
10982   /* Get fcontext from DW_AT_containing_type if present.  */
10983   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10984     fnp->fcontext = die_containing_type (die, cu);
10985
10986   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
10987      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
10988
10989   /* Get accessibility.  */
10990   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10991   if (attr)
10992     accessibility = DW_UNSND (attr);
10993   else
10994     accessibility = dwarf2_default_access_attribute (die, cu);
10995   switch (accessibility)
10996     {
10997     case DW_ACCESS_private:
10998       fnp->is_private = 1;
10999       break;
11000     case DW_ACCESS_protected:
11001       fnp->is_protected = 1;
11002       break;
11003     }
11004
11005   /* Check for artificial methods.  */
11006   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11007   if (attr && DW_UNSND (attr) != 0)
11008     fnp->is_artificial = 1;
11009
11010   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11011
11012   /* Get index in virtual function table if it is a virtual member
11013      function.  For older versions of GCC, this is an offset in the
11014      appropriate virtual table, as specified by DW_AT_containing_type.
11015      For everyone else, it is an expression to be evaluated relative
11016      to the object address.  */
11017
11018   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11019   if (attr)
11020     {
11021       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11022         {
11023           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11024             {
11025               /* Old-style GCC.  */
11026               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11027             }
11028           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11029                    || (DW_BLOCK (attr)->size > 1
11030                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11031                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11032             {
11033               struct dwarf_block blk;
11034               int offset;
11035
11036               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11037                         ? 1 : 2);
11038               blk.size = DW_BLOCK (attr)->size - offset;
11039               blk.data = DW_BLOCK (attr)->data + offset;
11040               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11041               if ((fnp->voffset % cu->header.addr_size) != 0)
11042                 dwarf2_complex_location_expr_complaint ();
11043               else
11044                 fnp->voffset /= cu->header.addr_size;
11045               fnp->voffset += 2;
11046             }
11047           else
11048             dwarf2_complex_location_expr_complaint ();
11049
11050           if (!fnp->fcontext)
11051             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11052         }
11053       else if (attr_form_is_section_offset (attr))
11054         {
11055           dwarf2_complex_location_expr_complaint ();
11056         }
11057       else
11058         {
11059           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11060                                                  fieldname);
11061         }
11062     }
11063   else
11064     {
11065       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11066       if (attr && DW_UNSND (attr))
11067         {
11068           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11069           complaint (&symfile_complaints,
11070                      _("Member function \"%s\" (offset %d) is virtual "
11071                        "but the vtable offset is not specified"),
11072                      fieldname, die->offset.sect_off);
11073           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11074           TYPE_CPLUS_DYNAMIC (type) = 1;
11075         }
11076     }
11077 }
11078
11079 /* Create the vector of member function fields, and attach it to the type.  */
11080
11081 static void
11082 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11083                                  struct dwarf2_cu *cu)
11084 {
11085   struct fnfieldlist *flp;
11086   int i;
11087
11088   if (cu->language == language_ada)
11089     error (_("unexpected member functions in Ada type"));
11090
11091   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11092   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11093     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11094
11095   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11096     {
11097       struct nextfnfield *nfp = flp->head;
11098       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11099       int k;
11100
11101       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11102       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11103       fn_flp->fn_fields = (struct fn_field *)
11104         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11105       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11106         fn_flp->fn_fields[k] = nfp->fnfield;
11107     }
11108
11109   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11110 }
11111
11112 /* Returns non-zero if NAME is the name of a vtable member in CU's
11113    language, zero otherwise.  */
11114 static int
11115 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11116 {
11117   static const char vptr[] = "_vptr";
11118   static const char vtable[] = "vtable";
11119
11120   /* Look for the C++ and Java forms of the vtable.  */
11121   if ((cu->language == language_java
11122        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11123        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11124        && is_cplus_marker (name[sizeof (vptr) - 1])))
11125     return 1;
11126
11127   return 0;
11128 }
11129
11130 /* GCC outputs unnamed structures that are really pointers to member
11131    functions, with the ABI-specified layout.  If TYPE describes
11132    such a structure, smash it into a member function type.
11133
11134    GCC shouldn't do this; it should just output pointer to member DIEs.
11135    This is GCC PR debug/28767.  */
11136
11137 static void
11138 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11139 {
11140   struct type *pfn_type, *domain_type, *new_type;
11141
11142   /* Check for a structure with no name and two children.  */
11143   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11144     return;
11145
11146   /* Check for __pfn and __delta members.  */
11147   if (TYPE_FIELD_NAME (type, 0) == NULL
11148       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11149       || TYPE_FIELD_NAME (type, 1) == NULL
11150       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11151     return;
11152
11153   /* Find the type of the method.  */
11154   pfn_type = TYPE_FIELD_TYPE (type, 0);
11155   if (pfn_type == NULL
11156       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11157       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11158     return;
11159
11160   /* Look for the "this" argument.  */
11161   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11162   if (TYPE_NFIELDS (pfn_type) == 0
11163       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11164       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11165     return;
11166
11167   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11168   new_type = alloc_type (objfile);
11169   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11170                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11171                         TYPE_VARARGS (pfn_type));
11172   smash_to_methodptr_type (type, new_type);
11173 }
11174
11175 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11176    (icc).  */
11177
11178 static int
11179 producer_is_icc (struct dwarf2_cu *cu)
11180 {
11181   if (!cu->checked_producer)
11182     check_producer (cu);
11183
11184   return cu->producer_is_icc;
11185 }
11186
11187 /* Called when we find the DIE that starts a structure or union scope
11188    (definition) to create a type for the structure or union.  Fill in
11189    the type's name and general properties; the members will not be
11190    processed until process_structure_type.
11191
11192    NOTE: we need to call these functions regardless of whether or not the
11193    DIE has a DW_AT_name attribute, since it might be an anonymous
11194    structure or union.  This gets the type entered into our set of
11195    user defined types.
11196
11197    However, if the structure is incomplete (an opaque struct/union)
11198    then suppress creating a symbol table entry for it since gdb only
11199    wants to find the one with the complete definition.  Note that if
11200    it is complete, we just call new_symbol, which does it's own
11201    checking about whether the struct/union is anonymous or not (and
11202    suppresses creating a symbol table entry itself).  */
11203
11204 static struct type *
11205 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11206 {
11207   struct objfile *objfile = cu->objfile;
11208   struct type *type;
11209   struct attribute *attr;
11210   const char *name;
11211
11212   /* If the definition of this type lives in .debug_types, read that type.
11213      Don't follow DW_AT_specification though, that will take us back up
11214      the chain and we want to go down.  */
11215   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11216   if (attr)
11217     {
11218       struct dwarf2_cu *type_cu = cu;
11219       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11220
11221       /* We could just recurse on read_structure_type, but we need to call
11222          get_die_type to ensure only one type for this DIE is created.
11223          This is important, for example, because for c++ classes we need
11224          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11225       type = read_type_die (type_die, type_cu);
11226
11227       /* TYPE_CU may not be the same as CU.
11228          Ensure TYPE is recorded in CU's type_hash table.  */
11229       return set_die_type (die, type, cu);
11230     }
11231
11232   type = alloc_type (objfile);
11233   INIT_CPLUS_SPECIFIC (type);
11234
11235   name = dwarf2_name (die, cu);
11236   if (name != NULL)
11237     {
11238       if (cu->language == language_cplus
11239           || cu->language == language_java)
11240         {
11241           const char *full_name = dwarf2_full_name (name, die, cu);
11242
11243           /* dwarf2_full_name might have already finished building the DIE's
11244              type.  If so, there is no need to continue.  */
11245           if (get_die_type (die, cu) != NULL)
11246             return get_die_type (die, cu);
11247
11248           TYPE_TAG_NAME (type) = full_name;
11249           if (die->tag == DW_TAG_structure_type
11250               || die->tag == DW_TAG_class_type)
11251             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11252         }
11253       else
11254         {
11255           /* The name is already allocated along with this objfile, so
11256              we don't need to duplicate it for the type.  */
11257           TYPE_TAG_NAME (type) = name;
11258           if (die->tag == DW_TAG_class_type)
11259             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11260         }
11261     }
11262
11263   if (die->tag == DW_TAG_structure_type)
11264     {
11265       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11266     }
11267   else if (die->tag == DW_TAG_union_type)
11268     {
11269       TYPE_CODE (type) = TYPE_CODE_UNION;
11270     }
11271   else
11272     {
11273       TYPE_CODE (type) = TYPE_CODE_CLASS;
11274     }
11275
11276   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11277     TYPE_DECLARED_CLASS (type) = 1;
11278
11279   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11280   if (attr)
11281     {
11282       TYPE_LENGTH (type) = DW_UNSND (attr);
11283     }
11284   else
11285     {
11286       TYPE_LENGTH (type) = 0;
11287     }
11288
11289   if (producer_is_icc (cu))
11290     {
11291       /* ICC does not output the required DW_AT_declaration
11292          on incomplete types, but gives them a size of zero.  */
11293     }
11294   else
11295     TYPE_STUB_SUPPORTED (type) = 1;
11296
11297   if (die_is_declaration (die, cu))
11298     TYPE_STUB (type) = 1;
11299   else if (attr == NULL && die->child == NULL
11300            && producer_is_realview (cu->producer))
11301     /* RealView does not output the required DW_AT_declaration
11302        on incomplete types.  */
11303     TYPE_STUB (type) = 1;
11304
11305   /* We need to add the type field to the die immediately so we don't
11306      infinitely recurse when dealing with pointers to the structure
11307      type within the structure itself.  */
11308   set_die_type (die, type, cu);
11309
11310   /* set_die_type should be already done.  */
11311   set_descriptive_type (type, die, cu);
11312
11313   return type;
11314 }
11315
11316 /* Finish creating a structure or union type, including filling in
11317    its members and creating a symbol for it.  */
11318
11319 static void
11320 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11321 {
11322   struct objfile *objfile = cu->objfile;
11323   struct die_info *child_die = die->child;
11324   struct type *type;
11325
11326   type = get_die_type (die, cu);
11327   if (type == NULL)
11328     type = read_structure_type (die, cu);
11329
11330   if (die->child != NULL && ! die_is_declaration (die, cu))
11331     {
11332       struct field_info fi;
11333       struct die_info *child_die;
11334       VEC (symbolp) *template_args = NULL;
11335       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11336
11337       memset (&fi, 0, sizeof (struct field_info));
11338
11339       child_die = die->child;
11340
11341       while (child_die && child_die->tag)
11342         {
11343           if (child_die->tag == DW_TAG_member
11344               || child_die->tag == DW_TAG_variable)
11345             {
11346               /* NOTE: carlton/2002-11-05: A C++ static data member
11347                  should be a DW_TAG_member that is a declaration, but
11348                  all versions of G++ as of this writing (so through at
11349                  least 3.2.1) incorrectly generate DW_TAG_variable
11350                  tags for them instead.  */
11351               dwarf2_add_field (&fi, child_die, cu);
11352             }
11353           else if (child_die->tag == DW_TAG_subprogram)
11354             {
11355               /* C++ member function.  */
11356               dwarf2_add_member_fn (&fi, child_die, type, cu);
11357             }
11358           else if (child_die->tag == DW_TAG_inheritance)
11359             {
11360               /* C++ base class field.  */
11361               dwarf2_add_field (&fi, child_die, cu);
11362             }
11363           else if (child_die->tag == DW_TAG_typedef)
11364             dwarf2_add_typedef (&fi, child_die, cu);
11365           else if (child_die->tag == DW_TAG_template_type_param
11366                    || child_die->tag == DW_TAG_template_value_param)
11367             {
11368               struct symbol *arg = new_symbol (child_die, NULL, cu);
11369
11370               if (arg != NULL)
11371                 VEC_safe_push (symbolp, template_args, arg);
11372             }
11373
11374           child_die = sibling_die (child_die);
11375         }
11376
11377       /* Attach template arguments to type.  */
11378       if (! VEC_empty (symbolp, template_args))
11379         {
11380           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11381           TYPE_N_TEMPLATE_ARGUMENTS (type)
11382             = VEC_length (symbolp, template_args);
11383           TYPE_TEMPLATE_ARGUMENTS (type)
11384             = obstack_alloc (&objfile->objfile_obstack,
11385                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11386                               * sizeof (struct symbol *)));
11387           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11388                   VEC_address (symbolp, template_args),
11389                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11390                    * sizeof (struct symbol *)));
11391           VEC_free (symbolp, template_args);
11392         }
11393
11394       /* Attach fields and member functions to the type.  */
11395       if (fi.nfields)
11396         dwarf2_attach_fields_to_type (&fi, type, cu);
11397       if (fi.nfnfields)
11398         {
11399           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11400
11401           /* Get the type which refers to the base class (possibly this
11402              class itself) which contains the vtable pointer for the current
11403              class from the DW_AT_containing_type attribute.  This use of
11404              DW_AT_containing_type is a GNU extension.  */
11405
11406           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11407             {
11408               struct type *t = die_containing_type (die, cu);
11409
11410               TYPE_VPTR_BASETYPE (type) = t;
11411               if (type == t)
11412                 {
11413                   int i;
11414
11415                   /* Our own class provides vtbl ptr.  */
11416                   for (i = TYPE_NFIELDS (t) - 1;
11417                        i >= TYPE_N_BASECLASSES (t);
11418                        --i)
11419                     {
11420                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11421
11422                       if (is_vtable_name (fieldname, cu))
11423                         {
11424                           TYPE_VPTR_FIELDNO (type) = i;
11425                           break;
11426                         }
11427                     }
11428
11429                   /* Complain if virtual function table field not found.  */
11430                   if (i < TYPE_N_BASECLASSES (t))
11431                     complaint (&symfile_complaints,
11432                                _("virtual function table pointer "
11433                                  "not found when defining class '%s'"),
11434                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11435                                "");
11436                 }
11437               else
11438                 {
11439                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11440                 }
11441             }
11442           else if (cu->producer
11443                    && strncmp (cu->producer,
11444                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11445             {
11446               /* The IBM XLC compiler does not provide direct indication
11447                  of the containing type, but the vtable pointer is
11448                  always named __vfp.  */
11449
11450               int i;
11451
11452               for (i = TYPE_NFIELDS (type) - 1;
11453                    i >= TYPE_N_BASECLASSES (type);
11454                    --i)
11455                 {
11456                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11457                     {
11458                       TYPE_VPTR_FIELDNO (type) = i;
11459                       TYPE_VPTR_BASETYPE (type) = type;
11460                       break;
11461                     }
11462                 }
11463             }
11464         }
11465
11466       /* Copy fi.typedef_field_list linked list elements content into the
11467          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11468       if (fi.typedef_field_list)
11469         {
11470           int i = fi.typedef_field_list_count;
11471
11472           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11473           TYPE_TYPEDEF_FIELD_ARRAY (type)
11474             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11475           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11476
11477           /* Reverse the list order to keep the debug info elements order.  */
11478           while (--i >= 0)
11479             {
11480               struct typedef_field *dest, *src;
11481
11482               dest = &TYPE_TYPEDEF_FIELD (type, i);
11483               src = &fi.typedef_field_list->field;
11484               fi.typedef_field_list = fi.typedef_field_list->next;
11485               *dest = *src;
11486             }
11487         }
11488
11489       do_cleanups (back_to);
11490
11491       if (HAVE_CPLUS_STRUCT (type))
11492         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11493     }
11494
11495   quirk_gcc_member_function_pointer (type, objfile);
11496
11497   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11498      snapshots) has been known to create a die giving a declaration
11499      for a class that has, as a child, a die giving a definition for a
11500      nested class.  So we have to process our children even if the
11501      current die is a declaration.  Normally, of course, a declaration
11502      won't have any children at all.  */
11503
11504   while (child_die != NULL && child_die->tag)
11505     {
11506       if (child_die->tag == DW_TAG_member
11507           || child_die->tag == DW_TAG_variable
11508           || child_die->tag == DW_TAG_inheritance
11509           || child_die->tag == DW_TAG_template_value_param
11510           || child_die->tag == DW_TAG_template_type_param)
11511         {
11512           /* Do nothing.  */
11513         }
11514       else
11515         process_die (child_die, cu);
11516
11517       child_die = sibling_die (child_die);
11518     }
11519
11520   /* Do not consider external references.  According to the DWARF standard,
11521      these DIEs are identified by the fact that they have no byte_size
11522      attribute, and a declaration attribute.  */
11523   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11524       || !die_is_declaration (die, cu))
11525     new_symbol (die, type, cu);
11526 }
11527
11528 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11529    complete the type's fields yet, or create any symbols.  */
11530
11531 static struct type *
11532 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11533 {
11534   struct objfile *objfile = cu->objfile;
11535   struct type *type;
11536   struct attribute *attr;
11537   const char *name;
11538
11539   /* If the definition of this type lives in .debug_types, read that type.
11540      Don't follow DW_AT_specification though, that will take us back up
11541      the chain and we want to go down.  */
11542   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11543   if (attr)
11544     {
11545       struct dwarf2_cu *type_cu = cu;
11546       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11547
11548       type = read_type_die (type_die, type_cu);
11549
11550       /* TYPE_CU may not be the same as CU.
11551          Ensure TYPE is recorded in CU's type_hash table.  */
11552       return set_die_type (die, type, cu);
11553     }
11554
11555   type = alloc_type (objfile);
11556
11557   TYPE_CODE (type) = TYPE_CODE_ENUM;
11558   name = dwarf2_full_name (NULL, die, cu);
11559   if (name != NULL)
11560     TYPE_TAG_NAME (type) = name;
11561
11562   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11563   if (attr)
11564     {
11565       TYPE_LENGTH (type) = DW_UNSND (attr);
11566     }
11567   else
11568     {
11569       TYPE_LENGTH (type) = 0;
11570     }
11571
11572   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11573      declared as private in the package spec, and then defined only
11574      inside the package body.  Such types are known as Taft Amendment
11575      Types.  When another package uses such a type, an incomplete DIE
11576      may be generated by the compiler.  */
11577   if (die_is_declaration (die, cu))
11578     TYPE_STUB (type) = 1;
11579
11580   return set_die_type (die, type, cu);
11581 }
11582
11583 /* Given a pointer to a die which begins an enumeration, process all
11584    the dies that define the members of the enumeration, and create the
11585    symbol for the enumeration type.
11586
11587    NOTE: We reverse the order of the element list.  */
11588
11589 static void
11590 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11591 {
11592   struct type *this_type;
11593
11594   this_type = get_die_type (die, cu);
11595   if (this_type == NULL)
11596     this_type = read_enumeration_type (die, cu);
11597
11598   if (die->child != NULL)
11599     {
11600       struct die_info *child_die;
11601       struct symbol *sym;
11602       struct field *fields = NULL;
11603       int num_fields = 0;
11604       int unsigned_enum = 1;
11605       const char *name;
11606       int flag_enum = 1;
11607       ULONGEST mask = 0;
11608
11609       child_die = die->child;
11610       while (child_die && child_die->tag)
11611         {
11612           if (child_die->tag != DW_TAG_enumerator)
11613             {
11614               process_die (child_die, cu);
11615             }
11616           else
11617             {
11618               name = dwarf2_name (child_die, cu);
11619               if (name)
11620                 {
11621                   sym = new_symbol (child_die, this_type, cu);
11622                   if (SYMBOL_VALUE (sym) < 0)
11623                     {
11624                       unsigned_enum = 0;
11625                       flag_enum = 0;
11626                     }
11627                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11628                     flag_enum = 0;
11629                   else
11630                     mask |= SYMBOL_VALUE (sym);
11631
11632                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11633                     {
11634                       fields = (struct field *)
11635                         xrealloc (fields,
11636                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11637                                   * sizeof (struct field));
11638                     }
11639
11640                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11641                   FIELD_TYPE (fields[num_fields]) = NULL;
11642                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11643                   FIELD_BITSIZE (fields[num_fields]) = 0;
11644
11645                   num_fields++;
11646                 }
11647             }
11648
11649           child_die = sibling_die (child_die);
11650         }
11651
11652       if (num_fields)
11653         {
11654           TYPE_NFIELDS (this_type) = num_fields;
11655           TYPE_FIELDS (this_type) = (struct field *)
11656             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11657           memcpy (TYPE_FIELDS (this_type), fields,
11658                   sizeof (struct field) * num_fields);
11659           xfree (fields);
11660         }
11661       if (unsigned_enum)
11662         TYPE_UNSIGNED (this_type) = 1;
11663       if (flag_enum)
11664         TYPE_FLAG_ENUM (this_type) = 1;
11665     }
11666
11667   /* If we are reading an enum from a .debug_types unit, and the enum
11668      is a declaration, and the enum is not the signatured type in the
11669      unit, then we do not want to add a symbol for it.  Adding a
11670      symbol would in some cases obscure the true definition of the
11671      enum, giving users an incomplete type when the definition is
11672      actually available.  Note that we do not want to do this for all
11673      enums which are just declarations, because C++0x allows forward
11674      enum declarations.  */
11675   if (cu->per_cu->is_debug_types
11676       && die_is_declaration (die, cu))
11677     {
11678       struct signatured_type *sig_type;
11679
11680       sig_type
11681         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
11682                                             cu->per_cu->info_or_types_section,
11683                                             cu->per_cu->offset);
11684       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11685       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11686         return;
11687     }
11688
11689   new_symbol (die, this_type, cu);
11690 }
11691
11692 /* Extract all information from a DW_TAG_array_type DIE and put it in
11693    the DIE's type field.  For now, this only handles one dimensional
11694    arrays.  */
11695
11696 static struct type *
11697 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11698 {
11699   struct objfile *objfile = cu->objfile;
11700   struct die_info *child_die;
11701   struct type *type;
11702   struct type *element_type, *range_type, *index_type;
11703   struct type **range_types = NULL;
11704   struct attribute *attr;
11705   int ndim = 0;
11706   struct cleanup *back_to;
11707   const char *name;
11708
11709   element_type = die_type (die, cu);
11710
11711   /* The die_type call above may have already set the type for this DIE.  */
11712   type = get_die_type (die, cu);
11713   if (type)
11714     return type;
11715
11716   /* Irix 6.2 native cc creates array types without children for
11717      arrays with unspecified length.  */
11718   if (die->child == NULL)
11719     {
11720       index_type = objfile_type (objfile)->builtin_int;
11721       range_type = create_range_type (NULL, index_type, 0, -1);
11722       type = create_array_type (NULL, element_type, range_type);
11723       return set_die_type (die, type, cu);
11724     }
11725
11726   back_to = make_cleanup (null_cleanup, NULL);
11727   child_die = die->child;
11728   while (child_die && child_die->tag)
11729     {
11730       if (child_die->tag == DW_TAG_subrange_type)
11731         {
11732           struct type *child_type = read_type_die (child_die, cu);
11733
11734           if (child_type != NULL)
11735             {
11736               /* The range type was succesfully read.  Save it for the
11737                  array type creation.  */
11738               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11739                 {
11740                   range_types = (struct type **)
11741                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11742                               * sizeof (struct type *));
11743                   if (ndim == 0)
11744                     make_cleanup (free_current_contents, &range_types);
11745                 }
11746               range_types[ndim++] = child_type;
11747             }
11748         }
11749       child_die = sibling_die (child_die);
11750     }
11751
11752   /* Dwarf2 dimensions are output from left to right, create the
11753      necessary array types in backwards order.  */
11754
11755   type = element_type;
11756
11757   if (read_array_order (die, cu) == DW_ORD_col_major)
11758     {
11759       int i = 0;
11760
11761       while (i < ndim)
11762         type = create_array_type (NULL, type, range_types[i++]);
11763     }
11764   else
11765     {
11766       while (ndim-- > 0)
11767         type = create_array_type (NULL, type, range_types[ndim]);
11768     }
11769
11770   /* Understand Dwarf2 support for vector types (like they occur on
11771      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11772      array type.  This is not part of the Dwarf2/3 standard yet, but a
11773      custom vendor extension.  The main difference between a regular
11774      array and the vector variant is that vectors are passed by value
11775      to functions.  */
11776   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11777   if (attr)
11778     make_vector_type (type);
11779
11780   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11781      implementation may choose to implement triple vectors using this
11782      attribute.  */
11783   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11784   if (attr)
11785     {
11786       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11787         TYPE_LENGTH (type) = DW_UNSND (attr);
11788       else
11789         complaint (&symfile_complaints,
11790                    _("DW_AT_byte_size for array type smaller "
11791                      "than the total size of elements"));
11792     }
11793
11794   name = dwarf2_name (die, cu);
11795   if (name)
11796     TYPE_NAME (type) = name;
11797
11798   /* Install the type in the die.  */
11799   set_die_type (die, type, cu);
11800
11801   /* set_die_type should be already done.  */
11802   set_descriptive_type (type, die, cu);
11803
11804   do_cleanups (back_to);
11805
11806   return type;
11807 }
11808
11809 static enum dwarf_array_dim_ordering
11810 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11811 {
11812   struct attribute *attr;
11813
11814   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11815
11816   if (attr) return DW_SND (attr);
11817
11818   /* GNU F77 is a special case, as at 08/2004 array type info is the
11819      opposite order to the dwarf2 specification, but data is still
11820      laid out as per normal fortran.
11821
11822      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11823      version checking.  */
11824
11825   if (cu->language == language_fortran
11826       && cu->producer && strstr (cu->producer, "GNU F77"))
11827     {
11828       return DW_ORD_row_major;
11829     }
11830
11831   switch (cu->language_defn->la_array_ordering)
11832     {
11833     case array_column_major:
11834       return DW_ORD_col_major;
11835     case array_row_major:
11836     default:
11837       return DW_ORD_row_major;
11838     };
11839 }
11840
11841 /* Extract all information from a DW_TAG_set_type DIE and put it in
11842    the DIE's type field.  */
11843
11844 static struct type *
11845 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11846 {
11847   struct type *domain_type, *set_type;
11848   struct attribute *attr;
11849
11850   domain_type = die_type (die, cu);
11851
11852   /* The die_type call above may have already set the type for this DIE.  */
11853   set_type = get_die_type (die, cu);
11854   if (set_type)
11855     return set_type;
11856
11857   set_type = create_set_type (NULL, domain_type);
11858
11859   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11860   if (attr)
11861     TYPE_LENGTH (set_type) = DW_UNSND (attr);
11862
11863   return set_die_type (die, set_type, cu);
11864 }
11865
11866 /* A helper for read_common_block that creates a locexpr baton.
11867    SYM is the symbol which we are marking as computed.
11868    COMMON_DIE is the DIE for the common block.
11869    COMMON_LOC is the location expression attribute for the common
11870    block itself.
11871    MEMBER_LOC is the location expression attribute for the particular
11872    member of the common block that we are processing.
11873    CU is the CU from which the above come.  */
11874
11875 static void
11876 mark_common_block_symbol_computed (struct symbol *sym,
11877                                    struct die_info *common_die,
11878                                    struct attribute *common_loc,
11879                                    struct attribute *member_loc,
11880                                    struct dwarf2_cu *cu)
11881 {
11882   struct objfile *objfile = dwarf2_per_objfile->objfile;
11883   struct dwarf2_locexpr_baton *baton;
11884   gdb_byte *ptr;
11885   unsigned int cu_off;
11886   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
11887   LONGEST offset = 0;
11888
11889   gdb_assert (common_loc && member_loc);
11890   gdb_assert (attr_form_is_block (common_loc));
11891   gdb_assert (attr_form_is_block (member_loc)
11892               || attr_form_is_constant (member_loc));
11893
11894   baton = obstack_alloc (&objfile->objfile_obstack,
11895                          sizeof (struct dwarf2_locexpr_baton));
11896   baton->per_cu = cu->per_cu;
11897   gdb_assert (baton->per_cu);
11898
11899   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
11900
11901   if (attr_form_is_constant (member_loc))
11902     {
11903       offset = dwarf2_get_attr_constant_value (member_loc, 0);
11904       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
11905     }
11906   else
11907     baton->size += DW_BLOCK (member_loc)->size;
11908
11909   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
11910   baton->data = ptr;
11911
11912   *ptr++ = DW_OP_call4;
11913   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
11914   store_unsigned_integer (ptr, 4, byte_order, cu_off);
11915   ptr += 4;
11916
11917   if (attr_form_is_constant (member_loc))
11918     {
11919       *ptr++ = DW_OP_addr;
11920       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
11921       ptr += cu->header.addr_size;
11922     }
11923   else
11924     {
11925       /* We have to copy the data here, because DW_OP_call4 will only
11926          use a DW_AT_location attribute.  */
11927       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
11928       ptr += DW_BLOCK (member_loc)->size;
11929     }
11930
11931   *ptr++ = DW_OP_plus;
11932   gdb_assert (ptr - baton->data == baton->size);
11933
11934   SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
11935   SYMBOL_LOCATION_BATON (sym) = baton;
11936   SYMBOL_CLASS (sym) = LOC_COMPUTED;
11937 }
11938
11939 /* Create appropriate locally-scoped variables for all the
11940    DW_TAG_common_block entries.  Also create a struct common_block
11941    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
11942    is used to sepate the common blocks name namespace from regular
11943    variable names.  */
11944
11945 static void
11946 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
11947 {
11948   struct attribute *attr;
11949
11950   attr = dwarf2_attr (die, DW_AT_location, cu);
11951   if (attr)
11952     {
11953       /* Support the .debug_loc offsets.  */
11954       if (attr_form_is_block (attr))
11955         {
11956           /* Ok.  */
11957         }
11958       else if (attr_form_is_section_offset (attr))
11959         {
11960           dwarf2_complex_location_expr_complaint ();
11961           attr = NULL;
11962         }
11963       else
11964         {
11965           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11966                                                  "common block member");
11967           attr = NULL;
11968         }
11969     }
11970
11971   if (die->child != NULL)
11972     {
11973       struct objfile *objfile = cu->objfile;
11974       struct die_info *child_die;
11975       size_t n_entries = 0, size;
11976       struct common_block *common_block;
11977       struct symbol *sym;
11978
11979       for (child_die = die->child;
11980            child_die && child_die->tag;
11981            child_die = sibling_die (child_die))
11982         ++n_entries;
11983
11984       size = (sizeof (struct common_block)
11985               + (n_entries - 1) * sizeof (struct symbol *));
11986       common_block = obstack_alloc (&objfile->objfile_obstack, size);
11987       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
11988       common_block->n_entries = 0;
11989
11990       for (child_die = die->child;
11991            child_die && child_die->tag;
11992            child_die = sibling_die (child_die))
11993         {
11994           /* Create the symbol in the DW_TAG_common_block block in the current
11995              symbol scope.  */
11996           sym = new_symbol (child_die, NULL, cu);
11997           if (sym != NULL)
11998             {
11999               struct attribute *member_loc;
12000
12001               common_block->contents[common_block->n_entries++] = sym;
12002
12003               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12004                                         cu);
12005               if (member_loc)
12006                 {
12007                   /* GDB has handled this for a long time, but it is
12008                      not specified by DWARF.  It seems to have been
12009                      emitted by gfortran at least as recently as:
12010                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12011                   complaint (&symfile_complaints,
12012                              _("Variable in common block has "
12013                                "DW_AT_data_member_location "
12014                                "- DIE at 0x%x [in module %s]"),
12015                              child_die->offset.sect_off, cu->objfile->name);
12016
12017                   if (attr_form_is_section_offset (member_loc))
12018                     dwarf2_complex_location_expr_complaint ();
12019                   else if (attr_form_is_constant (member_loc)
12020                            || attr_form_is_block (member_loc))
12021                     {
12022                       if (attr)
12023                         mark_common_block_symbol_computed (sym, die, attr,
12024                                                            member_loc, cu);
12025                     }
12026                   else
12027                     dwarf2_complex_location_expr_complaint ();
12028                 }
12029             }
12030         }
12031
12032       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12033       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12034     }
12035 }
12036
12037 /* Create a type for a C++ namespace.  */
12038
12039 static struct type *
12040 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12041 {
12042   struct objfile *objfile = cu->objfile;
12043   const char *previous_prefix, *name;
12044   int is_anonymous;
12045   struct type *type;
12046
12047   /* For extensions, reuse the type of the original namespace.  */
12048   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12049     {
12050       struct die_info *ext_die;
12051       struct dwarf2_cu *ext_cu = cu;
12052
12053       ext_die = dwarf2_extension (die, &ext_cu);
12054       type = read_type_die (ext_die, ext_cu);
12055
12056       /* EXT_CU may not be the same as CU.
12057          Ensure TYPE is recorded in CU's type_hash table.  */
12058       return set_die_type (die, type, cu);
12059     }
12060
12061   name = namespace_name (die, &is_anonymous, cu);
12062
12063   /* Now build the name of the current namespace.  */
12064
12065   previous_prefix = determine_prefix (die, cu);
12066   if (previous_prefix[0] != '\0')
12067     name = typename_concat (&objfile->objfile_obstack,
12068                             previous_prefix, name, 0, cu);
12069
12070   /* Create the type.  */
12071   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12072                     objfile);
12073   TYPE_NAME (type) = name;
12074   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12075
12076   return set_die_type (die, type, cu);
12077 }
12078
12079 /* Read a C++ namespace.  */
12080
12081 static void
12082 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12083 {
12084   struct objfile *objfile = cu->objfile;
12085   int is_anonymous;
12086
12087   /* Add a symbol associated to this if we haven't seen the namespace
12088      before.  Also, add a using directive if it's an anonymous
12089      namespace.  */
12090
12091   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12092     {
12093       struct type *type;
12094
12095       type = read_type_die (die, cu);
12096       new_symbol (die, type, cu);
12097
12098       namespace_name (die, &is_anonymous, cu);
12099       if (is_anonymous)
12100         {
12101           const char *previous_prefix = determine_prefix (die, cu);
12102
12103           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12104                                   NULL, NULL, 0, &objfile->objfile_obstack);
12105         }
12106     }
12107
12108   if (die->child != NULL)
12109     {
12110       struct die_info *child_die = die->child;
12111
12112       while (child_die && child_die->tag)
12113         {
12114           process_die (child_die, cu);
12115           child_die = sibling_die (child_die);
12116         }
12117     }
12118 }
12119
12120 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12121    imported module.  Still we need that type as local Fortran "use ... only"
12122    declaration imports depend on the created type in determine_prefix.  */
12123
12124 static struct type *
12125 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12126 {
12127   struct objfile *objfile = cu->objfile;
12128   const char *module_name;
12129   struct type *type;
12130
12131   module_name = dwarf2_name (die, cu);
12132   if (!module_name)
12133     complaint (&symfile_complaints,
12134                _("DW_TAG_module has no name, offset 0x%x"),
12135                die->offset.sect_off);
12136   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12137
12138   /* determine_prefix uses TYPE_TAG_NAME.  */
12139   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12140
12141   return set_die_type (die, type, cu);
12142 }
12143
12144 /* Read a Fortran module.  */
12145
12146 static void
12147 read_module (struct die_info *die, struct dwarf2_cu *cu)
12148 {
12149   struct die_info *child_die = die->child;
12150
12151   while (child_die && child_die->tag)
12152     {
12153       process_die (child_die, cu);
12154       child_die = sibling_die (child_die);
12155     }
12156 }
12157
12158 /* Return the name of the namespace represented by DIE.  Set
12159    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12160    namespace.  */
12161
12162 static const char *
12163 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12164 {
12165   struct die_info *current_die;
12166   const char *name = NULL;
12167
12168   /* Loop through the extensions until we find a name.  */
12169
12170   for (current_die = die;
12171        current_die != NULL;
12172        current_die = dwarf2_extension (die, &cu))
12173     {
12174       name = dwarf2_name (current_die, cu);
12175       if (name != NULL)
12176         break;
12177     }
12178
12179   /* Is it an anonymous namespace?  */
12180
12181   *is_anonymous = (name == NULL);
12182   if (*is_anonymous)
12183     name = CP_ANONYMOUS_NAMESPACE_STR;
12184
12185   return name;
12186 }
12187
12188 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12189    the user defined type vector.  */
12190
12191 static struct type *
12192 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12193 {
12194   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12195   struct comp_unit_head *cu_header = &cu->header;
12196   struct type *type;
12197   struct attribute *attr_byte_size;
12198   struct attribute *attr_address_class;
12199   int byte_size, addr_class;
12200   struct type *target_type;
12201
12202   target_type = die_type (die, cu);
12203
12204   /* The die_type call above may have already set the type for this DIE.  */
12205   type = get_die_type (die, cu);
12206   if (type)
12207     return type;
12208
12209   type = lookup_pointer_type (target_type);
12210
12211   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12212   if (attr_byte_size)
12213     byte_size = DW_UNSND (attr_byte_size);
12214   else
12215     byte_size = cu_header->addr_size;
12216
12217   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12218   if (attr_address_class)
12219     addr_class = DW_UNSND (attr_address_class);
12220   else
12221     addr_class = DW_ADDR_none;
12222
12223   /* If the pointer size or address class is different than the
12224      default, create a type variant marked as such and set the
12225      length accordingly.  */
12226   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12227     {
12228       if (gdbarch_address_class_type_flags_p (gdbarch))
12229         {
12230           int type_flags;
12231
12232           type_flags = gdbarch_address_class_type_flags
12233                          (gdbarch, byte_size, addr_class);
12234           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12235                       == 0);
12236           type = make_type_with_address_space (type, type_flags);
12237         }
12238       else if (TYPE_LENGTH (type) != byte_size)
12239         {
12240           complaint (&symfile_complaints,
12241                      _("invalid pointer size %d"), byte_size);
12242         }
12243       else
12244         {
12245           /* Should we also complain about unhandled address classes?  */
12246         }
12247     }
12248
12249   TYPE_LENGTH (type) = byte_size;
12250   return set_die_type (die, type, cu);
12251 }
12252
12253 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12254    the user defined type vector.  */
12255
12256 static struct type *
12257 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12258 {
12259   struct type *type;
12260   struct type *to_type;
12261   struct type *domain;
12262
12263   to_type = die_type (die, cu);
12264   domain = die_containing_type (die, cu);
12265
12266   /* The calls above may have already set the type for this DIE.  */
12267   type = get_die_type (die, cu);
12268   if (type)
12269     return type;
12270
12271   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12272     type = lookup_methodptr_type (to_type);
12273   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12274     {
12275       struct type *new_type = alloc_type (cu->objfile);
12276
12277       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12278                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12279                             TYPE_VARARGS (to_type));
12280       type = lookup_methodptr_type (new_type);
12281     }
12282   else
12283     type = lookup_memberptr_type (to_type, domain);
12284
12285   return set_die_type (die, type, cu);
12286 }
12287
12288 /* Extract all information from a DW_TAG_reference_type DIE and add to
12289    the user defined type vector.  */
12290
12291 static struct type *
12292 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12293 {
12294   struct comp_unit_head *cu_header = &cu->header;
12295   struct type *type, *target_type;
12296   struct attribute *attr;
12297
12298   target_type = die_type (die, cu);
12299
12300   /* The die_type call above may have already set the type for this DIE.  */
12301   type = get_die_type (die, cu);
12302   if (type)
12303     return type;
12304
12305   type = lookup_reference_type (target_type);
12306   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12307   if (attr)
12308     {
12309       TYPE_LENGTH (type) = DW_UNSND (attr);
12310     }
12311   else
12312     {
12313       TYPE_LENGTH (type) = cu_header->addr_size;
12314     }
12315   return set_die_type (die, type, cu);
12316 }
12317
12318 static struct type *
12319 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12320 {
12321   struct type *base_type, *cv_type;
12322
12323   base_type = die_type (die, cu);
12324
12325   /* The die_type call above may have already set the type for this DIE.  */
12326   cv_type = get_die_type (die, cu);
12327   if (cv_type)
12328     return cv_type;
12329
12330   /* In case the const qualifier is applied to an array type, the element type
12331      is so qualified, not the array type (section 6.7.3 of C99).  */
12332   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12333     {
12334       struct type *el_type, *inner_array;
12335
12336       base_type = copy_type (base_type);
12337       inner_array = base_type;
12338
12339       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12340         {
12341           TYPE_TARGET_TYPE (inner_array) =
12342             copy_type (TYPE_TARGET_TYPE (inner_array));
12343           inner_array = TYPE_TARGET_TYPE (inner_array);
12344         }
12345
12346       el_type = TYPE_TARGET_TYPE (inner_array);
12347       TYPE_TARGET_TYPE (inner_array) =
12348         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12349
12350       return set_die_type (die, base_type, cu);
12351     }
12352
12353   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12354   return set_die_type (die, cv_type, cu);
12355 }
12356
12357 static struct type *
12358 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12359 {
12360   struct type *base_type, *cv_type;
12361
12362   base_type = die_type (die, cu);
12363
12364   /* The die_type call above may have already set the type for this DIE.  */
12365   cv_type = get_die_type (die, cu);
12366   if (cv_type)
12367     return cv_type;
12368
12369   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12370   return set_die_type (die, cv_type, cu);
12371 }
12372
12373 /* Handle DW_TAG_restrict_type.  */
12374
12375 static struct type *
12376 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12377 {
12378   struct type *base_type, *cv_type;
12379
12380   base_type = die_type (die, cu);
12381
12382   /* The die_type call above may have already set the type for this DIE.  */
12383   cv_type = get_die_type (die, cu);
12384   if (cv_type)
12385     return cv_type;
12386
12387   cv_type = make_restrict_type (base_type);
12388   return set_die_type (die, cv_type, cu);
12389 }
12390
12391 /* Extract all information from a DW_TAG_string_type DIE and add to
12392    the user defined type vector.  It isn't really a user defined type,
12393    but it behaves like one, with other DIE's using an AT_user_def_type
12394    attribute to reference it.  */
12395
12396 static struct type *
12397 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12398 {
12399   struct objfile *objfile = cu->objfile;
12400   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12401   struct type *type, *range_type, *index_type, *char_type;
12402   struct attribute *attr;
12403   unsigned int length;
12404
12405   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12406   if (attr)
12407     {
12408       length = DW_UNSND (attr);
12409     }
12410   else
12411     {
12412       /* Check for the DW_AT_byte_size attribute.  */
12413       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12414       if (attr)
12415         {
12416           length = DW_UNSND (attr);
12417         }
12418       else
12419         {
12420           length = 1;
12421         }
12422     }
12423
12424   index_type = objfile_type (objfile)->builtin_int;
12425   range_type = create_range_type (NULL, index_type, 1, length);
12426   char_type = language_string_char_type (cu->language_defn, gdbarch);
12427   type = create_string_type (NULL, char_type, range_type);
12428
12429   return set_die_type (die, type, cu);
12430 }
12431
12432 /* Handle DIES due to C code like:
12433
12434    struct foo
12435    {
12436    int (*funcp)(int a, long l);
12437    int b;
12438    };
12439
12440    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12441
12442 static struct type *
12443 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12444 {
12445   struct objfile *objfile = cu->objfile;
12446   struct type *type;            /* Type that this function returns.  */
12447   struct type *ftype;           /* Function that returns above type.  */
12448   struct attribute *attr;
12449
12450   type = die_type (die, cu);
12451
12452   /* The die_type call above may have already set the type for this DIE.  */
12453   ftype = get_die_type (die, cu);
12454   if (ftype)
12455     return ftype;
12456
12457   ftype = lookup_function_type (type);
12458
12459   /* All functions in C++, Pascal and Java have prototypes.  */
12460   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12461   if ((attr && (DW_UNSND (attr) != 0))
12462       || cu->language == language_cplus
12463       || cu->language == language_java
12464       || cu->language == language_pascal)
12465     TYPE_PROTOTYPED (ftype) = 1;
12466   else if (producer_is_realview (cu->producer))
12467     /* RealView does not emit DW_AT_prototyped.  We can not
12468        distinguish prototyped and unprototyped functions; default to
12469        prototyped, since that is more common in modern code (and
12470        RealView warns about unprototyped functions).  */
12471     TYPE_PROTOTYPED (ftype) = 1;
12472
12473   /* Store the calling convention in the type if it's available in
12474      the subroutine die.  Otherwise set the calling convention to
12475      the default value DW_CC_normal.  */
12476   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12477   if (attr)
12478     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12479   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12480     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12481   else
12482     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12483
12484   /* We need to add the subroutine type to the die immediately so
12485      we don't infinitely recurse when dealing with parameters
12486      declared as the same subroutine type.  */
12487   set_die_type (die, ftype, cu);
12488
12489   if (die->child != NULL)
12490     {
12491       struct type *void_type = objfile_type (objfile)->builtin_void;
12492       struct die_info *child_die;
12493       int nparams, iparams;
12494
12495       /* Count the number of parameters.
12496          FIXME: GDB currently ignores vararg functions, but knows about
12497          vararg member functions.  */
12498       nparams = 0;
12499       child_die = die->child;
12500       while (child_die && child_die->tag)
12501         {
12502           if (child_die->tag == DW_TAG_formal_parameter)
12503             nparams++;
12504           else if (child_die->tag == DW_TAG_unspecified_parameters)
12505             TYPE_VARARGS (ftype) = 1;
12506           child_die = sibling_die (child_die);
12507         }
12508
12509       /* Allocate storage for parameters and fill them in.  */
12510       TYPE_NFIELDS (ftype) = nparams;
12511       TYPE_FIELDS (ftype) = (struct field *)
12512         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12513
12514       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12515          even if we error out during the parameters reading below.  */
12516       for (iparams = 0; iparams < nparams; iparams++)
12517         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12518
12519       iparams = 0;
12520       child_die = die->child;
12521       while (child_die && child_die->tag)
12522         {
12523           if (child_die->tag == DW_TAG_formal_parameter)
12524             {
12525               struct type *arg_type;
12526
12527               /* DWARF version 2 has no clean way to discern C++
12528                  static and non-static member functions.  G++ helps
12529                  GDB by marking the first parameter for non-static
12530                  member functions (which is the this pointer) as
12531                  artificial.  We pass this information to
12532                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12533
12534                  DWARF version 3 added DW_AT_object_pointer, which GCC
12535                  4.5 does not yet generate.  */
12536               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12537               if (attr)
12538                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12539               else
12540                 {
12541                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12542
12543                   /* GCC/43521: In java, the formal parameter
12544                      "this" is sometimes not marked with DW_AT_artificial.  */
12545                   if (cu->language == language_java)
12546                     {
12547                       const char *name = dwarf2_name (child_die, cu);
12548
12549                       if (name && !strcmp (name, "this"))
12550                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12551                     }
12552                 }
12553               arg_type = die_type (child_die, cu);
12554
12555               /* RealView does not mark THIS as const, which the testsuite
12556                  expects.  GCC marks THIS as const in method definitions,
12557                  but not in the class specifications (GCC PR 43053).  */
12558               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12559                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12560                 {
12561                   int is_this = 0;
12562                   struct dwarf2_cu *arg_cu = cu;
12563                   const char *name = dwarf2_name (child_die, cu);
12564
12565                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12566                   if (attr)
12567                     {
12568                       /* If the compiler emits this, use it.  */
12569                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12570                         is_this = 1;
12571                     }
12572                   else if (name && strcmp (name, "this") == 0)
12573                     /* Function definitions will have the argument names.  */
12574                     is_this = 1;
12575                   else if (name == NULL && iparams == 0)
12576                     /* Declarations may not have the names, so like
12577                        elsewhere in GDB, assume an artificial first
12578                        argument is "this".  */
12579                     is_this = 1;
12580
12581                   if (is_this)
12582                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12583                                              arg_type, 0);
12584                 }
12585
12586               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12587               iparams++;
12588             }
12589           child_die = sibling_die (child_die);
12590         }
12591     }
12592
12593   return ftype;
12594 }
12595
12596 static struct type *
12597 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12598 {
12599   struct objfile *objfile = cu->objfile;
12600   const char *name = NULL;
12601   struct type *this_type, *target_type;
12602
12603   name = dwarf2_full_name (NULL, die, cu);
12604   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12605                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12606   TYPE_NAME (this_type) = name;
12607   set_die_type (die, this_type, cu);
12608   target_type = die_type (die, cu);
12609   if (target_type != this_type)
12610     TYPE_TARGET_TYPE (this_type) = target_type;
12611   else
12612     {
12613       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12614          spec and cause infinite loops in GDB.  */
12615       complaint (&symfile_complaints,
12616                  _("Self-referential DW_TAG_typedef "
12617                    "- DIE at 0x%x [in module %s]"),
12618                  die->offset.sect_off, objfile->name);
12619       TYPE_TARGET_TYPE (this_type) = NULL;
12620     }
12621   return this_type;
12622 }
12623
12624 /* Find a representation of a given base type and install
12625    it in the TYPE field of the die.  */
12626
12627 static struct type *
12628 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12629 {
12630   struct objfile *objfile = cu->objfile;
12631   struct type *type;
12632   struct attribute *attr;
12633   int encoding = 0, size = 0;
12634   const char *name;
12635   enum type_code code = TYPE_CODE_INT;
12636   int type_flags = 0;
12637   struct type *target_type = NULL;
12638
12639   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12640   if (attr)
12641     {
12642       encoding = DW_UNSND (attr);
12643     }
12644   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12645   if (attr)
12646     {
12647       size = DW_UNSND (attr);
12648     }
12649   name = dwarf2_name (die, cu);
12650   if (!name)
12651     {
12652       complaint (&symfile_complaints,
12653                  _("DW_AT_name missing from DW_TAG_base_type"));
12654     }
12655
12656   switch (encoding)
12657     {
12658       case DW_ATE_address:
12659         /* Turn DW_ATE_address into a void * pointer.  */
12660         code = TYPE_CODE_PTR;
12661         type_flags |= TYPE_FLAG_UNSIGNED;
12662         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12663         break;
12664       case DW_ATE_boolean:
12665         code = TYPE_CODE_BOOL;
12666         type_flags |= TYPE_FLAG_UNSIGNED;
12667         break;
12668       case DW_ATE_complex_float:
12669         code = TYPE_CODE_COMPLEX;
12670         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12671         break;
12672       case DW_ATE_decimal_float:
12673         code = TYPE_CODE_DECFLOAT;
12674         break;
12675       case DW_ATE_float:
12676         code = TYPE_CODE_FLT;
12677         break;
12678       case DW_ATE_signed:
12679         break;
12680       case DW_ATE_unsigned:
12681         type_flags |= TYPE_FLAG_UNSIGNED;
12682         if (cu->language == language_fortran
12683             && name
12684             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12685           code = TYPE_CODE_CHAR;
12686         break;
12687       case DW_ATE_signed_char:
12688         if (cu->language == language_ada || cu->language == language_m2
12689             || cu->language == language_pascal
12690             || cu->language == language_fortran)
12691           code = TYPE_CODE_CHAR;
12692         break;
12693       case DW_ATE_unsigned_char:
12694         if (cu->language == language_ada || cu->language == language_m2
12695             || cu->language == language_pascal
12696             || cu->language == language_fortran)
12697           code = TYPE_CODE_CHAR;
12698         type_flags |= TYPE_FLAG_UNSIGNED;
12699         break;
12700       case DW_ATE_UTF:
12701         /* We just treat this as an integer and then recognize the
12702            type by name elsewhere.  */
12703         break;
12704
12705       default:
12706         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12707                    dwarf_type_encoding_name (encoding));
12708         break;
12709     }
12710
12711   type = init_type (code, size, type_flags, NULL, objfile);
12712   TYPE_NAME (type) = name;
12713   TYPE_TARGET_TYPE (type) = target_type;
12714
12715   if (name && strcmp (name, "char") == 0)
12716     TYPE_NOSIGN (type) = 1;
12717
12718   return set_die_type (die, type, cu);
12719 }
12720
12721 /* Read the given DW_AT_subrange DIE.  */
12722
12723 static struct type *
12724 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12725 {
12726   struct type *base_type;
12727   struct type *range_type;
12728   struct attribute *attr;
12729   LONGEST low, high;
12730   int low_default_is_valid;
12731   const char *name;
12732   LONGEST negative_mask;
12733
12734   base_type = die_type (die, cu);
12735   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
12736   check_typedef (base_type);
12737
12738   /* The die_type call above may have already set the type for this DIE.  */
12739   range_type = get_die_type (die, cu);
12740   if (range_type)
12741     return range_type;
12742
12743   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12744      omitting DW_AT_lower_bound.  */
12745   switch (cu->language)
12746     {
12747     case language_c:
12748     case language_cplus:
12749       low = 0;
12750       low_default_is_valid = 1;
12751       break;
12752     case language_fortran:
12753       low = 1;
12754       low_default_is_valid = 1;
12755       break;
12756     case language_d:
12757     case language_java:
12758     case language_objc:
12759       low = 0;
12760       low_default_is_valid = (cu->header.version >= 4);
12761       break;
12762     case language_ada:
12763     case language_m2:
12764     case language_pascal:
12765       low = 1;
12766       low_default_is_valid = (cu->header.version >= 4);
12767       break;
12768     default:
12769       low = 0;
12770       low_default_is_valid = 0;
12771       break;
12772     }
12773
12774   /* FIXME: For variable sized arrays either of these could be
12775      a variable rather than a constant value.  We'll allow it,
12776      but we don't know how to handle it.  */
12777   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12778   if (attr)
12779     low = dwarf2_get_attr_constant_value (attr, low);
12780   else if (!low_default_is_valid)
12781     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12782                                       "- DIE at 0x%x [in module %s]"),
12783                die->offset.sect_off, cu->objfile->name);
12784
12785   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12786   if (attr)
12787     {
12788       if (attr_form_is_block (attr) || is_ref_attr (attr))
12789         {
12790           /* GCC encodes arrays with unspecified or dynamic length
12791              with a DW_FORM_block1 attribute or a reference attribute.
12792              FIXME: GDB does not yet know how to handle dynamic
12793              arrays properly, treat them as arrays with unspecified
12794              length for now.
12795
12796              FIXME: jimb/2003-09-22: GDB does not really know
12797              how to handle arrays of unspecified length
12798              either; we just represent them as zero-length
12799              arrays.  Choose an appropriate upper bound given
12800              the lower bound we've computed above.  */
12801           high = low - 1;
12802         }
12803       else
12804         high = dwarf2_get_attr_constant_value (attr, 1);
12805     }
12806   else
12807     {
12808       attr = dwarf2_attr (die, DW_AT_count, cu);
12809       if (attr)
12810         {
12811           int count = dwarf2_get_attr_constant_value (attr, 1);
12812           high = low + count - 1;
12813         }
12814       else
12815         {
12816           /* Unspecified array length.  */
12817           high = low - 1;
12818         }
12819     }
12820
12821   /* Dwarf-2 specifications explicitly allows to create subrange types
12822      without specifying a base type.
12823      In that case, the base type must be set to the type of
12824      the lower bound, upper bound or count, in that order, if any of these
12825      three attributes references an object that has a type.
12826      If no base type is found, the Dwarf-2 specifications say that
12827      a signed integer type of size equal to the size of an address should
12828      be used.
12829      For the following C code: `extern char gdb_int [];'
12830      GCC produces an empty range DIE.
12831      FIXME: muller/2010-05-28: Possible references to object for low bound,
12832      high bound or count are not yet handled by this code.  */
12833   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12834     {
12835       struct objfile *objfile = cu->objfile;
12836       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12837       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12838       struct type *int_type = objfile_type (objfile)->builtin_int;
12839
12840       /* Test "int", "long int", and "long long int" objfile types,
12841          and select the first one having a size above or equal to the
12842          architecture address size.  */
12843       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12844         base_type = int_type;
12845       else
12846         {
12847           int_type = objfile_type (objfile)->builtin_long;
12848           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12849             base_type = int_type;
12850           else
12851             {
12852               int_type = objfile_type (objfile)->builtin_long_long;
12853               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12854                 base_type = int_type;
12855             }
12856         }
12857     }
12858
12859   negative_mask =
12860     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
12861   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
12862     low |= negative_mask;
12863   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
12864     high |= negative_mask;
12865
12866   range_type = create_range_type (NULL, base_type, low, high);
12867
12868   /* Mark arrays with dynamic length at least as an array of unspecified
12869      length.  GDB could check the boundary but before it gets implemented at
12870      least allow accessing the array elements.  */
12871   if (attr && attr_form_is_block (attr))
12872     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12873
12874   /* Ada expects an empty array on no boundary attributes.  */
12875   if (attr == NULL && cu->language != language_ada)
12876     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12877
12878   name = dwarf2_name (die, cu);
12879   if (name)
12880     TYPE_NAME (range_type) = name;
12881
12882   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12883   if (attr)
12884     TYPE_LENGTH (range_type) = DW_UNSND (attr);
12885
12886   set_die_type (die, range_type, cu);
12887
12888   /* set_die_type should be already done.  */
12889   set_descriptive_type (range_type, die, cu);
12890
12891   return range_type;
12892 }
12893
12894 static struct type *
12895 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
12896 {
12897   struct type *type;
12898
12899   /* For now, we only support the C meaning of an unspecified type: void.  */
12900
12901   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
12902   TYPE_NAME (type) = dwarf2_name (die, cu);
12903
12904   return set_die_type (die, type, cu);
12905 }
12906
12907 /* Read a single die and all its descendents.  Set the die's sibling
12908    field to NULL; set other fields in the die correctly, and set all
12909    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
12910    location of the info_ptr after reading all of those dies.  PARENT
12911    is the parent of the die in question.  */
12912
12913 static struct die_info *
12914 read_die_and_children (const struct die_reader_specs *reader,
12915                        gdb_byte *info_ptr,
12916                        gdb_byte **new_info_ptr,
12917                        struct die_info *parent)
12918 {
12919   struct die_info *die;
12920   gdb_byte *cur_ptr;
12921   int has_children;
12922
12923   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
12924   if (die == NULL)
12925     {
12926       *new_info_ptr = cur_ptr;
12927       return NULL;
12928     }
12929   store_in_ref_table (die, reader->cu);
12930
12931   if (has_children)
12932     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
12933   else
12934     {
12935       die->child = NULL;
12936       *new_info_ptr = cur_ptr;
12937     }
12938
12939   die->sibling = NULL;
12940   die->parent = parent;
12941   return die;
12942 }
12943
12944 /* Read a die, all of its descendents, and all of its siblings; set
12945    all of the fields of all of the dies correctly.  Arguments are as
12946    in read_die_and_children.  */
12947
12948 static struct die_info *
12949 read_die_and_siblings (const struct die_reader_specs *reader,
12950                        gdb_byte *info_ptr,
12951                        gdb_byte **new_info_ptr,
12952                        struct die_info *parent)
12953 {
12954   struct die_info *first_die, *last_sibling;
12955   gdb_byte *cur_ptr;
12956
12957   cur_ptr = info_ptr;
12958   first_die = last_sibling = NULL;
12959
12960   while (1)
12961     {
12962       struct die_info *die
12963         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
12964
12965       if (die == NULL)
12966         {
12967           *new_info_ptr = cur_ptr;
12968           return first_die;
12969         }
12970
12971       if (!first_die)
12972         first_die = die;
12973       else
12974         last_sibling->sibling = die;
12975
12976       last_sibling = die;
12977     }
12978 }
12979
12980 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
12981    attributes.
12982    The caller is responsible for filling in the extra attributes
12983    and updating (*DIEP)->num_attrs.
12984    Set DIEP to point to a newly allocated die with its information,
12985    except for its child, sibling, and parent fields.
12986    Set HAS_CHILDREN to tell whether the die has children or not.  */
12987
12988 static gdb_byte *
12989 read_full_die_1 (const struct die_reader_specs *reader,
12990                  struct die_info **diep, gdb_byte *info_ptr,
12991                  int *has_children, int num_extra_attrs)
12992 {
12993   unsigned int abbrev_number, bytes_read, i;
12994   sect_offset offset;
12995   struct abbrev_info *abbrev;
12996   struct die_info *die;
12997   struct dwarf2_cu *cu = reader->cu;
12998   bfd *abfd = reader->abfd;
12999
13000   offset.sect_off = info_ptr - reader->buffer;
13001   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13002   info_ptr += bytes_read;
13003   if (!abbrev_number)
13004     {
13005       *diep = NULL;
13006       *has_children = 0;
13007       return info_ptr;
13008     }
13009
13010   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13011   if (!abbrev)
13012     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13013            abbrev_number,
13014            bfd_get_filename (abfd));
13015
13016   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13017   die->offset = offset;
13018   die->tag = abbrev->tag;
13019   die->abbrev = abbrev_number;
13020
13021   /* Make the result usable.
13022      The caller needs to update num_attrs after adding the extra
13023      attributes.  */
13024   die->num_attrs = abbrev->num_attrs;
13025
13026   for (i = 0; i < abbrev->num_attrs; ++i)
13027     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13028                                info_ptr);
13029
13030   *diep = die;
13031   *has_children = abbrev->has_children;
13032   return info_ptr;
13033 }
13034
13035 /* Read a die and all its attributes.
13036    Set DIEP to point to a newly allocated die with its information,
13037    except for its child, sibling, and parent fields.
13038    Set HAS_CHILDREN to tell whether the die has children or not.  */
13039
13040 static gdb_byte *
13041 read_full_die (const struct die_reader_specs *reader,
13042                struct die_info **diep, gdb_byte *info_ptr,
13043                int *has_children)
13044 {
13045   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13046 }
13047 \f
13048 /* Abbreviation tables.
13049
13050    In DWARF version 2, the description of the debugging information is
13051    stored in a separate .debug_abbrev section.  Before we read any
13052    dies from a section we read in all abbreviations and install them
13053    in a hash table.  */
13054
13055 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13056
13057 static struct abbrev_info *
13058 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13059 {
13060   struct abbrev_info *abbrev;
13061
13062   abbrev = (struct abbrev_info *)
13063     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13064   memset (abbrev, 0, sizeof (struct abbrev_info));
13065   return abbrev;
13066 }
13067
13068 /* Add an abbreviation to the table.  */
13069
13070 static void
13071 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13072                          unsigned int abbrev_number,
13073                          struct abbrev_info *abbrev)
13074 {
13075   unsigned int hash_number;
13076
13077   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13078   abbrev->next = abbrev_table->abbrevs[hash_number];
13079   abbrev_table->abbrevs[hash_number] = abbrev;
13080 }
13081
13082 /* Look up an abbrev in the table.
13083    Returns NULL if the abbrev is not found.  */
13084
13085 static struct abbrev_info *
13086 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13087                             unsigned int abbrev_number)
13088 {
13089   unsigned int hash_number;
13090   struct abbrev_info *abbrev;
13091
13092   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13093   abbrev = abbrev_table->abbrevs[hash_number];
13094
13095   while (abbrev)
13096     {
13097       if (abbrev->number == abbrev_number)
13098         return abbrev;
13099       abbrev = abbrev->next;
13100     }
13101   return NULL;
13102 }
13103
13104 /* Read in an abbrev table.  */
13105
13106 static struct abbrev_table *
13107 abbrev_table_read_table (struct dwarf2_section_info *section,
13108                          sect_offset offset)
13109 {
13110   struct objfile *objfile = dwarf2_per_objfile->objfile;
13111   bfd *abfd = section->asection->owner;
13112   struct abbrev_table *abbrev_table;
13113   gdb_byte *abbrev_ptr;
13114   struct abbrev_info *cur_abbrev;
13115   unsigned int abbrev_number, bytes_read, abbrev_name;
13116   unsigned int abbrev_form;
13117   struct attr_abbrev *cur_attrs;
13118   unsigned int allocated_attrs;
13119
13120   abbrev_table = XMALLOC (struct abbrev_table);
13121   abbrev_table->offset = offset;
13122   obstack_init (&abbrev_table->abbrev_obstack);
13123   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13124                                          (ABBREV_HASH_SIZE
13125                                           * sizeof (struct abbrev_info *)));
13126   memset (abbrev_table->abbrevs, 0,
13127           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13128
13129   dwarf2_read_section (objfile, section);
13130   abbrev_ptr = section->buffer + offset.sect_off;
13131   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13132   abbrev_ptr += bytes_read;
13133
13134   allocated_attrs = ATTR_ALLOC_CHUNK;
13135   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13136
13137   /* Loop until we reach an abbrev number of 0.  */
13138   while (abbrev_number)
13139     {
13140       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13141
13142       /* read in abbrev header */
13143       cur_abbrev->number = abbrev_number;
13144       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13145       abbrev_ptr += bytes_read;
13146       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13147       abbrev_ptr += 1;
13148
13149       /* now read in declarations */
13150       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13151       abbrev_ptr += bytes_read;
13152       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13153       abbrev_ptr += bytes_read;
13154       while (abbrev_name)
13155         {
13156           if (cur_abbrev->num_attrs == allocated_attrs)
13157             {
13158               allocated_attrs += ATTR_ALLOC_CHUNK;
13159               cur_attrs
13160                 = xrealloc (cur_attrs, (allocated_attrs
13161                                         * sizeof (struct attr_abbrev)));
13162             }
13163
13164           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13165           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13166           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13167           abbrev_ptr += bytes_read;
13168           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13169           abbrev_ptr += bytes_read;
13170         }
13171
13172       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13173                                          (cur_abbrev->num_attrs
13174                                           * sizeof (struct attr_abbrev)));
13175       memcpy (cur_abbrev->attrs, cur_attrs,
13176               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13177
13178       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13179
13180       /* Get next abbreviation.
13181          Under Irix6 the abbreviations for a compilation unit are not
13182          always properly terminated with an abbrev number of 0.
13183          Exit loop if we encounter an abbreviation which we have
13184          already read (which means we are about to read the abbreviations
13185          for the next compile unit) or if the end of the abbreviation
13186          table is reached.  */
13187       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13188         break;
13189       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13190       abbrev_ptr += bytes_read;
13191       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13192         break;
13193     }
13194
13195   xfree (cur_attrs);
13196   return abbrev_table;
13197 }
13198
13199 /* Free the resources held by ABBREV_TABLE.  */
13200
13201 static void
13202 abbrev_table_free (struct abbrev_table *abbrev_table)
13203 {
13204   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13205   xfree (abbrev_table);
13206 }
13207
13208 /* Same as abbrev_table_free but as a cleanup.
13209    We pass in a pointer to the pointer to the table so that we can
13210    set the pointer to NULL when we're done.  It also simplifies
13211    build_type_unit_groups.  */
13212
13213 static void
13214 abbrev_table_free_cleanup (void *table_ptr)
13215 {
13216   struct abbrev_table **abbrev_table_ptr = table_ptr;
13217
13218   if (*abbrev_table_ptr != NULL)
13219     abbrev_table_free (*abbrev_table_ptr);
13220   *abbrev_table_ptr = NULL;
13221 }
13222
13223 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13224
13225 static void
13226 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13227                      struct dwarf2_section_info *abbrev_section)
13228 {
13229   cu->abbrev_table =
13230     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13231 }
13232
13233 /* Release the memory used by the abbrev table for a compilation unit.  */
13234
13235 static void
13236 dwarf2_free_abbrev_table (void *ptr_to_cu)
13237 {
13238   struct dwarf2_cu *cu = ptr_to_cu;
13239
13240   abbrev_table_free (cu->abbrev_table);
13241   /* Set this to NULL so that we SEGV if we try to read it later,
13242      and also because free_comp_unit verifies this is NULL.  */
13243   cu->abbrev_table = NULL;
13244 }
13245 \f
13246 /* Returns nonzero if TAG represents a type that we might generate a partial
13247    symbol for.  */
13248
13249 static int
13250 is_type_tag_for_partial (int tag)
13251 {
13252   switch (tag)
13253     {
13254 #if 0
13255     /* Some types that would be reasonable to generate partial symbols for,
13256        that we don't at present.  */
13257     case DW_TAG_array_type:
13258     case DW_TAG_file_type:
13259     case DW_TAG_ptr_to_member_type:
13260     case DW_TAG_set_type:
13261     case DW_TAG_string_type:
13262     case DW_TAG_subroutine_type:
13263 #endif
13264     case DW_TAG_base_type:
13265     case DW_TAG_class_type:
13266     case DW_TAG_interface_type:
13267     case DW_TAG_enumeration_type:
13268     case DW_TAG_structure_type:
13269     case DW_TAG_subrange_type:
13270     case DW_TAG_typedef:
13271     case DW_TAG_union_type:
13272       return 1;
13273     default:
13274       return 0;
13275     }
13276 }
13277
13278 /* Load all DIEs that are interesting for partial symbols into memory.  */
13279
13280 static struct partial_die_info *
13281 load_partial_dies (const struct die_reader_specs *reader,
13282                    gdb_byte *info_ptr, int building_psymtab)
13283 {
13284   struct dwarf2_cu *cu = reader->cu;
13285   struct objfile *objfile = cu->objfile;
13286   struct partial_die_info *part_die;
13287   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13288   struct abbrev_info *abbrev;
13289   unsigned int bytes_read;
13290   unsigned int load_all = 0;
13291   int nesting_level = 1;
13292
13293   parent_die = NULL;
13294   last_die = NULL;
13295
13296   gdb_assert (cu->per_cu != NULL);
13297   if (cu->per_cu->load_all_dies)
13298     load_all = 1;
13299
13300   cu->partial_dies
13301     = htab_create_alloc_ex (cu->header.length / 12,
13302                             partial_die_hash,
13303                             partial_die_eq,
13304                             NULL,
13305                             &cu->comp_unit_obstack,
13306                             hashtab_obstack_allocate,
13307                             dummy_obstack_deallocate);
13308
13309   part_die = obstack_alloc (&cu->comp_unit_obstack,
13310                             sizeof (struct partial_die_info));
13311
13312   while (1)
13313     {
13314       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13315
13316       /* A NULL abbrev means the end of a series of children.  */
13317       if (abbrev == NULL)
13318         {
13319           if (--nesting_level == 0)
13320             {
13321               /* PART_DIE was probably the last thing allocated on the
13322                  comp_unit_obstack, so we could call obstack_free
13323                  here.  We don't do that because the waste is small,
13324                  and will be cleaned up when we're done with this
13325                  compilation unit.  This way, we're also more robust
13326                  against other users of the comp_unit_obstack.  */
13327               return first_die;
13328             }
13329           info_ptr += bytes_read;
13330           last_die = parent_die;
13331           parent_die = parent_die->die_parent;
13332           continue;
13333         }
13334
13335       /* Check for template arguments.  We never save these; if
13336          they're seen, we just mark the parent, and go on our way.  */
13337       if (parent_die != NULL
13338           && cu->language == language_cplus
13339           && (abbrev->tag == DW_TAG_template_type_param
13340               || abbrev->tag == DW_TAG_template_value_param))
13341         {
13342           parent_die->has_template_arguments = 1;
13343
13344           if (!load_all)
13345             {
13346               /* We don't need a partial DIE for the template argument.  */
13347               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13348               continue;
13349             }
13350         }
13351
13352       /* We only recurse into c++ subprograms looking for template arguments.
13353          Skip their other children.  */
13354       if (!load_all
13355           && cu->language == language_cplus
13356           && parent_die != NULL
13357           && parent_die->tag == DW_TAG_subprogram)
13358         {
13359           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13360           continue;
13361         }
13362
13363       /* Check whether this DIE is interesting enough to save.  Normally
13364          we would not be interested in members here, but there may be
13365          later variables referencing them via DW_AT_specification (for
13366          static members).  */
13367       if (!load_all
13368           && !is_type_tag_for_partial (abbrev->tag)
13369           && abbrev->tag != DW_TAG_constant
13370           && abbrev->tag != DW_TAG_enumerator
13371           && abbrev->tag != DW_TAG_subprogram
13372           && abbrev->tag != DW_TAG_lexical_block
13373           && abbrev->tag != DW_TAG_variable
13374           && abbrev->tag != DW_TAG_namespace
13375           && abbrev->tag != DW_TAG_module
13376           && abbrev->tag != DW_TAG_member
13377           && abbrev->tag != DW_TAG_imported_unit)
13378         {
13379           /* Otherwise we skip to the next sibling, if any.  */
13380           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13381           continue;
13382         }
13383
13384       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13385                                    info_ptr);
13386
13387       /* This two-pass algorithm for processing partial symbols has a
13388          high cost in cache pressure.  Thus, handle some simple cases
13389          here which cover the majority of C partial symbols.  DIEs
13390          which neither have specification tags in them, nor could have
13391          specification tags elsewhere pointing at them, can simply be
13392          processed and discarded.
13393
13394          This segment is also optional; scan_partial_symbols and
13395          add_partial_symbol will handle these DIEs if we chain
13396          them in normally.  When compilers which do not emit large
13397          quantities of duplicate debug information are more common,
13398          this code can probably be removed.  */
13399
13400       /* Any complete simple types at the top level (pretty much all
13401          of them, for a language without namespaces), can be processed
13402          directly.  */
13403       if (parent_die == NULL
13404           && part_die->has_specification == 0
13405           && part_die->is_declaration == 0
13406           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13407               || part_die->tag == DW_TAG_base_type
13408               || part_die->tag == DW_TAG_subrange_type))
13409         {
13410           if (building_psymtab && part_die->name != NULL)
13411             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13412                                  VAR_DOMAIN, LOC_TYPEDEF,
13413                                  &objfile->static_psymbols,
13414                                  0, (CORE_ADDR) 0, cu->language, objfile);
13415           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13416           continue;
13417         }
13418
13419       /* The exception for DW_TAG_typedef with has_children above is
13420          a workaround of GCC PR debug/47510.  In the case of this complaint
13421          type_name_no_tag_or_error will error on such types later.
13422
13423          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13424          it could not find the child DIEs referenced later, this is checked
13425          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13426
13427       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13428         complaint (&symfile_complaints,
13429                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13430                      "- DIE at 0x%x [in module %s]"),
13431                    part_die->offset.sect_off, objfile->name);
13432
13433       /* If we're at the second level, and we're an enumerator, and
13434          our parent has no specification (meaning possibly lives in a
13435          namespace elsewhere), then we can add the partial symbol now
13436          instead of queueing it.  */
13437       if (part_die->tag == DW_TAG_enumerator
13438           && parent_die != NULL
13439           && parent_die->die_parent == NULL
13440           && parent_die->tag == DW_TAG_enumeration_type
13441           && parent_die->has_specification == 0)
13442         {
13443           if (part_die->name == NULL)
13444             complaint (&symfile_complaints,
13445                        _("malformed enumerator DIE ignored"));
13446           else if (building_psymtab)
13447             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13448                                  VAR_DOMAIN, LOC_CONST,
13449                                  (cu->language == language_cplus
13450                                   || cu->language == language_java)
13451                                  ? &objfile->global_psymbols
13452                                  : &objfile->static_psymbols,
13453                                  0, (CORE_ADDR) 0, cu->language, objfile);
13454
13455           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13456           continue;
13457         }
13458
13459       /* We'll save this DIE so link it in.  */
13460       part_die->die_parent = parent_die;
13461       part_die->die_sibling = NULL;
13462       part_die->die_child = NULL;
13463
13464       if (last_die && last_die == parent_die)
13465         last_die->die_child = part_die;
13466       else if (last_die)
13467         last_die->die_sibling = part_die;
13468
13469       last_die = part_die;
13470
13471       if (first_die == NULL)
13472         first_die = part_die;
13473
13474       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13475          find interesting need to be in the hash table, because we
13476          also have the parent/sibling/child chains; only those that we
13477          might refer to by offset later during partial symbol reading.
13478
13479          For now this means things that might have be the target of a
13480          DW_AT_specification, DW_AT_abstract_origin, or
13481          DW_AT_extension.  DW_AT_extension will refer only to
13482          namespaces; DW_AT_abstract_origin refers to functions (and
13483          many things under the function DIE, but we do not recurse
13484          into function DIEs during partial symbol reading) and
13485          possibly variables as well; DW_AT_specification refers to
13486          declarations.  Declarations ought to have the DW_AT_declaration
13487          flag.  It happens that GCC forgets to put it in sometimes, but
13488          only for functions, not for types.
13489
13490          Adding more things than necessary to the hash table is harmless
13491          except for the performance cost.  Adding too few will result in
13492          wasted time in find_partial_die, when we reread the compilation
13493          unit with load_all_dies set.  */
13494
13495       if (load_all
13496           || abbrev->tag == DW_TAG_constant
13497           || abbrev->tag == DW_TAG_subprogram
13498           || abbrev->tag == DW_TAG_variable
13499           || abbrev->tag == DW_TAG_namespace
13500           || part_die->is_declaration)
13501         {
13502           void **slot;
13503
13504           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13505                                            part_die->offset.sect_off, INSERT);
13506           *slot = part_die;
13507         }
13508
13509       part_die = obstack_alloc (&cu->comp_unit_obstack,
13510                                 sizeof (struct partial_die_info));
13511
13512       /* For some DIEs we want to follow their children (if any).  For C
13513          we have no reason to follow the children of structures; for other
13514          languages we have to, so that we can get at method physnames
13515          to infer fully qualified class names, for DW_AT_specification,
13516          and for C++ template arguments.  For C++, we also look one level
13517          inside functions to find template arguments (if the name of the
13518          function does not already contain the template arguments).
13519
13520          For Ada, we need to scan the children of subprograms and lexical
13521          blocks as well because Ada allows the definition of nested
13522          entities that could be interesting for the debugger, such as
13523          nested subprograms for instance.  */
13524       if (last_die->has_children
13525           && (load_all
13526               || last_die->tag == DW_TAG_namespace
13527               || last_die->tag == DW_TAG_module
13528               || last_die->tag == DW_TAG_enumeration_type
13529               || (cu->language == language_cplus
13530                   && last_die->tag == DW_TAG_subprogram
13531                   && (last_die->name == NULL
13532                       || strchr (last_die->name, '<') == NULL))
13533               || (cu->language != language_c
13534                   && (last_die->tag == DW_TAG_class_type
13535                       || last_die->tag == DW_TAG_interface_type
13536                       || last_die->tag == DW_TAG_structure_type
13537                       || last_die->tag == DW_TAG_union_type))
13538               || (cu->language == language_ada
13539                   && (last_die->tag == DW_TAG_subprogram
13540                       || last_die->tag == DW_TAG_lexical_block))))
13541         {
13542           nesting_level++;
13543           parent_die = last_die;
13544           continue;
13545         }
13546
13547       /* Otherwise we skip to the next sibling, if any.  */
13548       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13549
13550       /* Back to the top, do it again.  */
13551     }
13552 }
13553
13554 /* Read a minimal amount of information into the minimal die structure.  */
13555
13556 static gdb_byte *
13557 read_partial_die (const struct die_reader_specs *reader,
13558                   struct partial_die_info *part_die,
13559                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13560                   gdb_byte *info_ptr)
13561 {
13562   struct dwarf2_cu *cu = reader->cu;
13563   struct objfile *objfile = cu->objfile;
13564   gdb_byte *buffer = reader->buffer;
13565   unsigned int i;
13566   struct attribute attr;
13567   int has_low_pc_attr = 0;
13568   int has_high_pc_attr = 0;
13569   int high_pc_relative = 0;
13570
13571   memset (part_die, 0, sizeof (struct partial_die_info));
13572
13573   part_die->offset.sect_off = info_ptr - buffer;
13574
13575   info_ptr += abbrev_len;
13576
13577   if (abbrev == NULL)
13578     return info_ptr;
13579
13580   part_die->tag = abbrev->tag;
13581   part_die->has_children = abbrev->has_children;
13582
13583   for (i = 0; i < abbrev->num_attrs; ++i)
13584     {
13585       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13586
13587       /* Store the data if it is of an attribute we want to keep in a
13588          partial symbol table.  */
13589       switch (attr.name)
13590         {
13591         case DW_AT_name:
13592           switch (part_die->tag)
13593             {
13594             case DW_TAG_compile_unit:
13595             case DW_TAG_partial_unit:
13596             case DW_TAG_type_unit:
13597               /* Compilation units have a DW_AT_name that is a filename, not
13598                  a source language identifier.  */
13599             case DW_TAG_enumeration_type:
13600             case DW_TAG_enumerator:
13601               /* These tags always have simple identifiers already; no need
13602                  to canonicalize them.  */
13603               part_die->name = DW_STRING (&attr);
13604               break;
13605             default:
13606               part_die->name
13607                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13608                                             &objfile->objfile_obstack);
13609               break;
13610             }
13611           break;
13612         case DW_AT_linkage_name:
13613         case DW_AT_MIPS_linkage_name:
13614           /* Note that both forms of linkage name might appear.  We
13615              assume they will be the same, and we only store the last
13616              one we see.  */
13617           if (cu->language == language_ada)
13618             part_die->name = DW_STRING (&attr);
13619           part_die->linkage_name = DW_STRING (&attr);
13620           break;
13621         case DW_AT_low_pc:
13622           has_low_pc_attr = 1;
13623           part_die->lowpc = DW_ADDR (&attr);
13624           break;
13625         case DW_AT_high_pc:
13626           has_high_pc_attr = 1;
13627           if (attr.form == DW_FORM_addr
13628               || attr.form == DW_FORM_GNU_addr_index)
13629             part_die->highpc = DW_ADDR (&attr);
13630           else
13631             {
13632               high_pc_relative = 1;
13633               part_die->highpc = DW_UNSND (&attr);
13634             }
13635           break;
13636         case DW_AT_location:
13637           /* Support the .debug_loc offsets.  */
13638           if (attr_form_is_block (&attr))
13639             {
13640                part_die->d.locdesc = DW_BLOCK (&attr);
13641             }
13642           else if (attr_form_is_section_offset (&attr))
13643             {
13644               dwarf2_complex_location_expr_complaint ();
13645             }
13646           else
13647             {
13648               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13649                                                      "partial symbol information");
13650             }
13651           break;
13652         case DW_AT_external:
13653           part_die->is_external = DW_UNSND (&attr);
13654           break;
13655         case DW_AT_declaration:
13656           part_die->is_declaration = DW_UNSND (&attr);
13657           break;
13658         case DW_AT_type:
13659           part_die->has_type = 1;
13660           break;
13661         case DW_AT_abstract_origin:
13662         case DW_AT_specification:
13663         case DW_AT_extension:
13664           part_die->has_specification = 1;
13665           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13666           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13667                                    || cu->per_cu->is_dwz);
13668           break;
13669         case DW_AT_sibling:
13670           /* Ignore absolute siblings, they might point outside of
13671              the current compile unit.  */
13672           if (attr.form == DW_FORM_ref_addr)
13673             complaint (&symfile_complaints,
13674                        _("ignoring absolute DW_AT_sibling"));
13675           else
13676             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13677           break;
13678         case DW_AT_byte_size:
13679           part_die->has_byte_size = 1;
13680           break;
13681         case DW_AT_calling_convention:
13682           /* DWARF doesn't provide a way to identify a program's source-level
13683              entry point.  DW_AT_calling_convention attributes are only meant
13684              to describe functions' calling conventions.
13685
13686              However, because it's a necessary piece of information in
13687              Fortran, and because DW_CC_program is the only piece of debugging
13688              information whose definition refers to a 'main program' at all,
13689              several compilers have begun marking Fortran main programs with
13690              DW_CC_program --- even when those functions use the standard
13691              calling conventions.
13692
13693              So until DWARF specifies a way to provide this information and
13694              compilers pick up the new representation, we'll support this
13695              practice.  */
13696           if (DW_UNSND (&attr) == DW_CC_program
13697               && cu->language == language_fortran)
13698             {
13699               set_main_name (part_die->name);
13700
13701               /* As this DIE has a static linkage the name would be difficult
13702                  to look up later.  */
13703               language_of_main = language_fortran;
13704             }
13705           break;
13706         case DW_AT_inline:
13707           if (DW_UNSND (&attr) == DW_INL_inlined
13708               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13709             part_die->may_be_inlined = 1;
13710           break;
13711
13712         case DW_AT_import:
13713           if (part_die->tag == DW_TAG_imported_unit)
13714             {
13715               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13716               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13717                                   || cu->per_cu->is_dwz);
13718             }
13719           break;
13720
13721         default:
13722           break;
13723         }
13724     }
13725
13726   if (high_pc_relative)
13727     part_die->highpc += part_die->lowpc;
13728
13729   if (has_low_pc_attr && has_high_pc_attr)
13730     {
13731       /* When using the GNU linker, .gnu.linkonce. sections are used to
13732          eliminate duplicate copies of functions and vtables and such.
13733          The linker will arbitrarily choose one and discard the others.
13734          The AT_*_pc values for such functions refer to local labels in
13735          these sections.  If the section from that file was discarded, the
13736          labels are not in the output, so the relocs get a value of 0.
13737          If this is a discarded function, mark the pc bounds as invalid,
13738          so that GDB will ignore it.  */
13739       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13740         {
13741           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13742
13743           complaint (&symfile_complaints,
13744                      _("DW_AT_low_pc %s is zero "
13745                        "for DIE at 0x%x [in module %s]"),
13746                      paddress (gdbarch, part_die->lowpc),
13747                      part_die->offset.sect_off, objfile->name);
13748         }
13749       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13750       else if (part_die->lowpc >= part_die->highpc)
13751         {
13752           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13753
13754           complaint (&symfile_complaints,
13755                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13756                        "for DIE at 0x%x [in module %s]"),
13757                      paddress (gdbarch, part_die->lowpc),
13758                      paddress (gdbarch, part_die->highpc),
13759                      part_die->offset.sect_off, objfile->name);
13760         }
13761       else
13762         part_die->has_pc_info = 1;
13763     }
13764
13765   return info_ptr;
13766 }
13767
13768 /* Find a cached partial DIE at OFFSET in CU.  */
13769
13770 static struct partial_die_info *
13771 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13772 {
13773   struct partial_die_info *lookup_die = NULL;
13774   struct partial_die_info part_die;
13775
13776   part_die.offset = offset;
13777   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13778                                     offset.sect_off);
13779
13780   return lookup_die;
13781 }
13782
13783 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13784    except in the case of .debug_types DIEs which do not reference
13785    outside their CU (they do however referencing other types via
13786    DW_FORM_ref_sig8).  */
13787
13788 static struct partial_die_info *
13789 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13790 {
13791   struct objfile *objfile = cu->objfile;
13792   struct dwarf2_per_cu_data *per_cu = NULL;
13793   struct partial_die_info *pd = NULL;
13794
13795   if (offset_in_dwz == cu->per_cu->is_dwz
13796       && offset_in_cu_p (&cu->header, offset))
13797     {
13798       pd = find_partial_die_in_comp_unit (offset, cu);
13799       if (pd != NULL)
13800         return pd;
13801       /* We missed recording what we needed.
13802          Load all dies and try again.  */
13803       per_cu = cu->per_cu;
13804     }
13805   else
13806     {
13807       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13808       if (cu->per_cu->is_debug_types)
13809         {
13810           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13811                    " external reference to offset 0x%lx [in module %s].\n"),
13812                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
13813                  bfd_get_filename (objfile->obfd));
13814         }
13815       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
13816                                                  objfile);
13817
13818       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
13819         load_partial_comp_unit (per_cu);
13820
13821       per_cu->cu->last_used = 0;
13822       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13823     }
13824
13825   /* If we didn't find it, and not all dies have been loaded,
13826      load them all and try again.  */
13827
13828   if (pd == NULL && per_cu->load_all_dies == 0)
13829     {
13830       per_cu->load_all_dies = 1;
13831
13832       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
13833          THIS_CU->cu may already be in use.  So we can't just free it and
13834          replace its DIEs with the ones we read in.  Instead, we leave those
13835          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
13836          and clobber THIS_CU->cu->partial_dies with the hash table for the new
13837          set.  */
13838       load_partial_comp_unit (per_cu);
13839
13840       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13841     }
13842
13843   if (pd == NULL)
13844     internal_error (__FILE__, __LINE__,
13845                     _("could not find partial DIE 0x%x "
13846                       "in cache [from module %s]\n"),
13847                     offset.sect_off, bfd_get_filename (objfile->obfd));
13848   return pd;
13849 }
13850
13851 /* See if we can figure out if the class lives in a namespace.  We do
13852    this by looking for a member function; its demangled name will
13853    contain namespace info, if there is any.  */
13854
13855 static void
13856 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
13857                                   struct dwarf2_cu *cu)
13858 {
13859   /* NOTE: carlton/2003-10-07: Getting the info this way changes
13860      what template types look like, because the demangler
13861      frequently doesn't give the same name as the debug info.  We
13862      could fix this by only using the demangled name to get the
13863      prefix (but see comment in read_structure_type).  */
13864
13865   struct partial_die_info *real_pdi;
13866   struct partial_die_info *child_pdi;
13867
13868   /* If this DIE (this DIE's specification, if any) has a parent, then
13869      we should not do this.  We'll prepend the parent's fully qualified
13870      name when we create the partial symbol.  */
13871
13872   real_pdi = struct_pdi;
13873   while (real_pdi->has_specification)
13874     real_pdi = find_partial_die (real_pdi->spec_offset,
13875                                  real_pdi->spec_is_dwz, cu);
13876
13877   if (real_pdi->die_parent != NULL)
13878     return;
13879
13880   for (child_pdi = struct_pdi->die_child;
13881        child_pdi != NULL;
13882        child_pdi = child_pdi->die_sibling)
13883     {
13884       if (child_pdi->tag == DW_TAG_subprogram
13885           && child_pdi->linkage_name != NULL)
13886         {
13887           char *actual_class_name
13888             = language_class_name_from_physname (cu->language_defn,
13889                                                  child_pdi->linkage_name);
13890           if (actual_class_name != NULL)
13891             {
13892               struct_pdi->name
13893                 = obstack_copy0 (&cu->objfile->objfile_obstack,
13894                                  actual_class_name,
13895                                  strlen (actual_class_name));
13896               xfree (actual_class_name);
13897             }
13898           break;
13899         }
13900     }
13901 }
13902
13903 /* Adjust PART_DIE before generating a symbol for it.  This function
13904    may set the is_external flag or change the DIE's name.  */
13905
13906 static void
13907 fixup_partial_die (struct partial_die_info *part_die,
13908                    struct dwarf2_cu *cu)
13909 {
13910   /* Once we've fixed up a die, there's no point in doing so again.
13911      This also avoids a memory leak if we were to call
13912      guess_partial_die_structure_name multiple times.  */
13913   if (part_die->fixup_called)
13914     return;
13915
13916   /* If we found a reference attribute and the DIE has no name, try
13917      to find a name in the referred to DIE.  */
13918
13919   if (part_die->name == NULL && part_die->has_specification)
13920     {
13921       struct partial_die_info *spec_die;
13922
13923       spec_die = find_partial_die (part_die->spec_offset,
13924                                    part_die->spec_is_dwz, cu);
13925
13926       fixup_partial_die (spec_die, cu);
13927
13928       if (spec_die->name)
13929         {
13930           part_die->name = spec_die->name;
13931
13932           /* Copy DW_AT_external attribute if it is set.  */
13933           if (spec_die->is_external)
13934             part_die->is_external = spec_die->is_external;
13935         }
13936     }
13937
13938   /* Set default names for some unnamed DIEs.  */
13939
13940   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
13941     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
13942
13943   /* If there is no parent die to provide a namespace, and there are
13944      children, see if we can determine the namespace from their linkage
13945      name.  */
13946   if (cu->language == language_cplus
13947       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
13948       && part_die->die_parent == NULL
13949       && part_die->has_children
13950       && (part_die->tag == DW_TAG_class_type
13951           || part_die->tag == DW_TAG_structure_type
13952           || part_die->tag == DW_TAG_union_type))
13953     guess_partial_die_structure_name (part_die, cu);
13954
13955   /* GCC might emit a nameless struct or union that has a linkage
13956      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
13957   if (part_die->name == NULL
13958       && (part_die->tag == DW_TAG_class_type
13959           || part_die->tag == DW_TAG_interface_type
13960           || part_die->tag == DW_TAG_structure_type
13961           || part_die->tag == DW_TAG_union_type)
13962       && part_die->linkage_name != NULL)
13963     {
13964       char *demangled;
13965
13966       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
13967       if (demangled)
13968         {
13969           const char *base;
13970
13971           /* Strip any leading namespaces/classes, keep only the base name.
13972              DW_AT_name for named DIEs does not contain the prefixes.  */
13973           base = strrchr (demangled, ':');
13974           if (base && base > demangled && base[-1] == ':')
13975             base++;
13976           else
13977             base = demangled;
13978
13979           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
13980                                           base, strlen (base));
13981           xfree (demangled);
13982         }
13983     }
13984
13985   part_die->fixup_called = 1;
13986 }
13987
13988 /* Read an attribute value described by an attribute form.  */
13989
13990 static gdb_byte *
13991 read_attribute_value (const struct die_reader_specs *reader,
13992                       struct attribute *attr, unsigned form,
13993                       gdb_byte *info_ptr)
13994 {
13995   struct dwarf2_cu *cu = reader->cu;
13996   bfd *abfd = reader->abfd;
13997   struct comp_unit_head *cu_header = &cu->header;
13998   unsigned int bytes_read;
13999   struct dwarf_block *blk;
14000
14001   attr->form = form;
14002   switch (form)
14003     {
14004     case DW_FORM_ref_addr:
14005       if (cu->header.version == 2)
14006         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14007       else
14008         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14009                                        &cu->header, &bytes_read);
14010       info_ptr += bytes_read;
14011       break;
14012     case DW_FORM_GNU_ref_alt:
14013       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14014       info_ptr += bytes_read;
14015       break;
14016     case DW_FORM_addr:
14017       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14018       info_ptr += bytes_read;
14019       break;
14020     case DW_FORM_block2:
14021       blk = dwarf_alloc_block (cu);
14022       blk->size = read_2_bytes (abfd, info_ptr);
14023       info_ptr += 2;
14024       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14025       info_ptr += blk->size;
14026       DW_BLOCK (attr) = blk;
14027       break;
14028     case DW_FORM_block4:
14029       blk = dwarf_alloc_block (cu);
14030       blk->size = read_4_bytes (abfd, info_ptr);
14031       info_ptr += 4;
14032       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14033       info_ptr += blk->size;
14034       DW_BLOCK (attr) = blk;
14035       break;
14036     case DW_FORM_data2:
14037       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14038       info_ptr += 2;
14039       break;
14040     case DW_FORM_data4:
14041       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14042       info_ptr += 4;
14043       break;
14044     case DW_FORM_data8:
14045       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14046       info_ptr += 8;
14047       break;
14048     case DW_FORM_sec_offset:
14049       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14050       info_ptr += bytes_read;
14051       break;
14052     case DW_FORM_string:
14053       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14054       DW_STRING_IS_CANONICAL (attr) = 0;
14055       info_ptr += bytes_read;
14056       break;
14057     case DW_FORM_strp:
14058       if (!cu->per_cu->is_dwz)
14059         {
14060           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14061                                                    &bytes_read);
14062           DW_STRING_IS_CANONICAL (attr) = 0;
14063           info_ptr += bytes_read;
14064           break;
14065         }
14066       /* FALLTHROUGH */
14067     case DW_FORM_GNU_strp_alt:
14068       {
14069         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14070         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14071                                           &bytes_read);
14072
14073         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14074         DW_STRING_IS_CANONICAL (attr) = 0;
14075         info_ptr += bytes_read;
14076       }
14077       break;
14078     case DW_FORM_exprloc:
14079     case DW_FORM_block:
14080       blk = dwarf_alloc_block (cu);
14081       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14082       info_ptr += bytes_read;
14083       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14084       info_ptr += blk->size;
14085       DW_BLOCK (attr) = blk;
14086       break;
14087     case DW_FORM_block1:
14088       blk = dwarf_alloc_block (cu);
14089       blk->size = read_1_byte (abfd, info_ptr);
14090       info_ptr += 1;
14091       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14092       info_ptr += blk->size;
14093       DW_BLOCK (attr) = blk;
14094       break;
14095     case DW_FORM_data1:
14096       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14097       info_ptr += 1;
14098       break;
14099     case DW_FORM_flag:
14100       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14101       info_ptr += 1;
14102       break;
14103     case DW_FORM_flag_present:
14104       DW_UNSND (attr) = 1;
14105       break;
14106     case DW_FORM_sdata:
14107       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14108       info_ptr += bytes_read;
14109       break;
14110     case DW_FORM_udata:
14111       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14112       info_ptr += bytes_read;
14113       break;
14114     case DW_FORM_ref1:
14115       DW_UNSND (attr) = (cu->header.offset.sect_off
14116                          + read_1_byte (abfd, info_ptr));
14117       info_ptr += 1;
14118       break;
14119     case DW_FORM_ref2:
14120       DW_UNSND (attr) = (cu->header.offset.sect_off
14121                          + read_2_bytes (abfd, info_ptr));
14122       info_ptr += 2;
14123       break;
14124     case DW_FORM_ref4:
14125       DW_UNSND (attr) = (cu->header.offset.sect_off
14126                          + read_4_bytes (abfd, info_ptr));
14127       info_ptr += 4;
14128       break;
14129     case DW_FORM_ref8:
14130       DW_UNSND (attr) = (cu->header.offset.sect_off
14131                          + read_8_bytes (abfd, info_ptr));
14132       info_ptr += 8;
14133       break;
14134     case DW_FORM_ref_sig8:
14135       /* Convert the signature to something we can record in DW_UNSND
14136          for later lookup.
14137          NOTE: This is NULL if the type wasn't found.  */
14138       DW_SIGNATURED_TYPE (attr) =
14139         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14140       info_ptr += 8;
14141       break;
14142     case DW_FORM_ref_udata:
14143       DW_UNSND (attr) = (cu->header.offset.sect_off
14144                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14145       info_ptr += bytes_read;
14146       break;
14147     case DW_FORM_indirect:
14148       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14149       info_ptr += bytes_read;
14150       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14151       break;
14152     case DW_FORM_GNU_addr_index:
14153       if (reader->dwo_file == NULL)
14154         {
14155           /* For now flag a hard error.
14156              Later we can turn this into a complaint.  */
14157           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14158                  dwarf_form_name (form),
14159                  bfd_get_filename (abfd));
14160         }
14161       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14162       info_ptr += bytes_read;
14163       break;
14164     case DW_FORM_GNU_str_index:
14165       if (reader->dwo_file == NULL)
14166         {
14167           /* For now flag a hard error.
14168              Later we can turn this into a complaint if warranted.  */
14169           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14170                  dwarf_form_name (form),
14171                  bfd_get_filename (abfd));
14172         }
14173       {
14174         ULONGEST str_index =
14175           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14176
14177         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14178         DW_STRING_IS_CANONICAL (attr) = 0;
14179         info_ptr += bytes_read;
14180       }
14181       break;
14182     default:
14183       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14184              dwarf_form_name (form),
14185              bfd_get_filename (abfd));
14186     }
14187
14188   /* Super hack.  */
14189   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14190     attr->form = DW_FORM_GNU_ref_alt;
14191
14192   /* We have seen instances where the compiler tried to emit a byte
14193      size attribute of -1 which ended up being encoded as an unsigned
14194      0xffffffff.  Although 0xffffffff is technically a valid size value,
14195      an object of this size seems pretty unlikely so we can relatively
14196      safely treat these cases as if the size attribute was invalid and
14197      treat them as zero by default.  */
14198   if (attr->name == DW_AT_byte_size
14199       && form == DW_FORM_data4
14200       && DW_UNSND (attr) >= 0xffffffff)
14201     {
14202       complaint
14203         (&symfile_complaints,
14204          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14205          hex_string (DW_UNSND (attr)));
14206       DW_UNSND (attr) = 0;
14207     }
14208
14209   return info_ptr;
14210 }
14211
14212 /* Read an attribute described by an abbreviated attribute.  */
14213
14214 static gdb_byte *
14215 read_attribute (const struct die_reader_specs *reader,
14216                 struct attribute *attr, struct attr_abbrev *abbrev,
14217                 gdb_byte *info_ptr)
14218 {
14219   attr->name = abbrev->name;
14220   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14221 }
14222
14223 /* Read dwarf information from a buffer.  */
14224
14225 static unsigned int
14226 read_1_byte (bfd *abfd, const gdb_byte *buf)
14227 {
14228   return bfd_get_8 (abfd, buf);
14229 }
14230
14231 static int
14232 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14233 {
14234   return bfd_get_signed_8 (abfd, buf);
14235 }
14236
14237 static unsigned int
14238 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14239 {
14240   return bfd_get_16 (abfd, buf);
14241 }
14242
14243 static int
14244 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14245 {
14246   return bfd_get_signed_16 (abfd, buf);
14247 }
14248
14249 static unsigned int
14250 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14251 {
14252   return bfd_get_32 (abfd, buf);
14253 }
14254
14255 static int
14256 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14257 {
14258   return bfd_get_signed_32 (abfd, buf);
14259 }
14260
14261 static ULONGEST
14262 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14263 {
14264   return bfd_get_64 (abfd, buf);
14265 }
14266
14267 static CORE_ADDR
14268 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
14269               unsigned int *bytes_read)
14270 {
14271   struct comp_unit_head *cu_header = &cu->header;
14272   CORE_ADDR retval = 0;
14273
14274   if (cu_header->signed_addr_p)
14275     {
14276       switch (cu_header->addr_size)
14277         {
14278         case 2:
14279           retval = bfd_get_signed_16 (abfd, buf);
14280           break;
14281         case 4:
14282           retval = bfd_get_signed_32 (abfd, buf);
14283           break;
14284         case 8:
14285           retval = bfd_get_signed_64 (abfd, buf);
14286           break;
14287         default:
14288           internal_error (__FILE__, __LINE__,
14289                           _("read_address: bad switch, signed [in module %s]"),
14290                           bfd_get_filename (abfd));
14291         }
14292     }
14293   else
14294     {
14295       switch (cu_header->addr_size)
14296         {
14297         case 2:
14298           retval = bfd_get_16 (abfd, buf);
14299           break;
14300         case 4:
14301           retval = bfd_get_32 (abfd, buf);
14302           break;
14303         case 8:
14304           retval = bfd_get_64 (abfd, buf);
14305           break;
14306         default:
14307           internal_error (__FILE__, __LINE__,
14308                           _("read_address: bad switch, "
14309                             "unsigned [in module %s]"),
14310                           bfd_get_filename (abfd));
14311         }
14312     }
14313
14314   *bytes_read = cu_header->addr_size;
14315   return retval;
14316 }
14317
14318 /* Read the initial length from a section.  The (draft) DWARF 3
14319    specification allows the initial length to take up either 4 bytes
14320    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14321    bytes describe the length and all offsets will be 8 bytes in length
14322    instead of 4.
14323
14324    An older, non-standard 64-bit format is also handled by this
14325    function.  The older format in question stores the initial length
14326    as an 8-byte quantity without an escape value.  Lengths greater
14327    than 2^32 aren't very common which means that the initial 4 bytes
14328    is almost always zero.  Since a length value of zero doesn't make
14329    sense for the 32-bit format, this initial zero can be considered to
14330    be an escape value which indicates the presence of the older 64-bit
14331    format.  As written, the code can't detect (old format) lengths
14332    greater than 4GB.  If it becomes necessary to handle lengths
14333    somewhat larger than 4GB, we could allow other small values (such
14334    as the non-sensical values of 1, 2, and 3) to also be used as
14335    escape values indicating the presence of the old format.
14336
14337    The value returned via bytes_read should be used to increment the
14338    relevant pointer after calling read_initial_length().
14339
14340    [ Note:  read_initial_length() and read_offset() are based on the
14341      document entitled "DWARF Debugging Information Format", revision
14342      3, draft 8, dated November 19, 2001.  This document was obtained
14343      from:
14344
14345         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14346
14347      This document is only a draft and is subject to change.  (So beware.)
14348
14349      Details regarding the older, non-standard 64-bit format were
14350      determined empirically by examining 64-bit ELF files produced by
14351      the SGI toolchain on an IRIX 6.5 machine.
14352
14353      - Kevin, July 16, 2002
14354    ] */
14355
14356 static LONGEST
14357 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
14358 {
14359   LONGEST length = bfd_get_32 (abfd, buf);
14360
14361   if (length == 0xffffffff)
14362     {
14363       length = bfd_get_64 (abfd, buf + 4);
14364       *bytes_read = 12;
14365     }
14366   else if (length == 0)
14367     {
14368       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14369       length = bfd_get_64 (abfd, buf);
14370       *bytes_read = 8;
14371     }
14372   else
14373     {
14374       *bytes_read = 4;
14375     }
14376
14377   return length;
14378 }
14379
14380 /* Cover function for read_initial_length.
14381    Returns the length of the object at BUF, and stores the size of the
14382    initial length in *BYTES_READ and stores the size that offsets will be in
14383    *OFFSET_SIZE.
14384    If the initial length size is not equivalent to that specified in
14385    CU_HEADER then issue a complaint.
14386    This is useful when reading non-comp-unit headers.  */
14387
14388 static LONGEST
14389 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
14390                                         const struct comp_unit_head *cu_header,
14391                                         unsigned int *bytes_read,
14392                                         unsigned int *offset_size)
14393 {
14394   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14395
14396   gdb_assert (cu_header->initial_length_size == 4
14397               || cu_header->initial_length_size == 8
14398               || cu_header->initial_length_size == 12);
14399
14400   if (cu_header->initial_length_size != *bytes_read)
14401     complaint (&symfile_complaints,
14402                _("intermixed 32-bit and 64-bit DWARF sections"));
14403
14404   *offset_size = (*bytes_read == 4) ? 4 : 8;
14405   return length;
14406 }
14407
14408 /* Read an offset from the data stream.  The size of the offset is
14409    given by cu_header->offset_size.  */
14410
14411 static LONGEST
14412 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
14413              unsigned int *bytes_read)
14414 {
14415   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14416
14417   *bytes_read = cu_header->offset_size;
14418   return offset;
14419 }
14420
14421 /* Read an offset from the data stream.  */
14422
14423 static LONGEST
14424 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
14425 {
14426   LONGEST retval = 0;
14427
14428   switch (offset_size)
14429     {
14430     case 4:
14431       retval = bfd_get_32 (abfd, buf);
14432       break;
14433     case 8:
14434       retval = bfd_get_64 (abfd, buf);
14435       break;
14436     default:
14437       internal_error (__FILE__, __LINE__,
14438                       _("read_offset_1: bad switch [in module %s]"),
14439                       bfd_get_filename (abfd));
14440     }
14441
14442   return retval;
14443 }
14444
14445 static gdb_byte *
14446 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
14447 {
14448   /* If the size of a host char is 8 bits, we can return a pointer
14449      to the buffer, otherwise we have to copy the data to a buffer
14450      allocated on the temporary obstack.  */
14451   gdb_assert (HOST_CHAR_BIT == 8);
14452   return buf;
14453 }
14454
14455 static char *
14456 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14457 {
14458   /* If the size of a host char is 8 bits, we can return a pointer
14459      to the string, otherwise we have to copy the string to a buffer
14460      allocated on the temporary obstack.  */
14461   gdb_assert (HOST_CHAR_BIT == 8);
14462   if (*buf == '\0')
14463     {
14464       *bytes_read_ptr = 1;
14465       return NULL;
14466     }
14467   *bytes_read_ptr = strlen ((char *) buf) + 1;
14468   return (char *) buf;
14469 }
14470
14471 static char *
14472 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14473 {
14474   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14475   if (dwarf2_per_objfile->str.buffer == NULL)
14476     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14477            bfd_get_filename (abfd));
14478   if (str_offset >= dwarf2_per_objfile->str.size)
14479     error (_("DW_FORM_strp pointing outside of "
14480              ".debug_str section [in module %s]"),
14481            bfd_get_filename (abfd));
14482   gdb_assert (HOST_CHAR_BIT == 8);
14483   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14484     return NULL;
14485   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
14486 }
14487
14488 /* Read a string at offset STR_OFFSET in the .debug_str section from
14489    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14490    the string consists of a single NUL byte, return NULL; otherwise
14491    return a pointer to the string.  */
14492
14493 static char *
14494 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14495 {
14496   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14497
14498   if (dwz->str.buffer == NULL)
14499     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14500              "section [in module %s]"),
14501            bfd_get_filename (dwz->dwz_bfd));
14502   if (str_offset >= dwz->str.size)
14503     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14504              ".debug_str section [in module %s]"),
14505            bfd_get_filename (dwz->dwz_bfd));
14506   gdb_assert (HOST_CHAR_BIT == 8);
14507   if (dwz->str.buffer[str_offset] == '\0')
14508     return NULL;
14509   return (char *) (dwz->str.buffer + str_offset);
14510 }
14511
14512 static char *
14513 read_indirect_string (bfd *abfd, gdb_byte *buf,
14514                       const struct comp_unit_head *cu_header,
14515                       unsigned int *bytes_read_ptr)
14516 {
14517   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14518
14519   return read_indirect_string_at_offset (abfd, str_offset);
14520 }
14521
14522 static ULONGEST
14523 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14524 {
14525   ULONGEST result;
14526   unsigned int num_read;
14527   int i, shift;
14528   unsigned char byte;
14529
14530   result = 0;
14531   shift = 0;
14532   num_read = 0;
14533   i = 0;
14534   while (1)
14535     {
14536       byte = bfd_get_8 (abfd, buf);
14537       buf++;
14538       num_read++;
14539       result |= ((ULONGEST) (byte & 127) << shift);
14540       if ((byte & 128) == 0)
14541         {
14542           break;
14543         }
14544       shift += 7;
14545     }
14546   *bytes_read_ptr = num_read;
14547   return result;
14548 }
14549
14550 static LONGEST
14551 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14552 {
14553   LONGEST result;
14554   int i, shift, num_read;
14555   unsigned char byte;
14556
14557   result = 0;
14558   shift = 0;
14559   num_read = 0;
14560   i = 0;
14561   while (1)
14562     {
14563       byte = bfd_get_8 (abfd, buf);
14564       buf++;
14565       num_read++;
14566       result |= ((LONGEST) (byte & 127) << shift);
14567       shift += 7;
14568       if ((byte & 128) == 0)
14569         {
14570           break;
14571         }
14572     }
14573   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14574     result |= -(((LONGEST) 1) << shift);
14575   *bytes_read_ptr = num_read;
14576   return result;
14577 }
14578
14579 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14580    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14581    ADDR_SIZE is the size of addresses from the CU header.  */
14582
14583 static CORE_ADDR
14584 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14585 {
14586   struct objfile *objfile = dwarf2_per_objfile->objfile;
14587   bfd *abfd = objfile->obfd;
14588   const gdb_byte *info_ptr;
14589
14590   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14591   if (dwarf2_per_objfile->addr.buffer == NULL)
14592     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14593            objfile->name);
14594   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14595     error (_("DW_FORM_addr_index pointing outside of "
14596              ".debug_addr section [in module %s]"),
14597            objfile->name);
14598   info_ptr = (dwarf2_per_objfile->addr.buffer
14599               + addr_base + addr_index * addr_size);
14600   if (addr_size == 4)
14601     return bfd_get_32 (abfd, info_ptr);
14602   else
14603     return bfd_get_64 (abfd, info_ptr);
14604 }
14605
14606 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14607
14608 static CORE_ADDR
14609 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14610 {
14611   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14612 }
14613
14614 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14615
14616 static CORE_ADDR
14617 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
14618                              unsigned int *bytes_read)
14619 {
14620   bfd *abfd = cu->objfile->obfd;
14621   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14622
14623   return read_addr_index (cu, addr_index);
14624 }
14625
14626 /* Data structure to pass results from dwarf2_read_addr_index_reader
14627    back to dwarf2_read_addr_index.  */
14628
14629 struct dwarf2_read_addr_index_data
14630 {
14631   ULONGEST addr_base;
14632   int addr_size;
14633 };
14634
14635 /* die_reader_func for dwarf2_read_addr_index.  */
14636
14637 static void
14638 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14639                                gdb_byte *info_ptr,
14640                                struct die_info *comp_unit_die,
14641                                int has_children,
14642                                void *data)
14643 {
14644   struct dwarf2_cu *cu = reader->cu;
14645   struct dwarf2_read_addr_index_data *aidata =
14646     (struct dwarf2_read_addr_index_data *) data;
14647
14648   aidata->addr_base = cu->addr_base;
14649   aidata->addr_size = cu->header.addr_size;
14650 }
14651
14652 /* Given an index in .debug_addr, fetch the value.
14653    NOTE: This can be called during dwarf expression evaluation,
14654    long after the debug information has been read, and thus per_cu->cu
14655    may no longer exist.  */
14656
14657 CORE_ADDR
14658 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14659                         unsigned int addr_index)
14660 {
14661   struct objfile *objfile = per_cu->objfile;
14662   struct dwarf2_cu *cu = per_cu->cu;
14663   ULONGEST addr_base;
14664   int addr_size;
14665
14666   /* This is intended to be called from outside this file.  */
14667   dw2_setup (objfile);
14668
14669   /* We need addr_base and addr_size.
14670      If we don't have PER_CU->cu, we have to get it.
14671      Nasty, but the alternative is storing the needed info in PER_CU,
14672      which at this point doesn't seem justified: it's not clear how frequently
14673      it would get used and it would increase the size of every PER_CU.
14674      Entry points like dwarf2_per_cu_addr_size do a similar thing
14675      so we're not in uncharted territory here.
14676      Alas we need to be a bit more complicated as addr_base is contained
14677      in the DIE.
14678
14679      We don't need to read the entire CU(/TU).
14680      We just need the header and top level die.
14681
14682      IWBN to use the aging mechanism to let us lazily later discard the CU.
14683      For now we skip this optimization.  */
14684
14685   if (cu != NULL)
14686     {
14687       addr_base = cu->addr_base;
14688       addr_size = cu->header.addr_size;
14689     }
14690   else
14691     {
14692       struct dwarf2_read_addr_index_data aidata;
14693
14694       /* Note: We can't use init_cutu_and_read_dies_simple here,
14695          we need addr_base.  */
14696       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14697                                dwarf2_read_addr_index_reader, &aidata);
14698       addr_base = aidata.addr_base;
14699       addr_size = aidata.addr_size;
14700     }
14701
14702   return read_addr_index_1 (addr_index, addr_base, addr_size);
14703 }
14704
14705 /* Given a DW_AT_str_index, fetch the string.  */
14706
14707 static char *
14708 read_str_index (const struct die_reader_specs *reader,
14709                 struct dwarf2_cu *cu, ULONGEST str_index)
14710 {
14711   struct objfile *objfile = dwarf2_per_objfile->objfile;
14712   const char *dwo_name = objfile->name;
14713   bfd *abfd = objfile->obfd;
14714   struct dwo_sections *sections = &reader->dwo_file->sections;
14715   gdb_byte *info_ptr;
14716   ULONGEST str_offset;
14717
14718   dwarf2_read_section (objfile, &sections->str);
14719   dwarf2_read_section (objfile, &sections->str_offsets);
14720   if (sections->str.buffer == NULL)
14721     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14722              " in CU at offset 0x%lx [in module %s]"),
14723            (long) cu->header.offset.sect_off, dwo_name);
14724   if (sections->str_offsets.buffer == NULL)
14725     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14726              " in CU at offset 0x%lx [in module %s]"),
14727            (long) cu->header.offset.sect_off, dwo_name);
14728   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14729     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14730              " section in CU at offset 0x%lx [in module %s]"),
14731            (long) cu->header.offset.sect_off, dwo_name);
14732   info_ptr = (sections->str_offsets.buffer
14733               + str_index * cu->header.offset_size);
14734   if (cu->header.offset_size == 4)
14735     str_offset = bfd_get_32 (abfd, info_ptr);
14736   else
14737     str_offset = bfd_get_64 (abfd, info_ptr);
14738   if (str_offset >= sections->str.size)
14739     error (_("Offset from DW_FORM_str_index pointing outside of"
14740              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14741            (long) cu->header.offset.sect_off, dwo_name);
14742   return (char *) (sections->str.buffer + str_offset);
14743 }
14744
14745 /* Return the length of an LEB128 number in BUF.  */
14746
14747 static int
14748 leb128_size (const gdb_byte *buf)
14749 {
14750   const gdb_byte *begin = buf;
14751   gdb_byte byte;
14752
14753   while (1)
14754     {
14755       byte = *buf++;
14756       if ((byte & 128) == 0)
14757         return buf - begin;
14758     }
14759 }
14760
14761 static void
14762 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14763 {
14764   switch (lang)
14765     {
14766     case DW_LANG_C89:
14767     case DW_LANG_C99:
14768     case DW_LANG_C:
14769       cu->language = language_c;
14770       break;
14771     case DW_LANG_C_plus_plus:
14772       cu->language = language_cplus;
14773       break;
14774     case DW_LANG_D:
14775       cu->language = language_d;
14776       break;
14777     case DW_LANG_Fortran77:
14778     case DW_LANG_Fortran90:
14779     case DW_LANG_Fortran95:
14780       cu->language = language_fortran;
14781       break;
14782     case DW_LANG_Go:
14783       cu->language = language_go;
14784       break;
14785     case DW_LANG_Mips_Assembler:
14786       cu->language = language_asm;
14787       break;
14788     case DW_LANG_Java:
14789       cu->language = language_java;
14790       break;
14791     case DW_LANG_Ada83:
14792     case DW_LANG_Ada95:
14793       cu->language = language_ada;
14794       break;
14795     case DW_LANG_Modula2:
14796       cu->language = language_m2;
14797       break;
14798     case DW_LANG_Pascal83:
14799       cu->language = language_pascal;
14800       break;
14801     case DW_LANG_ObjC:
14802       cu->language = language_objc;
14803       break;
14804     case DW_LANG_Cobol74:
14805     case DW_LANG_Cobol85:
14806     default:
14807       cu->language = language_minimal;
14808       break;
14809     }
14810   cu->language_defn = language_def (cu->language);
14811 }
14812
14813 /* Return the named attribute or NULL if not there.  */
14814
14815 static struct attribute *
14816 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
14817 {
14818   for (;;)
14819     {
14820       unsigned int i;
14821       struct attribute *spec = NULL;
14822
14823       for (i = 0; i < die->num_attrs; ++i)
14824         {
14825           if (die->attrs[i].name == name)
14826             return &die->attrs[i];
14827           if (die->attrs[i].name == DW_AT_specification
14828               || die->attrs[i].name == DW_AT_abstract_origin)
14829             spec = &die->attrs[i];
14830         }
14831
14832       if (!spec)
14833         break;
14834
14835       die = follow_die_ref (die, spec, &cu);
14836     }
14837
14838   return NULL;
14839 }
14840
14841 /* Return the named attribute or NULL if not there,
14842    but do not follow DW_AT_specification, etc.
14843    This is for use in contexts where we're reading .debug_types dies.
14844    Following DW_AT_specification, DW_AT_abstract_origin will take us
14845    back up the chain, and we want to go down.  */
14846
14847 static struct attribute *
14848 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
14849 {
14850   unsigned int i;
14851
14852   for (i = 0; i < die->num_attrs; ++i)
14853     if (die->attrs[i].name == name)
14854       return &die->attrs[i];
14855
14856   return NULL;
14857 }
14858
14859 /* Return non-zero iff the attribute NAME is defined for the given DIE,
14860    and holds a non-zero value.  This function should only be used for
14861    DW_FORM_flag or DW_FORM_flag_present attributes.  */
14862
14863 static int
14864 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
14865 {
14866   struct attribute *attr = dwarf2_attr (die, name, cu);
14867
14868   return (attr && DW_UNSND (attr));
14869 }
14870
14871 static int
14872 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
14873 {
14874   /* A DIE is a declaration if it has a DW_AT_declaration attribute
14875      which value is non-zero.  However, we have to be careful with
14876      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
14877      (via dwarf2_flag_true_p) follows this attribute.  So we may
14878      end up accidently finding a declaration attribute that belongs
14879      to a different DIE referenced by the specification attribute,
14880      even though the given DIE does not have a declaration attribute.  */
14881   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
14882           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
14883 }
14884
14885 /* Return the die giving the specification for DIE, if there is
14886    one.  *SPEC_CU is the CU containing DIE on input, and the CU
14887    containing the return value on output.  If there is no
14888    specification, but there is an abstract origin, that is
14889    returned.  */
14890
14891 static struct die_info *
14892 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
14893 {
14894   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
14895                                              *spec_cu);
14896
14897   if (spec_attr == NULL)
14898     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
14899
14900   if (spec_attr == NULL)
14901     return NULL;
14902   else
14903     return follow_die_ref (die, spec_attr, spec_cu);
14904 }
14905
14906 /* Free the line_header structure *LH, and any arrays and strings it
14907    refers to.
14908    NOTE: This is also used as a "cleanup" function.  */
14909
14910 static void
14911 free_line_header (struct line_header *lh)
14912 {
14913   if (lh->standard_opcode_lengths)
14914     xfree (lh->standard_opcode_lengths);
14915
14916   /* Remember that all the lh->file_names[i].name pointers are
14917      pointers into debug_line_buffer, and don't need to be freed.  */
14918   if (lh->file_names)
14919     xfree (lh->file_names);
14920
14921   /* Similarly for the include directory names.  */
14922   if (lh->include_dirs)
14923     xfree (lh->include_dirs);
14924
14925   xfree (lh);
14926 }
14927
14928 /* Add an entry to LH's include directory table.  */
14929
14930 static void
14931 add_include_dir (struct line_header *lh, char *include_dir)
14932 {
14933   /* Grow the array if necessary.  */
14934   if (lh->include_dirs_size == 0)
14935     {
14936       lh->include_dirs_size = 1; /* for testing */
14937       lh->include_dirs = xmalloc (lh->include_dirs_size
14938                                   * sizeof (*lh->include_dirs));
14939     }
14940   else if (lh->num_include_dirs >= lh->include_dirs_size)
14941     {
14942       lh->include_dirs_size *= 2;
14943       lh->include_dirs = xrealloc (lh->include_dirs,
14944                                    (lh->include_dirs_size
14945                                     * sizeof (*lh->include_dirs)));
14946     }
14947
14948   lh->include_dirs[lh->num_include_dirs++] = include_dir;
14949 }
14950
14951 /* Add an entry to LH's file name table.  */
14952
14953 static void
14954 add_file_name (struct line_header *lh,
14955                char *name,
14956                unsigned int dir_index,
14957                unsigned int mod_time,
14958                unsigned int length)
14959 {
14960   struct file_entry *fe;
14961
14962   /* Grow the array if necessary.  */
14963   if (lh->file_names_size == 0)
14964     {
14965       lh->file_names_size = 1; /* for testing */
14966       lh->file_names = xmalloc (lh->file_names_size
14967                                 * sizeof (*lh->file_names));
14968     }
14969   else if (lh->num_file_names >= lh->file_names_size)
14970     {
14971       lh->file_names_size *= 2;
14972       lh->file_names = xrealloc (lh->file_names,
14973                                  (lh->file_names_size
14974                                   * sizeof (*lh->file_names)));
14975     }
14976
14977   fe = &lh->file_names[lh->num_file_names++];
14978   fe->name = name;
14979   fe->dir_index = dir_index;
14980   fe->mod_time = mod_time;
14981   fe->length = length;
14982   fe->included_p = 0;
14983   fe->symtab = NULL;
14984 }
14985
14986 /* A convenience function to find the proper .debug_line section for a
14987    CU.  */
14988
14989 static struct dwarf2_section_info *
14990 get_debug_line_section (struct dwarf2_cu *cu)
14991 {
14992   struct dwarf2_section_info *section;
14993
14994   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
14995      DWO file.  */
14996   if (cu->dwo_unit && cu->per_cu->is_debug_types)
14997     section = &cu->dwo_unit->dwo_file->sections.line;
14998   else if (cu->per_cu->is_dwz)
14999     {
15000       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15001
15002       section = &dwz->line;
15003     }
15004   else
15005     section = &dwarf2_per_objfile->line;
15006
15007   return section;
15008 }
15009
15010 /* Read the statement program header starting at OFFSET in
15011    .debug_line, or .debug_line.dwo.  Return a pointer
15012    to a struct line_header, allocated using xmalloc.
15013
15014    NOTE: the strings in the include directory and file name tables of
15015    the returned object point into the dwarf line section buffer,
15016    and must not be freed.  */
15017
15018 static struct line_header *
15019 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15020 {
15021   struct cleanup *back_to;
15022   struct line_header *lh;
15023   gdb_byte *line_ptr;
15024   unsigned int bytes_read, offset_size;
15025   int i;
15026   char *cur_dir, *cur_file;
15027   struct dwarf2_section_info *section;
15028   bfd *abfd;
15029
15030   section = get_debug_line_section (cu);
15031   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15032   if (section->buffer == NULL)
15033     {
15034       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15035         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15036       else
15037         complaint (&symfile_complaints, _("missing .debug_line section"));
15038       return 0;
15039     }
15040
15041   /* We can't do this until we know the section is non-empty.
15042      Only then do we know we have such a section.  */
15043   abfd = section->asection->owner;
15044
15045   /* Make sure that at least there's room for the total_length field.
15046      That could be 12 bytes long, but we're just going to fudge that.  */
15047   if (offset + 4 >= section->size)
15048     {
15049       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15050       return 0;
15051     }
15052
15053   lh = xmalloc (sizeof (*lh));
15054   memset (lh, 0, sizeof (*lh));
15055   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15056                           (void *) lh);
15057
15058   line_ptr = section->buffer + offset;
15059
15060   /* Read in the header.  */
15061   lh->total_length =
15062     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15063                                             &bytes_read, &offset_size);
15064   line_ptr += bytes_read;
15065   if (line_ptr + lh->total_length > (section->buffer + section->size))
15066     {
15067       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15068       return 0;
15069     }
15070   lh->statement_program_end = line_ptr + lh->total_length;
15071   lh->version = read_2_bytes (abfd, line_ptr);
15072   line_ptr += 2;
15073   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15074   line_ptr += offset_size;
15075   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15076   line_ptr += 1;
15077   if (lh->version >= 4)
15078     {
15079       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15080       line_ptr += 1;
15081     }
15082   else
15083     lh->maximum_ops_per_instruction = 1;
15084
15085   if (lh->maximum_ops_per_instruction == 0)
15086     {
15087       lh->maximum_ops_per_instruction = 1;
15088       complaint (&symfile_complaints,
15089                  _("invalid maximum_ops_per_instruction "
15090                    "in `.debug_line' section"));
15091     }
15092
15093   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15094   line_ptr += 1;
15095   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15096   line_ptr += 1;
15097   lh->line_range = read_1_byte (abfd, line_ptr);
15098   line_ptr += 1;
15099   lh->opcode_base = read_1_byte (abfd, line_ptr);
15100   line_ptr += 1;
15101   lh->standard_opcode_lengths
15102     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15103
15104   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15105   for (i = 1; i < lh->opcode_base; ++i)
15106     {
15107       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15108       line_ptr += 1;
15109     }
15110
15111   /* Read directory table.  */
15112   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15113     {
15114       line_ptr += bytes_read;
15115       add_include_dir (lh, cur_dir);
15116     }
15117   line_ptr += bytes_read;
15118
15119   /* Read file name table.  */
15120   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15121     {
15122       unsigned int dir_index, mod_time, length;
15123
15124       line_ptr += bytes_read;
15125       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15126       line_ptr += bytes_read;
15127       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15128       line_ptr += bytes_read;
15129       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15130       line_ptr += bytes_read;
15131
15132       add_file_name (lh, cur_file, dir_index, mod_time, length);
15133     }
15134   line_ptr += bytes_read;
15135   lh->statement_program_start = line_ptr;
15136
15137   if (line_ptr > (section->buffer + section->size))
15138     complaint (&symfile_complaints,
15139                _("line number info header doesn't "
15140                  "fit in `.debug_line' section"));
15141
15142   discard_cleanups (back_to);
15143   return lh;
15144 }
15145
15146 /* Subroutine of dwarf_decode_lines to simplify it.
15147    Return the file name of the psymtab for included file FILE_INDEX
15148    in line header LH of PST.
15149    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15150    If space for the result is malloc'd, it will be freed by a cleanup.
15151    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15152
15153    The function creates dangling cleanup registration.  */
15154
15155 static char *
15156 psymtab_include_file_name (const struct line_header *lh, int file_index,
15157                            const struct partial_symtab *pst,
15158                            const char *comp_dir)
15159 {
15160   const struct file_entry fe = lh->file_names [file_index];
15161   char *include_name = fe.name;
15162   char *include_name_to_compare = include_name;
15163   char *dir_name = NULL;
15164   const char *pst_filename;
15165   char *copied_name = NULL;
15166   int file_is_pst;
15167
15168   if (fe.dir_index)
15169     dir_name = lh->include_dirs[fe.dir_index - 1];
15170
15171   if (!IS_ABSOLUTE_PATH (include_name)
15172       && (dir_name != NULL || comp_dir != NULL))
15173     {
15174       /* Avoid creating a duplicate psymtab for PST.
15175          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15176          Before we do the comparison, however, we need to account
15177          for DIR_NAME and COMP_DIR.
15178          First prepend dir_name (if non-NULL).  If we still don't
15179          have an absolute path prepend comp_dir (if non-NULL).
15180          However, the directory we record in the include-file's
15181          psymtab does not contain COMP_DIR (to match the
15182          corresponding symtab(s)).
15183
15184          Example:
15185
15186          bash$ cd /tmp
15187          bash$ gcc -g ./hello.c
15188          include_name = "hello.c"
15189          dir_name = "."
15190          DW_AT_comp_dir = comp_dir = "/tmp"
15191          DW_AT_name = "./hello.c"  */
15192
15193       if (dir_name != NULL)
15194         {
15195           include_name = concat (dir_name, SLASH_STRING,
15196                                  include_name, (char *)NULL);
15197           include_name_to_compare = include_name;
15198           make_cleanup (xfree, include_name);
15199         }
15200       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15201         {
15202           include_name_to_compare = concat (comp_dir, SLASH_STRING,
15203                                             include_name, (char *)NULL);
15204         }
15205     }
15206
15207   pst_filename = pst->filename;
15208   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15209     {
15210       copied_name = concat (pst->dirname, SLASH_STRING,
15211                             pst_filename, (char *)NULL);
15212       pst_filename = copied_name;
15213     }
15214
15215   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15216
15217   if (include_name_to_compare != include_name)
15218     xfree (include_name_to_compare);
15219   if (copied_name != NULL)
15220     xfree (copied_name);
15221
15222   if (file_is_pst)
15223     return NULL;
15224   return include_name;
15225 }
15226
15227 /* Ignore this record_line request.  */
15228
15229 static void
15230 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15231 {
15232   return;
15233 }
15234
15235 /* Subroutine of dwarf_decode_lines to simplify it.
15236    Process the line number information in LH.  */
15237
15238 static void
15239 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15240                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15241 {
15242   gdb_byte *line_ptr, *extended_end;
15243   gdb_byte *line_end;
15244   unsigned int bytes_read, extended_len;
15245   unsigned char op_code, extended_op, adj_opcode;
15246   CORE_ADDR baseaddr;
15247   struct objfile *objfile = cu->objfile;
15248   bfd *abfd = objfile->obfd;
15249   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15250   const int decode_for_pst_p = (pst != NULL);
15251   struct subfile *last_subfile = NULL;
15252   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15253     = record_line;
15254
15255   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15256
15257   line_ptr = lh->statement_program_start;
15258   line_end = lh->statement_program_end;
15259
15260   /* Read the statement sequences until there's nothing left.  */
15261   while (line_ptr < line_end)
15262     {
15263       /* state machine registers  */
15264       CORE_ADDR address = 0;
15265       unsigned int file = 1;
15266       unsigned int line = 1;
15267       unsigned int column = 0;
15268       int is_stmt = lh->default_is_stmt;
15269       int basic_block = 0;
15270       int end_sequence = 0;
15271       CORE_ADDR addr;
15272       unsigned char op_index = 0;
15273
15274       if (!decode_for_pst_p && lh->num_file_names >= file)
15275         {
15276           /* Start a subfile for the current file of the state machine.  */
15277           /* lh->include_dirs and lh->file_names are 0-based, but the
15278              directory and file name numbers in the statement program
15279              are 1-based.  */
15280           struct file_entry *fe = &lh->file_names[file - 1];
15281           char *dir = NULL;
15282
15283           if (fe->dir_index)
15284             dir = lh->include_dirs[fe->dir_index - 1];
15285
15286           dwarf2_start_subfile (fe->name, dir, comp_dir);
15287         }
15288
15289       /* Decode the table.  */
15290       while (!end_sequence)
15291         {
15292           op_code = read_1_byte (abfd, line_ptr);
15293           line_ptr += 1;
15294           if (line_ptr > line_end)
15295             {
15296               dwarf2_debug_line_missing_end_sequence_complaint ();
15297               break;
15298             }
15299
15300           if (op_code >= lh->opcode_base)
15301             {
15302               /* Special operand.  */
15303               adj_opcode = op_code - lh->opcode_base;
15304               address += (((op_index + (adj_opcode / lh->line_range))
15305                            / lh->maximum_ops_per_instruction)
15306                           * lh->minimum_instruction_length);
15307               op_index = ((op_index + (adj_opcode / lh->line_range))
15308                           % lh->maximum_ops_per_instruction);
15309               line += lh->line_base + (adj_opcode % lh->line_range);
15310               if (lh->num_file_names < file || file == 0)
15311                 dwarf2_debug_line_missing_file_complaint ();
15312               /* For now we ignore lines not starting on an
15313                  instruction boundary.  */
15314               else if (op_index == 0)
15315                 {
15316                   lh->file_names[file - 1].included_p = 1;
15317                   if (!decode_for_pst_p && is_stmt)
15318                     {
15319                       if (last_subfile != current_subfile)
15320                         {
15321                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15322                           if (last_subfile)
15323                             (*p_record_line) (last_subfile, 0, addr);
15324                           last_subfile = current_subfile;
15325                         }
15326                       /* Append row to matrix using current values.  */
15327                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15328                       (*p_record_line) (current_subfile, line, addr);
15329                     }
15330                 }
15331               basic_block = 0;
15332             }
15333           else switch (op_code)
15334             {
15335             case DW_LNS_extended_op:
15336               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15337                                                    &bytes_read);
15338               line_ptr += bytes_read;
15339               extended_end = line_ptr + extended_len;
15340               extended_op = read_1_byte (abfd, line_ptr);
15341               line_ptr += 1;
15342               switch (extended_op)
15343                 {
15344                 case DW_LNE_end_sequence:
15345                   p_record_line = record_line;
15346                   end_sequence = 1;
15347                   break;
15348                 case DW_LNE_set_address:
15349                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15350
15351                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15352                     {
15353                       /* This line table is for a function which has been
15354                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15355
15356                       long line_offset
15357                         = line_ptr - get_debug_line_section (cu)->buffer;
15358
15359                       complaint (&symfile_complaints,
15360                                  _(".debug_line address at offset 0x%lx is 0 "
15361                                    "[in module %s]"),
15362                                  line_offset, objfile->name);
15363                       p_record_line = noop_record_line;
15364                     }
15365
15366                   op_index = 0;
15367                   line_ptr += bytes_read;
15368                   address += baseaddr;
15369                   break;
15370                 case DW_LNE_define_file:
15371                   {
15372                     char *cur_file;
15373                     unsigned int dir_index, mod_time, length;
15374
15375                     cur_file = read_direct_string (abfd, line_ptr,
15376                                                    &bytes_read);
15377                     line_ptr += bytes_read;
15378                     dir_index =
15379                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15380                     line_ptr += bytes_read;
15381                     mod_time =
15382                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15383                     line_ptr += bytes_read;
15384                     length =
15385                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15386                     line_ptr += bytes_read;
15387                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15388                   }
15389                   break;
15390                 case DW_LNE_set_discriminator:
15391                   /* The discriminator is not interesting to the debugger;
15392                      just ignore it.  */
15393                   line_ptr = extended_end;
15394                   break;
15395                 default:
15396                   complaint (&symfile_complaints,
15397                              _("mangled .debug_line section"));
15398                   return;
15399                 }
15400               /* Make sure that we parsed the extended op correctly.  If e.g.
15401                  we expected a different address size than the producer used,
15402                  we may have read the wrong number of bytes.  */
15403               if (line_ptr != extended_end)
15404                 {
15405                   complaint (&symfile_complaints,
15406                              _("mangled .debug_line section"));
15407                   return;
15408                 }
15409               break;
15410             case DW_LNS_copy:
15411               if (lh->num_file_names < file || file == 0)
15412                 dwarf2_debug_line_missing_file_complaint ();
15413               else
15414                 {
15415                   lh->file_names[file - 1].included_p = 1;
15416                   if (!decode_for_pst_p && is_stmt)
15417                     {
15418                       if (last_subfile != current_subfile)
15419                         {
15420                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15421                           if (last_subfile)
15422                             (*p_record_line) (last_subfile, 0, addr);
15423                           last_subfile = current_subfile;
15424                         }
15425                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15426                       (*p_record_line) (current_subfile, line, addr);
15427                     }
15428                 }
15429               basic_block = 0;
15430               break;
15431             case DW_LNS_advance_pc:
15432               {
15433                 CORE_ADDR adjust
15434                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15435
15436                 address += (((op_index + adjust)
15437                              / lh->maximum_ops_per_instruction)
15438                             * lh->minimum_instruction_length);
15439                 op_index = ((op_index + adjust)
15440                             % lh->maximum_ops_per_instruction);
15441                 line_ptr += bytes_read;
15442               }
15443               break;
15444             case DW_LNS_advance_line:
15445               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15446               line_ptr += bytes_read;
15447               break;
15448             case DW_LNS_set_file:
15449               {
15450                 /* The arrays lh->include_dirs and lh->file_names are
15451                    0-based, but the directory and file name numbers in
15452                    the statement program are 1-based.  */
15453                 struct file_entry *fe;
15454                 char *dir = NULL;
15455
15456                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15457                 line_ptr += bytes_read;
15458                 if (lh->num_file_names < file || file == 0)
15459                   dwarf2_debug_line_missing_file_complaint ();
15460                 else
15461                   {
15462                     fe = &lh->file_names[file - 1];
15463                     if (fe->dir_index)
15464                       dir = lh->include_dirs[fe->dir_index - 1];
15465                     if (!decode_for_pst_p)
15466                       {
15467                         last_subfile = current_subfile;
15468                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15469                       }
15470                   }
15471               }
15472               break;
15473             case DW_LNS_set_column:
15474               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15475               line_ptr += bytes_read;
15476               break;
15477             case DW_LNS_negate_stmt:
15478               is_stmt = (!is_stmt);
15479               break;
15480             case DW_LNS_set_basic_block:
15481               basic_block = 1;
15482               break;
15483             /* Add to the address register of the state machine the
15484                address increment value corresponding to special opcode
15485                255.  I.e., this value is scaled by the minimum
15486                instruction length since special opcode 255 would have
15487                scaled the increment.  */
15488             case DW_LNS_const_add_pc:
15489               {
15490                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15491
15492                 address += (((op_index + adjust)
15493                              / lh->maximum_ops_per_instruction)
15494                             * lh->minimum_instruction_length);
15495                 op_index = ((op_index + adjust)
15496                             % lh->maximum_ops_per_instruction);
15497               }
15498               break;
15499             case DW_LNS_fixed_advance_pc:
15500               address += read_2_bytes (abfd, line_ptr);
15501               op_index = 0;
15502               line_ptr += 2;
15503               break;
15504             default:
15505               {
15506                 /* Unknown standard opcode, ignore it.  */
15507                 int i;
15508
15509                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15510                   {
15511                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15512                     line_ptr += bytes_read;
15513                   }
15514               }
15515             }
15516         }
15517       if (lh->num_file_names < file || file == 0)
15518         dwarf2_debug_line_missing_file_complaint ();
15519       else
15520         {
15521           lh->file_names[file - 1].included_p = 1;
15522           if (!decode_for_pst_p)
15523             {
15524               addr = gdbarch_addr_bits_remove (gdbarch, address);
15525               (*p_record_line) (current_subfile, 0, addr);
15526             }
15527         }
15528     }
15529 }
15530
15531 /* Decode the Line Number Program (LNP) for the given line_header
15532    structure and CU.  The actual information extracted and the type
15533    of structures created from the LNP depends on the value of PST.
15534
15535    1. If PST is NULL, then this procedure uses the data from the program
15536       to create all necessary symbol tables, and their linetables.
15537
15538    2. If PST is not NULL, this procedure reads the program to determine
15539       the list of files included by the unit represented by PST, and
15540       builds all the associated partial symbol tables.
15541
15542    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15543    It is used for relative paths in the line table.
15544    NOTE: When processing partial symtabs (pst != NULL),
15545    comp_dir == pst->dirname.
15546
15547    NOTE: It is important that psymtabs have the same file name (via strcmp)
15548    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15549    symtab we don't use it in the name of the psymtabs we create.
15550    E.g. expand_line_sal requires this when finding psymtabs to expand.
15551    A good testcase for this is mb-inline.exp.  */
15552
15553 static void
15554 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15555                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15556                     int want_line_info)
15557 {
15558   struct objfile *objfile = cu->objfile;
15559   const int decode_for_pst_p = (pst != NULL);
15560   struct subfile *first_subfile = current_subfile;
15561
15562   if (want_line_info)
15563     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15564
15565   if (decode_for_pst_p)
15566     {
15567       int file_index;
15568
15569       /* Now that we're done scanning the Line Header Program, we can
15570          create the psymtab of each included file.  */
15571       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15572         if (lh->file_names[file_index].included_p == 1)
15573           {
15574             char *include_name =
15575               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15576             if (include_name != NULL)
15577               dwarf2_create_include_psymtab (include_name, pst, objfile);
15578           }
15579     }
15580   else
15581     {
15582       /* Make sure a symtab is created for every file, even files
15583          which contain only variables (i.e. no code with associated
15584          line numbers).  */
15585       int i;
15586
15587       for (i = 0; i < lh->num_file_names; i++)
15588         {
15589           char *dir = NULL;
15590           struct file_entry *fe;
15591
15592           fe = &lh->file_names[i];
15593           if (fe->dir_index)
15594             dir = lh->include_dirs[fe->dir_index - 1];
15595           dwarf2_start_subfile (fe->name, dir, comp_dir);
15596
15597           /* Skip the main file; we don't need it, and it must be
15598              allocated last, so that it will show up before the
15599              non-primary symtabs in the objfile's symtab list.  */
15600           if (current_subfile == first_subfile)
15601             continue;
15602
15603           if (current_subfile->symtab == NULL)
15604             current_subfile->symtab = allocate_symtab (current_subfile->name,
15605                                                        objfile);
15606           fe->symtab = current_subfile->symtab;
15607         }
15608     }
15609 }
15610
15611 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15612    DIRNAME the name of the source directory which contains FILENAME
15613    or NULL if not known.  COMP_DIR is the compilation directory for the
15614    linetable's compilation unit or NULL if not known.
15615    This routine tries to keep line numbers from identical absolute and
15616    relative file names in a common subfile.
15617
15618    Using the `list' example from the GDB testsuite, which resides in
15619    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15620    of /srcdir/list0.c yields the following debugging information for list0.c:
15621
15622    DW_AT_name:          /srcdir/list0.c
15623    DW_AT_comp_dir:              /compdir
15624    files.files[0].name: list0.h
15625    files.files[0].dir:  /srcdir
15626    files.files[1].name: list0.c
15627    files.files[1].dir:  /srcdir
15628
15629    The line number information for list0.c has to end up in a single
15630    subfile, so that `break /srcdir/list0.c:1' works as expected.
15631    start_subfile will ensure that this happens provided that we pass the
15632    concatenation of files.files[1].dir and files.files[1].name as the
15633    subfile's name.  */
15634
15635 static void
15636 dwarf2_start_subfile (char *filename, const char *dirname,
15637                       const char *comp_dir)
15638 {
15639   char *fullname;
15640
15641   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15642      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15643      second argument to start_subfile.  To be consistent, we do the
15644      same here.  In order not to lose the line information directory,
15645      we concatenate it to the filename when it makes sense.
15646      Note that the Dwarf3 standard says (speaking of filenames in line
15647      information): ``The directory index is ignored for file names
15648      that represent full path names''.  Thus ignoring dirname in the
15649      `else' branch below isn't an issue.  */
15650
15651   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15652     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15653   else
15654     fullname = filename;
15655
15656   start_subfile (fullname, comp_dir);
15657
15658   if (fullname != filename)
15659     xfree (fullname);
15660 }
15661
15662 /* Start a symtab for DWARF.
15663    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15664
15665 static void
15666 dwarf2_start_symtab (struct dwarf2_cu *cu,
15667                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15668 {
15669   start_symtab (name, comp_dir, low_pc);
15670   record_debugformat ("DWARF 2");
15671   record_producer (cu->producer);
15672
15673   /* We assume that we're processing GCC output.  */
15674   processing_gcc_compilation = 2;
15675
15676   cu->processing_has_namespace_info = 0;
15677 }
15678
15679 static void
15680 var_decode_location (struct attribute *attr, struct symbol *sym,
15681                      struct dwarf2_cu *cu)
15682 {
15683   struct objfile *objfile = cu->objfile;
15684   struct comp_unit_head *cu_header = &cu->header;
15685
15686   /* NOTE drow/2003-01-30: There used to be a comment and some special
15687      code here to turn a symbol with DW_AT_external and a
15688      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15689      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15690      with some versions of binutils) where shared libraries could have
15691      relocations against symbols in their debug information - the
15692      minimal symbol would have the right address, but the debug info
15693      would not.  It's no longer necessary, because we will explicitly
15694      apply relocations when we read in the debug information now.  */
15695
15696   /* A DW_AT_location attribute with no contents indicates that a
15697      variable has been optimized away.  */
15698   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15699     {
15700       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15701       return;
15702     }
15703
15704   /* Handle one degenerate form of location expression specially, to
15705      preserve GDB's previous behavior when section offsets are
15706      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15707      then mark this symbol as LOC_STATIC.  */
15708
15709   if (attr_form_is_block (attr)
15710       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15711            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15712           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15713               && (DW_BLOCK (attr)->size
15714                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15715     {
15716       unsigned int dummy;
15717
15718       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15719         SYMBOL_VALUE_ADDRESS (sym) =
15720           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15721       else
15722         SYMBOL_VALUE_ADDRESS (sym) =
15723           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15724       SYMBOL_CLASS (sym) = LOC_STATIC;
15725       fixup_symbol_section (sym, objfile);
15726       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15727                                               SYMBOL_SECTION (sym));
15728       return;
15729     }
15730
15731   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15732      expression evaluator, and use LOC_COMPUTED only when necessary
15733      (i.e. when the value of a register or memory location is
15734      referenced, or a thread-local block, etc.).  Then again, it might
15735      not be worthwhile.  I'm assuming that it isn't unless performance
15736      or memory numbers show me otherwise.  */
15737
15738   dwarf2_symbol_mark_computed (attr, sym, cu);
15739   SYMBOL_CLASS (sym) = LOC_COMPUTED;
15740
15741   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
15742     cu->has_loclist = 1;
15743 }
15744
15745 /* Given a pointer to a DWARF information entry, figure out if we need
15746    to make a symbol table entry for it, and if so, create a new entry
15747    and return a pointer to it.
15748    If TYPE is NULL, determine symbol type from the die, otherwise
15749    used the passed type.
15750    If SPACE is not NULL, use it to hold the new symbol.  If it is
15751    NULL, allocate a new symbol on the objfile's obstack.  */
15752
15753 static struct symbol *
15754 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15755                  struct symbol *space)
15756 {
15757   struct objfile *objfile = cu->objfile;
15758   struct symbol *sym = NULL;
15759   const char *name;
15760   struct attribute *attr = NULL;
15761   struct attribute *attr2 = NULL;
15762   CORE_ADDR baseaddr;
15763   struct pending **list_to_add = NULL;
15764
15765   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15766
15767   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15768
15769   name = dwarf2_name (die, cu);
15770   if (name)
15771     {
15772       const char *linkagename;
15773       int suppress_add = 0;
15774
15775       if (space)
15776         sym = space;
15777       else
15778         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
15779       OBJSTAT (objfile, n_syms++);
15780
15781       /* Cache this symbol's name and the name's demangled form (if any).  */
15782       SYMBOL_SET_LANGUAGE (sym, cu->language);
15783       linkagename = dwarf2_physname (name, die, cu);
15784       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15785
15786       /* Fortran does not have mangling standard and the mangling does differ
15787          between gfortran, iFort etc.  */
15788       if (cu->language == language_fortran
15789           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15790         symbol_set_demangled_name (&(sym->ginfo),
15791                                    dwarf2_full_name (name, die, cu),
15792                                    NULL);
15793
15794       /* Default assumptions.
15795          Use the passed type or decode it from the die.  */
15796       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15797       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15798       if (type != NULL)
15799         SYMBOL_TYPE (sym) = type;
15800       else
15801         SYMBOL_TYPE (sym) = die_type (die, cu);
15802       attr = dwarf2_attr (die,
15803                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15804                           cu);
15805       if (attr)
15806         {
15807           SYMBOL_LINE (sym) = DW_UNSND (attr);
15808         }
15809
15810       attr = dwarf2_attr (die,
15811                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
15812                           cu);
15813       if (attr)
15814         {
15815           int file_index = DW_UNSND (attr);
15816
15817           if (cu->line_header == NULL
15818               || file_index > cu->line_header->num_file_names)
15819             complaint (&symfile_complaints,
15820                        _("file index out of range"));
15821           else if (file_index > 0)
15822             {
15823               struct file_entry *fe;
15824
15825               fe = &cu->line_header->file_names[file_index - 1];
15826               SYMBOL_SYMTAB (sym) = fe->symtab;
15827             }
15828         }
15829
15830       switch (die->tag)
15831         {
15832         case DW_TAG_label:
15833           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15834           if (attr)
15835             {
15836               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
15837             }
15838           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
15839           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
15840           SYMBOL_CLASS (sym) = LOC_LABEL;
15841           add_symbol_to_list (sym, cu->list_in_scope);
15842           break;
15843         case DW_TAG_subprogram:
15844           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15845              finish_block.  */
15846           SYMBOL_CLASS (sym) = LOC_BLOCK;
15847           attr2 = dwarf2_attr (die, DW_AT_external, cu);
15848           if ((attr2 && (DW_UNSND (attr2) != 0))
15849               || cu->language == language_ada)
15850             {
15851               /* Subprograms marked external are stored as a global symbol.
15852                  Ada subprograms, whether marked external or not, are always
15853                  stored as a global symbol, because we want to be able to
15854                  access them globally.  For instance, we want to be able
15855                  to break on a nested subprogram without having to
15856                  specify the context.  */
15857               list_to_add = &global_symbols;
15858             }
15859           else
15860             {
15861               list_to_add = cu->list_in_scope;
15862             }
15863           break;
15864         case DW_TAG_inlined_subroutine:
15865           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15866              finish_block.  */
15867           SYMBOL_CLASS (sym) = LOC_BLOCK;
15868           SYMBOL_INLINED (sym) = 1;
15869           list_to_add = cu->list_in_scope;
15870           break;
15871         case DW_TAG_template_value_param:
15872           suppress_add = 1;
15873           /* Fall through.  */
15874         case DW_TAG_constant:
15875         case DW_TAG_variable:
15876         case DW_TAG_member:
15877           /* Compilation with minimal debug info may result in
15878              variables with missing type entries.  Change the
15879              misleading `void' type to something sensible.  */
15880           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
15881             SYMBOL_TYPE (sym)
15882               = objfile_type (objfile)->nodebug_data_symbol;
15883
15884           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15885           /* In the case of DW_TAG_member, we should only be called for
15886              static const members.  */
15887           if (die->tag == DW_TAG_member)
15888             {
15889               /* dwarf2_add_field uses die_is_declaration,
15890                  so we do the same.  */
15891               gdb_assert (die_is_declaration (die, cu));
15892               gdb_assert (attr);
15893             }
15894           if (attr)
15895             {
15896               dwarf2_const_value (attr, sym, cu);
15897               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15898               if (!suppress_add)
15899                 {
15900                   if (attr2 && (DW_UNSND (attr2) != 0))
15901                     list_to_add = &global_symbols;
15902                   else
15903                     list_to_add = cu->list_in_scope;
15904                 }
15905               break;
15906             }
15907           attr = dwarf2_attr (die, DW_AT_location, cu);
15908           if (attr)
15909             {
15910               var_decode_location (attr, sym, cu);
15911               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15912
15913               /* Fortran explicitly imports any global symbols to the local
15914                  scope by DW_TAG_common_block.  */
15915               if (cu->language == language_fortran && die->parent
15916                   && die->parent->tag == DW_TAG_common_block)
15917                 attr2 = NULL;
15918
15919               if (SYMBOL_CLASS (sym) == LOC_STATIC
15920                   && SYMBOL_VALUE_ADDRESS (sym) == 0
15921                   && !dwarf2_per_objfile->has_section_at_zero)
15922                 {
15923                   /* When a static variable is eliminated by the linker,
15924                      the corresponding debug information is not stripped
15925                      out, but the variable address is set to null;
15926                      do not add such variables into symbol table.  */
15927                 }
15928               else if (attr2 && (DW_UNSND (attr2) != 0))
15929                 {
15930                   /* Workaround gfortran PR debug/40040 - it uses
15931                      DW_AT_location for variables in -fPIC libraries which may
15932                      get overriden by other libraries/executable and get
15933                      a different address.  Resolve it by the minimal symbol
15934                      which may come from inferior's executable using copy
15935                      relocation.  Make this workaround only for gfortran as for
15936                      other compilers GDB cannot guess the minimal symbol
15937                      Fortran mangling kind.  */
15938                   if (cu->language == language_fortran && die->parent
15939                       && die->parent->tag == DW_TAG_module
15940                       && cu->producer
15941                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
15942                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15943
15944                   /* A variable with DW_AT_external is never static,
15945                      but it may be block-scoped.  */
15946                   list_to_add = (cu->list_in_scope == &file_symbols
15947                                  ? &global_symbols : cu->list_in_scope);
15948                 }
15949               else
15950                 list_to_add = cu->list_in_scope;
15951             }
15952           else
15953             {
15954               /* We do not know the address of this symbol.
15955                  If it is an external symbol and we have type information
15956                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
15957                  The address of the variable will then be determined from
15958                  the minimal symbol table whenever the variable is
15959                  referenced.  */
15960               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15961
15962               /* Fortran explicitly imports any global symbols to the local
15963                  scope by DW_TAG_common_block.  */
15964               if (cu->language == language_fortran && die->parent
15965                   && die->parent->tag == DW_TAG_common_block)
15966                 {
15967                   /* SYMBOL_CLASS doesn't matter here because
15968                      read_common_block is going to reset it.  */
15969                   if (!suppress_add)
15970                     list_to_add = cu->list_in_scope;
15971                 }
15972               else if (attr2 && (DW_UNSND (attr2) != 0)
15973                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
15974                 {
15975                   /* A variable with DW_AT_external is never static, but it
15976                      may be block-scoped.  */
15977                   list_to_add = (cu->list_in_scope == &file_symbols
15978                                  ? &global_symbols : cu->list_in_scope);
15979
15980                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15981                 }
15982               else if (!die_is_declaration (die, cu))
15983                 {
15984                   /* Use the default LOC_OPTIMIZED_OUT class.  */
15985                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
15986                   if (!suppress_add)
15987                     list_to_add = cu->list_in_scope;
15988                 }
15989             }
15990           break;
15991         case DW_TAG_formal_parameter:
15992           /* If we are inside a function, mark this as an argument.  If
15993              not, we might be looking at an argument to an inlined function
15994              when we do not have enough information to show inlined frames;
15995              pretend it's a local variable in that case so that the user can
15996              still see it.  */
15997           if (context_stack_depth > 0
15998               && context_stack[context_stack_depth - 1].name != NULL)
15999             SYMBOL_IS_ARGUMENT (sym) = 1;
16000           attr = dwarf2_attr (die, DW_AT_location, cu);
16001           if (attr)
16002             {
16003               var_decode_location (attr, sym, cu);
16004             }
16005           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16006           if (attr)
16007             {
16008               dwarf2_const_value (attr, sym, cu);
16009             }
16010
16011           list_to_add = cu->list_in_scope;
16012           break;
16013         case DW_TAG_unspecified_parameters:
16014           /* From varargs functions; gdb doesn't seem to have any
16015              interest in this information, so just ignore it for now.
16016              (FIXME?) */
16017           break;
16018         case DW_TAG_template_type_param:
16019           suppress_add = 1;
16020           /* Fall through.  */
16021         case DW_TAG_class_type:
16022         case DW_TAG_interface_type:
16023         case DW_TAG_structure_type:
16024         case DW_TAG_union_type:
16025         case DW_TAG_set_type:
16026         case DW_TAG_enumeration_type:
16027           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16028           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16029
16030           {
16031             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16032                really ever be static objects: otherwise, if you try
16033                to, say, break of a class's method and you're in a file
16034                which doesn't mention that class, it won't work unless
16035                the check for all static symbols in lookup_symbol_aux
16036                saves you.  See the OtherFileClass tests in
16037                gdb.c++/namespace.exp.  */
16038
16039             if (!suppress_add)
16040               {
16041                 list_to_add = (cu->list_in_scope == &file_symbols
16042                                && (cu->language == language_cplus
16043                                    || cu->language == language_java)
16044                                ? &global_symbols : cu->list_in_scope);
16045
16046                 /* The semantics of C++ state that "struct foo {
16047                    ... }" also defines a typedef for "foo".  A Java
16048                    class declaration also defines a typedef for the
16049                    class.  */
16050                 if (cu->language == language_cplus
16051                     || cu->language == language_java
16052                     || cu->language == language_ada)
16053                   {
16054                     /* The symbol's name is already allocated along
16055                        with this objfile, so we don't need to
16056                        duplicate it for the type.  */
16057                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16058                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16059                   }
16060               }
16061           }
16062           break;
16063         case DW_TAG_typedef:
16064           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16065           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16066           list_to_add = cu->list_in_scope;
16067           break;
16068         case DW_TAG_base_type:
16069         case DW_TAG_subrange_type:
16070           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16071           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16072           list_to_add = cu->list_in_scope;
16073           break;
16074         case DW_TAG_enumerator:
16075           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16076           if (attr)
16077             {
16078               dwarf2_const_value (attr, sym, cu);
16079             }
16080           {
16081             /* NOTE: carlton/2003-11-10: See comment above in the
16082                DW_TAG_class_type, etc. block.  */
16083
16084             list_to_add = (cu->list_in_scope == &file_symbols
16085                            && (cu->language == language_cplus
16086                                || cu->language == language_java)
16087                            ? &global_symbols : cu->list_in_scope);
16088           }
16089           break;
16090         case DW_TAG_namespace:
16091           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16092           list_to_add = &global_symbols;
16093           break;
16094         case DW_TAG_common_block:
16095           SYMBOL_CLASS (sym) = LOC_COMMON_BLOCK;
16096           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16097           add_symbol_to_list (sym, cu->list_in_scope);
16098           break;
16099         default:
16100           /* Not a tag we recognize.  Hopefully we aren't processing
16101              trash data, but since we must specifically ignore things
16102              we don't recognize, there is nothing else we should do at
16103              this point.  */
16104           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16105                      dwarf_tag_name (die->tag));
16106           break;
16107         }
16108
16109       if (suppress_add)
16110         {
16111           sym->hash_next = objfile->template_symbols;
16112           objfile->template_symbols = sym;
16113           list_to_add = NULL;
16114         }
16115
16116       if (list_to_add != NULL)
16117         add_symbol_to_list (sym, list_to_add);
16118
16119       /* For the benefit of old versions of GCC, check for anonymous
16120          namespaces based on the demangled name.  */
16121       if (!cu->processing_has_namespace_info
16122           && cu->language == language_cplus)
16123         cp_scan_for_anonymous_namespaces (sym, objfile);
16124     }
16125   return (sym);
16126 }
16127
16128 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16129
16130 static struct symbol *
16131 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16132 {
16133   return new_symbol_full (die, type, cu, NULL);
16134 }
16135
16136 /* Given an attr with a DW_FORM_dataN value in host byte order,
16137    zero-extend it as appropriate for the symbol's type.  The DWARF
16138    standard (v4) is not entirely clear about the meaning of using
16139    DW_FORM_dataN for a constant with a signed type, where the type is
16140    wider than the data.  The conclusion of a discussion on the DWARF
16141    list was that this is unspecified.  We choose to always zero-extend
16142    because that is the interpretation long in use by GCC.  */
16143
16144 static gdb_byte *
16145 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16146                          const char *name, struct obstack *obstack,
16147                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16148 {
16149   struct objfile *objfile = cu->objfile;
16150   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16151                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16152   LONGEST l = DW_UNSND (attr);
16153
16154   if (bits < sizeof (*value) * 8)
16155     {
16156       l &= ((LONGEST) 1 << bits) - 1;
16157       *value = l;
16158     }
16159   else if (bits == sizeof (*value) * 8)
16160     *value = l;
16161   else
16162     {
16163       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16164       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16165       return bytes;
16166     }
16167
16168   return NULL;
16169 }
16170
16171 /* Read a constant value from an attribute.  Either set *VALUE, or if
16172    the value does not fit in *VALUE, set *BYTES - either already
16173    allocated on the objfile obstack, or newly allocated on OBSTACK,
16174    or, set *BATON, if we translated the constant to a location
16175    expression.  */
16176
16177 static void
16178 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16179                          const char *name, struct obstack *obstack,
16180                          struct dwarf2_cu *cu,
16181                          LONGEST *value, gdb_byte **bytes,
16182                          struct dwarf2_locexpr_baton **baton)
16183 {
16184   struct objfile *objfile = cu->objfile;
16185   struct comp_unit_head *cu_header = &cu->header;
16186   struct dwarf_block *blk;
16187   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16188                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16189
16190   *value = 0;
16191   *bytes = NULL;
16192   *baton = NULL;
16193
16194   switch (attr->form)
16195     {
16196     case DW_FORM_addr:
16197     case DW_FORM_GNU_addr_index:
16198       {
16199         gdb_byte *data;
16200
16201         if (TYPE_LENGTH (type) != cu_header->addr_size)
16202           dwarf2_const_value_length_mismatch_complaint (name,
16203                                                         cu_header->addr_size,
16204                                                         TYPE_LENGTH (type));
16205         /* Symbols of this form are reasonably rare, so we just
16206            piggyback on the existing location code rather than writing
16207            a new implementation of symbol_computed_ops.  */
16208         *baton = obstack_alloc (&objfile->objfile_obstack,
16209                                 sizeof (struct dwarf2_locexpr_baton));
16210         (*baton)->per_cu = cu->per_cu;
16211         gdb_assert ((*baton)->per_cu);
16212
16213         (*baton)->size = 2 + cu_header->addr_size;
16214         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16215         (*baton)->data = data;
16216
16217         data[0] = DW_OP_addr;
16218         store_unsigned_integer (&data[1], cu_header->addr_size,
16219                                 byte_order, DW_ADDR (attr));
16220         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16221       }
16222       break;
16223     case DW_FORM_string:
16224     case DW_FORM_strp:
16225     case DW_FORM_GNU_str_index:
16226     case DW_FORM_GNU_strp_alt:
16227       /* DW_STRING is already allocated on the objfile obstack, point
16228          directly to it.  */
16229       *bytes = (gdb_byte *) DW_STRING (attr);
16230       break;
16231     case DW_FORM_block1:
16232     case DW_FORM_block2:
16233     case DW_FORM_block4:
16234     case DW_FORM_block:
16235     case DW_FORM_exprloc:
16236       blk = DW_BLOCK (attr);
16237       if (TYPE_LENGTH (type) != blk->size)
16238         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16239                                                       TYPE_LENGTH (type));
16240       *bytes = blk->data;
16241       break;
16242
16243       /* The DW_AT_const_value attributes are supposed to carry the
16244          symbol's value "represented as it would be on the target
16245          architecture."  By the time we get here, it's already been
16246          converted to host endianness, so we just need to sign- or
16247          zero-extend it as appropriate.  */
16248     case DW_FORM_data1:
16249       *bytes = dwarf2_const_value_data (attr, type, name,
16250                                         obstack, cu, value, 8);
16251       break;
16252     case DW_FORM_data2:
16253       *bytes = dwarf2_const_value_data (attr, type, name,
16254                                         obstack, cu, value, 16);
16255       break;
16256     case DW_FORM_data4:
16257       *bytes = dwarf2_const_value_data (attr, type, name,
16258                                         obstack, cu, value, 32);
16259       break;
16260     case DW_FORM_data8:
16261       *bytes = dwarf2_const_value_data (attr, type, name,
16262                                         obstack, cu, value, 64);
16263       break;
16264
16265     case DW_FORM_sdata:
16266       *value = DW_SND (attr);
16267       break;
16268
16269     case DW_FORM_udata:
16270       *value = DW_UNSND (attr);
16271       break;
16272
16273     default:
16274       complaint (&symfile_complaints,
16275                  _("unsupported const value attribute form: '%s'"),
16276                  dwarf_form_name (attr->form));
16277       *value = 0;
16278       break;
16279     }
16280 }
16281
16282
16283 /* Copy constant value from an attribute to a symbol.  */
16284
16285 static void
16286 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16287                     struct dwarf2_cu *cu)
16288 {
16289   struct objfile *objfile = cu->objfile;
16290   struct comp_unit_head *cu_header = &cu->header;
16291   LONGEST value;
16292   gdb_byte *bytes;
16293   struct dwarf2_locexpr_baton *baton;
16294
16295   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16296                            SYMBOL_PRINT_NAME (sym),
16297                            &objfile->objfile_obstack, cu,
16298                            &value, &bytes, &baton);
16299
16300   if (baton != NULL)
16301     {
16302       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
16303       SYMBOL_LOCATION_BATON (sym) = baton;
16304       SYMBOL_CLASS (sym) = LOC_COMPUTED;
16305     }
16306   else if (bytes != NULL)
16307      {
16308       SYMBOL_VALUE_BYTES (sym) = bytes;
16309       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
16310     }
16311   else
16312     {
16313       SYMBOL_VALUE (sym) = value;
16314       SYMBOL_CLASS (sym) = LOC_CONST;
16315     }
16316 }
16317
16318 /* Return the type of the die in question using its DW_AT_type attribute.  */
16319
16320 static struct type *
16321 die_type (struct die_info *die, struct dwarf2_cu *cu)
16322 {
16323   struct attribute *type_attr;
16324
16325   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16326   if (!type_attr)
16327     {
16328       /* A missing DW_AT_type represents a void type.  */
16329       return objfile_type (cu->objfile)->builtin_void;
16330     }
16331
16332   return lookup_die_type (die, type_attr, cu);
16333 }
16334
16335 /* True iff CU's producer generates GNAT Ada auxiliary information
16336    that allows to find parallel types through that information instead
16337    of having to do expensive parallel lookups by type name.  */
16338
16339 static int
16340 need_gnat_info (struct dwarf2_cu *cu)
16341 {
16342   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16343      of GNAT produces this auxiliary information, without any indication
16344      that it is produced.  Part of enhancing the FSF version of GNAT
16345      to produce that information will be to put in place an indicator
16346      that we can use in order to determine whether the descriptive type
16347      info is available or not.  One suggestion that has been made is
16348      to use a new attribute, attached to the CU die.  For now, assume
16349      that the descriptive type info is not available.  */
16350   return 0;
16351 }
16352
16353 /* Return the auxiliary type of the die in question using its
16354    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16355    attribute is not present.  */
16356
16357 static struct type *
16358 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16359 {
16360   struct attribute *type_attr;
16361
16362   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16363   if (!type_attr)
16364     return NULL;
16365
16366   return lookup_die_type (die, type_attr, cu);
16367 }
16368
16369 /* If DIE has a descriptive_type attribute, then set the TYPE's
16370    descriptive type accordingly.  */
16371
16372 static void
16373 set_descriptive_type (struct type *type, struct die_info *die,
16374                       struct dwarf2_cu *cu)
16375 {
16376   struct type *descriptive_type = die_descriptive_type (die, cu);
16377
16378   if (descriptive_type)
16379     {
16380       ALLOCATE_GNAT_AUX_TYPE (type);
16381       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16382     }
16383 }
16384
16385 /* Return the containing type of the die in question using its
16386    DW_AT_containing_type attribute.  */
16387
16388 static struct type *
16389 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16390 {
16391   struct attribute *type_attr;
16392
16393   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16394   if (!type_attr)
16395     error (_("Dwarf Error: Problem turning containing type into gdb type "
16396              "[in module %s]"), cu->objfile->name);
16397
16398   return lookup_die_type (die, type_attr, cu);
16399 }
16400
16401 /* Look up the type of DIE in CU using its type attribute ATTR.
16402    If there is no type substitute an error marker.  */
16403
16404 static struct type *
16405 lookup_die_type (struct die_info *die, struct attribute *attr,
16406                  struct dwarf2_cu *cu)
16407 {
16408   struct objfile *objfile = cu->objfile;
16409   struct type *this_type;
16410
16411   /* First see if we have it cached.  */
16412
16413   if (attr->form == DW_FORM_GNU_ref_alt)
16414     {
16415       struct dwarf2_per_cu_data *per_cu;
16416       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16417
16418       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16419       this_type = get_die_type_at_offset (offset, per_cu);
16420     }
16421   else if (is_ref_attr (attr))
16422     {
16423       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16424
16425       this_type = get_die_type_at_offset (offset, cu->per_cu);
16426     }
16427   else if (attr->form == DW_FORM_ref_sig8)
16428     {
16429       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16430
16431       /* sig_type will be NULL if the signatured type is missing from
16432          the debug info.  */
16433       if (sig_type == NULL)
16434         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16435                  "at 0x%x [in module %s]"),
16436                die->offset.sect_off, objfile->name);
16437
16438       gdb_assert (sig_type->per_cu.is_debug_types);
16439       /* If we haven't filled in type_offset_in_section yet, then we
16440          haven't read the type in yet.  */
16441       this_type = NULL;
16442       if (sig_type->type_offset_in_section.sect_off != 0)
16443         {
16444           this_type =
16445             get_die_type_at_offset (sig_type->type_offset_in_section,
16446                                     &sig_type->per_cu);
16447         }
16448     }
16449   else
16450     {
16451       dump_die_for_error (die);
16452       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16453              dwarf_attr_name (attr->name), objfile->name);
16454     }
16455
16456   /* If not cached we need to read it in.  */
16457
16458   if (this_type == NULL)
16459     {
16460       struct die_info *type_die;
16461       struct dwarf2_cu *type_cu = cu;
16462
16463       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16464       /* If we found the type now, it's probably because the type came
16465          from an inter-CU reference and the type's CU got expanded before
16466          ours.  */
16467       this_type = get_die_type (type_die, type_cu);
16468       if (this_type == NULL)
16469         this_type = read_type_die_1 (type_die, type_cu);
16470     }
16471
16472   /* If we still don't have a type use an error marker.  */
16473
16474   if (this_type == NULL)
16475     {
16476       char *message, *saved;
16477
16478       /* read_type_die already issued a complaint.  */
16479       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16480                             objfile->name,
16481                             cu->header.offset.sect_off,
16482                             die->offset.sect_off);
16483       saved = obstack_copy0 (&objfile->objfile_obstack,
16484                              message, strlen (message));
16485       xfree (message);
16486
16487       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16488     }
16489
16490   return this_type;
16491 }
16492
16493 /* Return the type in DIE, CU.
16494    Returns NULL for invalid types.
16495
16496    This first does a lookup in the appropriate type_hash table,
16497    and only reads the die in if necessary.
16498
16499    NOTE: This can be called when reading in partial or full symbols.  */
16500
16501 static struct type *
16502 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16503 {
16504   struct type *this_type;
16505
16506   this_type = get_die_type (die, cu);
16507   if (this_type)
16508     return this_type;
16509
16510   return read_type_die_1 (die, cu);
16511 }
16512
16513 /* Read the type in DIE, CU.
16514    Returns NULL for invalid types.  */
16515
16516 static struct type *
16517 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16518 {
16519   struct type *this_type = NULL;
16520
16521   switch (die->tag)
16522     {
16523     case DW_TAG_class_type:
16524     case DW_TAG_interface_type:
16525     case DW_TAG_structure_type:
16526     case DW_TAG_union_type:
16527       this_type = read_structure_type (die, cu);
16528       break;
16529     case DW_TAG_enumeration_type:
16530       this_type = read_enumeration_type (die, cu);
16531       break;
16532     case DW_TAG_subprogram:
16533     case DW_TAG_subroutine_type:
16534     case DW_TAG_inlined_subroutine:
16535       this_type = read_subroutine_type (die, cu);
16536       break;
16537     case DW_TAG_array_type:
16538       this_type = read_array_type (die, cu);
16539       break;
16540     case DW_TAG_set_type:
16541       this_type = read_set_type (die, cu);
16542       break;
16543     case DW_TAG_pointer_type:
16544       this_type = read_tag_pointer_type (die, cu);
16545       break;
16546     case DW_TAG_ptr_to_member_type:
16547       this_type = read_tag_ptr_to_member_type (die, cu);
16548       break;
16549     case DW_TAG_reference_type:
16550       this_type = read_tag_reference_type (die, cu);
16551       break;
16552     case DW_TAG_const_type:
16553       this_type = read_tag_const_type (die, cu);
16554       break;
16555     case DW_TAG_volatile_type:
16556       this_type = read_tag_volatile_type (die, cu);
16557       break;
16558     case DW_TAG_restrict_type:
16559       this_type = read_tag_restrict_type (die, cu);
16560       break;
16561     case DW_TAG_string_type:
16562       this_type = read_tag_string_type (die, cu);
16563       break;
16564     case DW_TAG_typedef:
16565       this_type = read_typedef (die, cu);
16566       break;
16567     case DW_TAG_subrange_type:
16568       this_type = read_subrange_type (die, cu);
16569       break;
16570     case DW_TAG_base_type:
16571       this_type = read_base_type (die, cu);
16572       break;
16573     case DW_TAG_unspecified_type:
16574       this_type = read_unspecified_type (die, cu);
16575       break;
16576     case DW_TAG_namespace:
16577       this_type = read_namespace_type (die, cu);
16578       break;
16579     case DW_TAG_module:
16580       this_type = read_module_type (die, cu);
16581       break;
16582     default:
16583       complaint (&symfile_complaints,
16584                  _("unexpected tag in read_type_die: '%s'"),
16585                  dwarf_tag_name (die->tag));
16586       break;
16587     }
16588
16589   return this_type;
16590 }
16591
16592 /* See if we can figure out if the class lives in a namespace.  We do
16593    this by looking for a member function; its demangled name will
16594    contain namespace info, if there is any.
16595    Return the computed name or NULL.
16596    Space for the result is allocated on the objfile's obstack.
16597    This is the full-die version of guess_partial_die_structure_name.
16598    In this case we know DIE has no useful parent.  */
16599
16600 static char *
16601 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16602 {
16603   struct die_info *spec_die;
16604   struct dwarf2_cu *spec_cu;
16605   struct die_info *child;
16606
16607   spec_cu = cu;
16608   spec_die = die_specification (die, &spec_cu);
16609   if (spec_die != NULL)
16610     {
16611       die = spec_die;
16612       cu = spec_cu;
16613     }
16614
16615   for (child = die->child;
16616        child != NULL;
16617        child = child->sibling)
16618     {
16619       if (child->tag == DW_TAG_subprogram)
16620         {
16621           struct attribute *attr;
16622
16623           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16624           if (attr == NULL)
16625             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16626           if (attr != NULL)
16627             {
16628               char *actual_name
16629                 = language_class_name_from_physname (cu->language_defn,
16630                                                      DW_STRING (attr));
16631               char *name = NULL;
16632
16633               if (actual_name != NULL)
16634                 {
16635                   const char *die_name = dwarf2_name (die, cu);
16636
16637                   if (die_name != NULL
16638                       && strcmp (die_name, actual_name) != 0)
16639                     {
16640                       /* Strip off the class name from the full name.
16641                          We want the prefix.  */
16642                       int die_name_len = strlen (die_name);
16643                       int actual_name_len = strlen (actual_name);
16644
16645                       /* Test for '::' as a sanity check.  */
16646                       if (actual_name_len > die_name_len + 2
16647                           && actual_name[actual_name_len
16648                                          - die_name_len - 1] == ':')
16649                         name =
16650                           obstack_copy0 (&cu->objfile->objfile_obstack,
16651                                          actual_name,
16652                                          actual_name_len - die_name_len - 2);
16653                     }
16654                 }
16655               xfree (actual_name);
16656               return name;
16657             }
16658         }
16659     }
16660
16661   return NULL;
16662 }
16663
16664 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16665    prefix part in such case.  See
16666    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16667
16668 static char *
16669 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16670 {
16671   struct attribute *attr;
16672   char *base;
16673
16674   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16675       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16676     return NULL;
16677
16678   attr = dwarf2_attr (die, DW_AT_name, cu);
16679   if (attr != NULL && DW_STRING (attr) != NULL)
16680     return NULL;
16681
16682   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16683   if (attr == NULL)
16684     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16685   if (attr == NULL || DW_STRING (attr) == NULL)
16686     return NULL;
16687
16688   /* dwarf2_name had to be already called.  */
16689   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16690
16691   /* Strip the base name, keep any leading namespaces/classes.  */
16692   base = strrchr (DW_STRING (attr), ':');
16693   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16694     return "";
16695
16696   return obstack_copy0 (&cu->objfile->objfile_obstack,
16697                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16698 }
16699
16700 /* Return the name of the namespace/class that DIE is defined within,
16701    or "" if we can't tell.  The caller should not xfree the result.
16702
16703    For example, if we're within the method foo() in the following
16704    code:
16705
16706    namespace N {
16707      class C {
16708        void foo () {
16709        }
16710      };
16711    }
16712
16713    then determine_prefix on foo's die will return "N::C".  */
16714
16715 static const char *
16716 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16717 {
16718   struct die_info *parent, *spec_die;
16719   struct dwarf2_cu *spec_cu;
16720   struct type *parent_type;
16721   char *retval;
16722
16723   if (cu->language != language_cplus && cu->language != language_java
16724       && cu->language != language_fortran)
16725     return "";
16726
16727   retval = anonymous_struct_prefix (die, cu);
16728   if (retval)
16729     return retval;
16730
16731   /* We have to be careful in the presence of DW_AT_specification.
16732      For example, with GCC 3.4, given the code
16733
16734      namespace N {
16735        void foo() {
16736          // Definition of N::foo.
16737        }
16738      }
16739
16740      then we'll have a tree of DIEs like this:
16741
16742      1: DW_TAG_compile_unit
16743        2: DW_TAG_namespace        // N
16744          3: DW_TAG_subprogram     // declaration of N::foo
16745        4: DW_TAG_subprogram       // definition of N::foo
16746             DW_AT_specification   // refers to die #3
16747
16748      Thus, when processing die #4, we have to pretend that we're in
16749      the context of its DW_AT_specification, namely the contex of die
16750      #3.  */
16751   spec_cu = cu;
16752   spec_die = die_specification (die, &spec_cu);
16753   if (spec_die == NULL)
16754     parent = die->parent;
16755   else
16756     {
16757       parent = spec_die->parent;
16758       cu = spec_cu;
16759     }
16760
16761   if (parent == NULL)
16762     return "";
16763   else if (parent->building_fullname)
16764     {
16765       const char *name;
16766       const char *parent_name;
16767
16768       /* It has been seen on RealView 2.2 built binaries,
16769          DW_TAG_template_type_param types actually _defined_ as
16770          children of the parent class:
16771
16772          enum E {};
16773          template class <class Enum> Class{};
16774          Class<enum E> class_e;
16775
16776          1: DW_TAG_class_type (Class)
16777            2: DW_TAG_enumeration_type (E)
16778              3: DW_TAG_enumerator (enum1:0)
16779              3: DW_TAG_enumerator (enum2:1)
16780              ...
16781            2: DW_TAG_template_type_param
16782               DW_AT_type  DW_FORM_ref_udata (E)
16783
16784          Besides being broken debug info, it can put GDB into an
16785          infinite loop.  Consider:
16786
16787          When we're building the full name for Class<E>, we'll start
16788          at Class, and go look over its template type parameters,
16789          finding E.  We'll then try to build the full name of E, and
16790          reach here.  We're now trying to build the full name of E,
16791          and look over the parent DIE for containing scope.  In the
16792          broken case, if we followed the parent DIE of E, we'd again
16793          find Class, and once again go look at its template type
16794          arguments, etc., etc.  Simply don't consider such parent die
16795          as source-level parent of this die (it can't be, the language
16796          doesn't allow it), and break the loop here.  */
16797       name = dwarf2_name (die, cu);
16798       parent_name = dwarf2_name (parent, cu);
16799       complaint (&symfile_complaints,
16800                  _("template param type '%s' defined within parent '%s'"),
16801                  name ? name : "<unknown>",
16802                  parent_name ? parent_name : "<unknown>");
16803       return "";
16804     }
16805   else
16806     switch (parent->tag)
16807       {
16808       case DW_TAG_namespace:
16809         parent_type = read_type_die (parent, cu);
16810         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
16811            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
16812            Work around this problem here.  */
16813         if (cu->language == language_cplus
16814             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
16815           return "";
16816         /* We give a name to even anonymous namespaces.  */
16817         return TYPE_TAG_NAME (parent_type);
16818       case DW_TAG_class_type:
16819       case DW_TAG_interface_type:
16820       case DW_TAG_structure_type:
16821       case DW_TAG_union_type:
16822       case DW_TAG_module:
16823         parent_type = read_type_die (parent, cu);
16824         if (TYPE_TAG_NAME (parent_type) != NULL)
16825           return TYPE_TAG_NAME (parent_type);
16826         else
16827           /* An anonymous structure is only allowed non-static data
16828              members; no typedefs, no member functions, et cetera.
16829              So it does not need a prefix.  */
16830           return "";
16831       case DW_TAG_compile_unit:
16832       case DW_TAG_partial_unit:
16833         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
16834         if (cu->language == language_cplus
16835             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16836             && die->child != NULL
16837             && (die->tag == DW_TAG_class_type
16838                 || die->tag == DW_TAG_structure_type
16839                 || die->tag == DW_TAG_union_type))
16840           {
16841             char *name = guess_full_die_structure_name (die, cu);
16842             if (name != NULL)
16843               return name;
16844           }
16845         return "";
16846       default:
16847         return determine_prefix (parent, cu);
16848       }
16849 }
16850
16851 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
16852    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
16853    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
16854    an obconcat, otherwise allocate storage for the result.  The CU argument is
16855    used to determine the language and hence, the appropriate separator.  */
16856
16857 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
16858
16859 static char *
16860 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
16861                  int physname, struct dwarf2_cu *cu)
16862 {
16863   const char *lead = "";
16864   const char *sep;
16865
16866   if (suffix == NULL || suffix[0] == '\0'
16867       || prefix == NULL || prefix[0] == '\0')
16868     sep = "";
16869   else if (cu->language == language_java)
16870     sep = ".";
16871   else if (cu->language == language_fortran && physname)
16872     {
16873       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
16874          DW_AT_MIPS_linkage_name is preferred and used instead.  */
16875
16876       lead = "__";
16877       sep = "_MOD_";
16878     }
16879   else
16880     sep = "::";
16881
16882   if (prefix == NULL)
16883     prefix = "";
16884   if (suffix == NULL)
16885     suffix = "";
16886
16887   if (obs == NULL)
16888     {
16889       char *retval
16890         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
16891
16892       strcpy (retval, lead);
16893       strcat (retval, prefix);
16894       strcat (retval, sep);
16895       strcat (retval, suffix);
16896       return retval;
16897     }
16898   else
16899     {
16900       /* We have an obstack.  */
16901       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
16902     }
16903 }
16904
16905 /* Return sibling of die, NULL if no sibling.  */
16906
16907 static struct die_info *
16908 sibling_die (struct die_info *die)
16909 {
16910   return die->sibling;
16911 }
16912
16913 /* Get name of a die, return NULL if not found.  */
16914
16915 static const char *
16916 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
16917                           struct obstack *obstack)
16918 {
16919   if (name && cu->language == language_cplus)
16920     {
16921       char *canon_name = cp_canonicalize_string (name);
16922
16923       if (canon_name != NULL)
16924         {
16925           if (strcmp (canon_name, name) != 0)
16926             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
16927           xfree (canon_name);
16928         }
16929     }
16930
16931   return name;
16932 }
16933
16934 /* Get name of a die, return NULL if not found.  */
16935
16936 static const char *
16937 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
16938 {
16939   struct attribute *attr;
16940
16941   attr = dwarf2_attr (die, DW_AT_name, cu);
16942   if ((!attr || !DW_STRING (attr))
16943       && die->tag != DW_TAG_class_type
16944       && die->tag != DW_TAG_interface_type
16945       && die->tag != DW_TAG_structure_type
16946       && die->tag != DW_TAG_union_type)
16947     return NULL;
16948
16949   switch (die->tag)
16950     {
16951     case DW_TAG_compile_unit:
16952     case DW_TAG_partial_unit:
16953       /* Compilation units have a DW_AT_name that is a filename, not
16954          a source language identifier.  */
16955     case DW_TAG_enumeration_type:
16956     case DW_TAG_enumerator:
16957       /* These tags always have simple identifiers already; no need
16958          to canonicalize them.  */
16959       return DW_STRING (attr);
16960
16961     case DW_TAG_subprogram:
16962       /* Java constructors will all be named "<init>", so return
16963          the class name when we see this special case.  */
16964       if (cu->language == language_java
16965           && DW_STRING (attr) != NULL
16966           && strcmp (DW_STRING (attr), "<init>") == 0)
16967         {
16968           struct dwarf2_cu *spec_cu = cu;
16969           struct die_info *spec_die;
16970
16971           /* GCJ will output '<init>' for Java constructor names.
16972              For this special case, return the name of the parent class.  */
16973
16974           /* GCJ may output suprogram DIEs with AT_specification set.
16975              If so, use the name of the specified DIE.  */
16976           spec_die = die_specification (die, &spec_cu);
16977           if (spec_die != NULL)
16978             return dwarf2_name (spec_die, spec_cu);
16979
16980           do
16981             {
16982               die = die->parent;
16983               if (die->tag == DW_TAG_class_type)
16984                 return dwarf2_name (die, cu);
16985             }
16986           while (die->tag != DW_TAG_compile_unit
16987                  && die->tag != DW_TAG_partial_unit);
16988         }
16989       break;
16990
16991     case DW_TAG_class_type:
16992     case DW_TAG_interface_type:
16993     case DW_TAG_structure_type:
16994     case DW_TAG_union_type:
16995       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
16996          structures or unions.  These were of the form "._%d" in GCC 4.1,
16997          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
16998          and GCC 4.4.  We work around this problem by ignoring these.  */
16999       if (attr && DW_STRING (attr)
17000           && (strncmp (DW_STRING (attr), "._", 2) == 0
17001               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17002         return NULL;
17003
17004       /* GCC might emit a nameless typedef that has a linkage name.  See
17005          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17006       if (!attr || DW_STRING (attr) == NULL)
17007         {
17008           char *demangled = NULL;
17009
17010           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17011           if (attr == NULL)
17012             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17013
17014           if (attr == NULL || DW_STRING (attr) == NULL)
17015             return NULL;
17016
17017           /* Avoid demangling DW_STRING (attr) the second time on a second
17018              call for the same DIE.  */
17019           if (!DW_STRING_IS_CANONICAL (attr))
17020             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
17021
17022           if (demangled)
17023             {
17024               char *base;
17025
17026               /* FIXME: we already did this for the partial symbol... */
17027               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17028                                                 demangled, strlen (demangled));
17029               DW_STRING_IS_CANONICAL (attr) = 1;
17030               xfree (demangled);
17031
17032               /* Strip any leading namespaces/classes, keep only the base name.
17033                  DW_AT_name for named DIEs does not contain the prefixes.  */
17034               base = strrchr (DW_STRING (attr), ':');
17035               if (base && base > DW_STRING (attr) && base[-1] == ':')
17036                 return &base[1];
17037               else
17038                 return DW_STRING (attr);
17039             }
17040         }
17041       break;
17042
17043     default:
17044       break;
17045     }
17046
17047   if (!DW_STRING_IS_CANONICAL (attr))
17048     {
17049       DW_STRING (attr)
17050         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17051                                     &cu->objfile->objfile_obstack);
17052       DW_STRING_IS_CANONICAL (attr) = 1;
17053     }
17054   return DW_STRING (attr);
17055 }
17056
17057 /* Return the die that this die in an extension of, or NULL if there
17058    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17059    containing the return value on output.  */
17060
17061 static struct die_info *
17062 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17063 {
17064   struct attribute *attr;
17065
17066   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17067   if (attr == NULL)
17068     return NULL;
17069
17070   return follow_die_ref (die, attr, ext_cu);
17071 }
17072
17073 /* Convert a DIE tag into its string name.  */
17074
17075 static const char *
17076 dwarf_tag_name (unsigned tag)
17077 {
17078   const char *name = get_DW_TAG_name (tag);
17079
17080   if (name == NULL)
17081     return "DW_TAG_<unknown>";
17082
17083   return name;
17084 }
17085
17086 /* Convert a DWARF attribute code into its string name.  */
17087
17088 static const char *
17089 dwarf_attr_name (unsigned attr)
17090 {
17091   const char *name;
17092
17093 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17094   if (attr == DW_AT_MIPS_fde)
17095     return "DW_AT_MIPS_fde";
17096 #else
17097   if (attr == DW_AT_HP_block_index)
17098     return "DW_AT_HP_block_index";
17099 #endif
17100
17101   name = get_DW_AT_name (attr);
17102
17103   if (name == NULL)
17104     return "DW_AT_<unknown>";
17105
17106   return name;
17107 }
17108
17109 /* Convert a DWARF value form code into its string name.  */
17110
17111 static const char *
17112 dwarf_form_name (unsigned form)
17113 {
17114   const char *name = get_DW_FORM_name (form);
17115
17116   if (name == NULL)
17117     return "DW_FORM_<unknown>";
17118
17119   return name;
17120 }
17121
17122 static char *
17123 dwarf_bool_name (unsigned mybool)
17124 {
17125   if (mybool)
17126     return "TRUE";
17127   else
17128     return "FALSE";
17129 }
17130
17131 /* Convert a DWARF type code into its string name.  */
17132
17133 static const char *
17134 dwarf_type_encoding_name (unsigned enc)
17135 {
17136   const char *name = get_DW_ATE_name (enc);
17137
17138   if (name == NULL)
17139     return "DW_ATE_<unknown>";
17140
17141   return name;
17142 }
17143
17144 static void
17145 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17146 {
17147   unsigned int i;
17148
17149   print_spaces (indent, f);
17150   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17151            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17152
17153   if (die->parent != NULL)
17154     {
17155       print_spaces (indent, f);
17156       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17157                           die->parent->offset.sect_off);
17158     }
17159
17160   print_spaces (indent, f);
17161   fprintf_unfiltered (f, "  has children: %s\n",
17162            dwarf_bool_name (die->child != NULL));
17163
17164   print_spaces (indent, f);
17165   fprintf_unfiltered (f, "  attributes:\n");
17166
17167   for (i = 0; i < die->num_attrs; ++i)
17168     {
17169       print_spaces (indent, f);
17170       fprintf_unfiltered (f, "    %s (%s) ",
17171                dwarf_attr_name (die->attrs[i].name),
17172                dwarf_form_name (die->attrs[i].form));
17173
17174       switch (die->attrs[i].form)
17175         {
17176         case DW_FORM_addr:
17177         case DW_FORM_GNU_addr_index:
17178           fprintf_unfiltered (f, "address: ");
17179           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17180           break;
17181         case DW_FORM_block2:
17182         case DW_FORM_block4:
17183         case DW_FORM_block:
17184         case DW_FORM_block1:
17185           fprintf_unfiltered (f, "block: size %s",
17186                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17187           break;
17188         case DW_FORM_exprloc:
17189           fprintf_unfiltered (f, "expression: size %s",
17190                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17191           break;
17192         case DW_FORM_ref_addr:
17193           fprintf_unfiltered (f, "ref address: ");
17194           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17195           break;
17196         case DW_FORM_GNU_ref_alt:
17197           fprintf_unfiltered (f, "alt ref address: ");
17198           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17199           break;
17200         case DW_FORM_ref1:
17201         case DW_FORM_ref2:
17202         case DW_FORM_ref4:
17203         case DW_FORM_ref8:
17204         case DW_FORM_ref_udata:
17205           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17206                               (long) (DW_UNSND (&die->attrs[i])));
17207           break;
17208         case DW_FORM_data1:
17209         case DW_FORM_data2:
17210         case DW_FORM_data4:
17211         case DW_FORM_data8:
17212         case DW_FORM_udata:
17213         case DW_FORM_sdata:
17214           fprintf_unfiltered (f, "constant: %s",
17215                               pulongest (DW_UNSND (&die->attrs[i])));
17216           break;
17217         case DW_FORM_sec_offset:
17218           fprintf_unfiltered (f, "section offset: %s",
17219                               pulongest (DW_UNSND (&die->attrs[i])));
17220           break;
17221         case DW_FORM_ref_sig8:
17222           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17223             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
17224                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
17225           else
17226             fprintf_unfiltered (f, "signatured type, offset: unknown");
17227           break;
17228         case DW_FORM_string:
17229         case DW_FORM_strp:
17230         case DW_FORM_GNU_str_index:
17231         case DW_FORM_GNU_strp_alt:
17232           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17233                    DW_STRING (&die->attrs[i])
17234                    ? DW_STRING (&die->attrs[i]) : "",
17235                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17236           break;
17237         case DW_FORM_flag:
17238           if (DW_UNSND (&die->attrs[i]))
17239             fprintf_unfiltered (f, "flag: TRUE");
17240           else
17241             fprintf_unfiltered (f, "flag: FALSE");
17242           break;
17243         case DW_FORM_flag_present:
17244           fprintf_unfiltered (f, "flag: TRUE");
17245           break;
17246         case DW_FORM_indirect:
17247           /* The reader will have reduced the indirect form to
17248              the "base form" so this form should not occur.  */
17249           fprintf_unfiltered (f, 
17250                               "unexpected attribute form: DW_FORM_indirect");
17251           break;
17252         default:
17253           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17254                    die->attrs[i].form);
17255           break;
17256         }
17257       fprintf_unfiltered (f, "\n");
17258     }
17259 }
17260
17261 static void
17262 dump_die_for_error (struct die_info *die)
17263 {
17264   dump_die_shallow (gdb_stderr, 0, die);
17265 }
17266
17267 static void
17268 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17269 {
17270   int indent = level * 4;
17271
17272   gdb_assert (die != NULL);
17273
17274   if (level >= max_level)
17275     return;
17276
17277   dump_die_shallow (f, indent, die);
17278
17279   if (die->child != NULL)
17280     {
17281       print_spaces (indent, f);
17282       fprintf_unfiltered (f, "  Children:");
17283       if (level + 1 < max_level)
17284         {
17285           fprintf_unfiltered (f, "\n");
17286           dump_die_1 (f, level + 1, max_level, die->child);
17287         }
17288       else
17289         {
17290           fprintf_unfiltered (f,
17291                               " [not printed, max nesting level reached]\n");
17292         }
17293     }
17294
17295   if (die->sibling != NULL && level > 0)
17296     {
17297       dump_die_1 (f, level, max_level, die->sibling);
17298     }
17299 }
17300
17301 /* This is called from the pdie macro in gdbinit.in.
17302    It's not static so gcc will keep a copy callable from gdb.  */
17303
17304 void
17305 dump_die (struct die_info *die, int max_level)
17306 {
17307   dump_die_1 (gdb_stdlog, 0, max_level, die);
17308 }
17309
17310 static void
17311 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17312 {
17313   void **slot;
17314
17315   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17316                                    INSERT);
17317
17318   *slot = die;
17319 }
17320
17321 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17322    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17323
17324 static int
17325 is_ref_attr (struct attribute *attr)
17326 {
17327   switch (attr->form)
17328     {
17329     case DW_FORM_ref_addr:
17330     case DW_FORM_ref1:
17331     case DW_FORM_ref2:
17332     case DW_FORM_ref4:
17333     case DW_FORM_ref8:
17334     case DW_FORM_ref_udata:
17335     case DW_FORM_GNU_ref_alt:
17336       return 1;
17337     default:
17338       return 0;
17339     }
17340 }
17341
17342 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17343    required kind.  */
17344
17345 static sect_offset
17346 dwarf2_get_ref_die_offset (struct attribute *attr)
17347 {
17348   sect_offset retval = { DW_UNSND (attr) };
17349
17350   if (is_ref_attr (attr))
17351     return retval;
17352
17353   retval.sect_off = 0;
17354   complaint (&symfile_complaints,
17355              _("unsupported die ref attribute form: '%s'"),
17356              dwarf_form_name (attr->form));
17357   return retval;
17358 }
17359
17360 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17361  * the value held by the attribute is not constant.  */
17362
17363 static LONGEST
17364 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17365 {
17366   if (attr->form == DW_FORM_sdata)
17367     return DW_SND (attr);
17368   else if (attr->form == DW_FORM_udata
17369            || attr->form == DW_FORM_data1
17370            || attr->form == DW_FORM_data2
17371            || attr->form == DW_FORM_data4
17372            || attr->form == DW_FORM_data8)
17373     return DW_UNSND (attr);
17374   else
17375     {
17376       complaint (&symfile_complaints,
17377                  _("Attribute value is not a constant (%s)"),
17378                  dwarf_form_name (attr->form));
17379       return default_value;
17380     }
17381 }
17382
17383 /* Follow reference or signature attribute ATTR of SRC_DIE.
17384    On entry *REF_CU is the CU of SRC_DIE.
17385    On exit *REF_CU is the CU of the result.  */
17386
17387 static struct die_info *
17388 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17389                        struct dwarf2_cu **ref_cu)
17390 {
17391   struct die_info *die;
17392
17393   if (is_ref_attr (attr))
17394     die = follow_die_ref (src_die, attr, ref_cu);
17395   else if (attr->form == DW_FORM_ref_sig8)
17396     die = follow_die_sig (src_die, attr, ref_cu);
17397   else
17398     {
17399       dump_die_for_error (src_die);
17400       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17401              (*ref_cu)->objfile->name);
17402     }
17403
17404   return die;
17405 }
17406
17407 /* Follow reference OFFSET.
17408    On entry *REF_CU is the CU of the source die referencing OFFSET.
17409    On exit *REF_CU is the CU of the result.
17410    Returns NULL if OFFSET is invalid.  */
17411
17412 static struct die_info *
17413 follow_die_offset (sect_offset offset, int offset_in_dwz,
17414                    struct dwarf2_cu **ref_cu)
17415 {
17416   struct die_info temp_die;
17417   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17418
17419   gdb_assert (cu->per_cu != NULL);
17420
17421   target_cu = cu;
17422
17423   if (cu->per_cu->is_debug_types)
17424     {
17425       /* .debug_types CUs cannot reference anything outside their CU.
17426          If they need to, they have to reference a signatured type via
17427          DW_FORM_ref_sig8.  */
17428       if (! offset_in_cu_p (&cu->header, offset))
17429         return NULL;
17430     }
17431   else if (offset_in_dwz != cu->per_cu->is_dwz
17432            || ! offset_in_cu_p (&cu->header, offset))
17433     {
17434       struct dwarf2_per_cu_data *per_cu;
17435
17436       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17437                                                  cu->objfile);
17438
17439       /* If necessary, add it to the queue and load its DIEs.  */
17440       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17441         load_full_comp_unit (per_cu, cu->language);
17442
17443       target_cu = per_cu->cu;
17444     }
17445   else if (cu->dies == NULL)
17446     {
17447       /* We're loading full DIEs during partial symbol reading.  */
17448       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17449       load_full_comp_unit (cu->per_cu, language_minimal);
17450     }
17451
17452   *ref_cu = target_cu;
17453   temp_die.offset = offset;
17454   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17455 }
17456
17457 /* Follow reference attribute ATTR of SRC_DIE.
17458    On entry *REF_CU is the CU of SRC_DIE.
17459    On exit *REF_CU is the CU of the result.  */
17460
17461 static struct die_info *
17462 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17463                 struct dwarf2_cu **ref_cu)
17464 {
17465   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17466   struct dwarf2_cu *cu = *ref_cu;
17467   struct die_info *die;
17468
17469   die = follow_die_offset (offset,
17470                            (attr->form == DW_FORM_GNU_ref_alt
17471                             || cu->per_cu->is_dwz),
17472                            ref_cu);
17473   if (!die)
17474     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17475            "at 0x%x [in module %s]"),
17476            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17477
17478   return die;
17479 }
17480
17481 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17482    Returned value is intended for DW_OP_call*.  Returned
17483    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17484
17485 struct dwarf2_locexpr_baton
17486 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17487                                struct dwarf2_per_cu_data *per_cu,
17488                                CORE_ADDR (*get_frame_pc) (void *baton),
17489                                void *baton)
17490 {
17491   struct dwarf2_cu *cu;
17492   struct die_info *die;
17493   struct attribute *attr;
17494   struct dwarf2_locexpr_baton retval;
17495
17496   dw2_setup (per_cu->objfile);
17497
17498   if (per_cu->cu == NULL)
17499     load_cu (per_cu);
17500   cu = per_cu->cu;
17501
17502   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17503   if (!die)
17504     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17505            offset.sect_off, per_cu->objfile->name);
17506
17507   attr = dwarf2_attr (die, DW_AT_location, cu);
17508   if (!attr)
17509     {
17510       /* DWARF: "If there is no such attribute, then there is no effect.".
17511          DATA is ignored if SIZE is 0.  */
17512
17513       retval.data = NULL;
17514       retval.size = 0;
17515     }
17516   else if (attr_form_is_section_offset (attr))
17517     {
17518       struct dwarf2_loclist_baton loclist_baton;
17519       CORE_ADDR pc = (*get_frame_pc) (baton);
17520       size_t size;
17521
17522       fill_in_loclist_baton (cu, &loclist_baton, attr);
17523
17524       retval.data = dwarf2_find_location_expression (&loclist_baton,
17525                                                      &size, pc);
17526       retval.size = size;
17527     }
17528   else
17529     {
17530       if (!attr_form_is_block (attr))
17531         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17532                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17533                offset.sect_off, per_cu->objfile->name);
17534
17535       retval.data = DW_BLOCK (attr)->data;
17536       retval.size = DW_BLOCK (attr)->size;
17537     }
17538   retval.per_cu = cu->per_cu;
17539
17540   age_cached_comp_units ();
17541
17542   return retval;
17543 }
17544
17545 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17546    offset.  */
17547
17548 struct dwarf2_locexpr_baton
17549 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17550                              struct dwarf2_per_cu_data *per_cu,
17551                              CORE_ADDR (*get_frame_pc) (void *baton),
17552                              void *baton)
17553 {
17554   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17555
17556   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17557 }
17558
17559 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17560    PER_CU.  */
17561
17562 struct type *
17563 dwarf2_get_die_type (cu_offset die_offset,
17564                      struct dwarf2_per_cu_data *per_cu)
17565 {
17566   sect_offset die_offset_sect;
17567
17568   dw2_setup (per_cu->objfile);
17569
17570   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17571   return get_die_type_at_offset (die_offset_sect, per_cu);
17572 }
17573
17574 /* Follow the signature attribute ATTR in SRC_DIE.
17575    On entry *REF_CU is the CU of SRC_DIE.
17576    On exit *REF_CU is the CU of the result.  */
17577
17578 static struct die_info *
17579 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17580                 struct dwarf2_cu **ref_cu)
17581 {
17582   struct objfile *objfile = (*ref_cu)->objfile;
17583   struct die_info temp_die;
17584   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17585   struct dwarf2_cu *sig_cu;
17586   struct die_info *die;
17587
17588   /* sig_type will be NULL if the signatured type is missing from
17589      the debug info.  */
17590   if (sig_type == NULL)
17591     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17592              "at 0x%x [in module %s]"),
17593            src_die->offset.sect_off, objfile->name);
17594
17595   /* If necessary, add it to the queue and load its DIEs.  */
17596
17597   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17598     read_signatured_type (sig_type);
17599
17600   gdb_assert (sig_type->per_cu.cu != NULL);
17601
17602   sig_cu = sig_type->per_cu.cu;
17603   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17604   temp_die.offset = sig_type->type_offset_in_section;
17605   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17606                              temp_die.offset.sect_off);
17607   if (die)
17608     {
17609       /* For .gdb_index version 7 keep track of included TUs.
17610          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17611       if (dwarf2_per_objfile->index_table != NULL
17612           && dwarf2_per_objfile->index_table->version <= 7)
17613         {
17614           VEC_safe_push (dwarf2_per_cu_ptr,
17615                          (*ref_cu)->per_cu->imported_symtabs,
17616                          sig_cu->per_cu);
17617         }
17618
17619       *ref_cu = sig_cu;
17620       return die;
17621     }
17622
17623   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17624          "from DIE at 0x%x [in module %s]"),
17625          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17626 }
17627
17628 /* Given an offset of a signatured type, return its signatured_type.  */
17629
17630 static struct signatured_type *
17631 lookup_signatured_type_at_offset (struct objfile *objfile,
17632                                   struct dwarf2_section_info *section,
17633                                   sect_offset offset)
17634 {
17635   gdb_byte *info_ptr = section->buffer + offset.sect_off;
17636   unsigned int length, initial_length_size;
17637   unsigned int sig_offset;
17638   struct signatured_type find_entry, *sig_type;
17639
17640   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
17641   sig_offset = (initial_length_size
17642                 + 2 /*version*/
17643                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
17644                 + 1 /*address_size*/);
17645   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
17646   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
17647
17648   /* This is only used to lookup previously recorded types.
17649      If we didn't find it, it's our bug.  */
17650   gdb_assert (sig_type != NULL);
17651   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
17652
17653   return sig_type;
17654 }
17655
17656 /* Load the DIEs associated with type unit PER_CU into memory.  */
17657
17658 static void
17659 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17660 {
17661   struct signatured_type *sig_type;
17662
17663   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17664   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17665
17666   /* We have the per_cu, but we need the signatured_type.
17667      Fortunately this is an easy translation.  */
17668   gdb_assert (per_cu->is_debug_types);
17669   sig_type = (struct signatured_type *) per_cu;
17670
17671   gdb_assert (per_cu->cu == NULL);
17672
17673   read_signatured_type (sig_type);
17674
17675   gdb_assert (per_cu->cu != NULL);
17676 }
17677
17678 /* die_reader_func for read_signatured_type.
17679    This is identical to load_full_comp_unit_reader,
17680    but is kept separate for now.  */
17681
17682 static void
17683 read_signatured_type_reader (const struct die_reader_specs *reader,
17684                              gdb_byte *info_ptr,
17685                              struct die_info *comp_unit_die,
17686                              int has_children,
17687                              void *data)
17688 {
17689   struct dwarf2_cu *cu = reader->cu;
17690
17691   gdb_assert (cu->die_hash == NULL);
17692   cu->die_hash =
17693     htab_create_alloc_ex (cu->header.length / 12,
17694                           die_hash,
17695                           die_eq,
17696                           NULL,
17697                           &cu->comp_unit_obstack,
17698                           hashtab_obstack_allocate,
17699                           dummy_obstack_deallocate);
17700
17701   if (has_children)
17702     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17703                                                   &info_ptr, comp_unit_die);
17704   cu->dies = comp_unit_die;
17705   /* comp_unit_die is not stored in die_hash, no need.  */
17706
17707   /* We try not to read any attributes in this function, because not
17708      all CUs needed for references have been loaded yet, and symbol
17709      table processing isn't initialized.  But we have to set the CU language,
17710      or we won't be able to build types correctly.
17711      Similarly, if we do not read the producer, we can not apply
17712      producer-specific interpretation.  */
17713   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17714 }
17715
17716 /* Read in a signatured type and build its CU and DIEs.
17717    If the type is a stub for the real type in a DWO file,
17718    read in the real type from the DWO file as well.  */
17719
17720 static void
17721 read_signatured_type (struct signatured_type *sig_type)
17722 {
17723   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17724
17725   gdb_assert (per_cu->is_debug_types);
17726   gdb_assert (per_cu->cu == NULL);
17727
17728   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17729                            read_signatured_type_reader, NULL);
17730 }
17731
17732 /* Decode simple location descriptions.
17733    Given a pointer to a dwarf block that defines a location, compute
17734    the location and return the value.
17735
17736    NOTE drow/2003-11-18: This function is called in two situations
17737    now: for the address of static or global variables (partial symbols
17738    only) and for offsets into structures which are expected to be
17739    (more or less) constant.  The partial symbol case should go away,
17740    and only the constant case should remain.  That will let this
17741    function complain more accurately.  A few special modes are allowed
17742    without complaint for global variables (for instance, global
17743    register values and thread-local values).
17744
17745    A location description containing no operations indicates that the
17746    object is optimized out.  The return value is 0 for that case.
17747    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17748    callers will only want a very basic result and this can become a
17749    complaint.
17750
17751    Note that stack[0] is unused except as a default error return.  */
17752
17753 static CORE_ADDR
17754 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17755 {
17756   struct objfile *objfile = cu->objfile;
17757   size_t i;
17758   size_t size = blk->size;
17759   gdb_byte *data = blk->data;
17760   CORE_ADDR stack[64];
17761   int stacki;
17762   unsigned int bytes_read, unsnd;
17763   gdb_byte op;
17764
17765   i = 0;
17766   stacki = 0;
17767   stack[stacki] = 0;
17768   stack[++stacki] = 0;
17769
17770   while (i < size)
17771     {
17772       op = data[i++];
17773       switch (op)
17774         {
17775         case DW_OP_lit0:
17776         case DW_OP_lit1:
17777         case DW_OP_lit2:
17778         case DW_OP_lit3:
17779         case DW_OP_lit4:
17780         case DW_OP_lit5:
17781         case DW_OP_lit6:
17782         case DW_OP_lit7:
17783         case DW_OP_lit8:
17784         case DW_OP_lit9:
17785         case DW_OP_lit10:
17786         case DW_OP_lit11:
17787         case DW_OP_lit12:
17788         case DW_OP_lit13:
17789         case DW_OP_lit14:
17790         case DW_OP_lit15:
17791         case DW_OP_lit16:
17792         case DW_OP_lit17:
17793         case DW_OP_lit18:
17794         case DW_OP_lit19:
17795         case DW_OP_lit20:
17796         case DW_OP_lit21:
17797         case DW_OP_lit22:
17798         case DW_OP_lit23:
17799         case DW_OP_lit24:
17800         case DW_OP_lit25:
17801         case DW_OP_lit26:
17802         case DW_OP_lit27:
17803         case DW_OP_lit28:
17804         case DW_OP_lit29:
17805         case DW_OP_lit30:
17806         case DW_OP_lit31:
17807           stack[++stacki] = op - DW_OP_lit0;
17808           break;
17809
17810         case DW_OP_reg0:
17811         case DW_OP_reg1:
17812         case DW_OP_reg2:
17813         case DW_OP_reg3:
17814         case DW_OP_reg4:
17815         case DW_OP_reg5:
17816         case DW_OP_reg6:
17817         case DW_OP_reg7:
17818         case DW_OP_reg8:
17819         case DW_OP_reg9:
17820         case DW_OP_reg10:
17821         case DW_OP_reg11:
17822         case DW_OP_reg12:
17823         case DW_OP_reg13:
17824         case DW_OP_reg14:
17825         case DW_OP_reg15:
17826         case DW_OP_reg16:
17827         case DW_OP_reg17:
17828         case DW_OP_reg18:
17829         case DW_OP_reg19:
17830         case DW_OP_reg20:
17831         case DW_OP_reg21:
17832         case DW_OP_reg22:
17833         case DW_OP_reg23:
17834         case DW_OP_reg24:
17835         case DW_OP_reg25:
17836         case DW_OP_reg26:
17837         case DW_OP_reg27:
17838         case DW_OP_reg28:
17839         case DW_OP_reg29:
17840         case DW_OP_reg30:
17841         case DW_OP_reg31:
17842           stack[++stacki] = op - DW_OP_reg0;
17843           if (i < size)
17844             dwarf2_complex_location_expr_complaint ();
17845           break;
17846
17847         case DW_OP_regx:
17848           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
17849           i += bytes_read;
17850           stack[++stacki] = unsnd;
17851           if (i < size)
17852             dwarf2_complex_location_expr_complaint ();
17853           break;
17854
17855         case DW_OP_addr:
17856           stack[++stacki] = read_address (objfile->obfd, &data[i],
17857                                           cu, &bytes_read);
17858           i += bytes_read;
17859           break;
17860
17861         case DW_OP_const1u:
17862           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
17863           i += 1;
17864           break;
17865
17866         case DW_OP_const1s:
17867           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
17868           i += 1;
17869           break;
17870
17871         case DW_OP_const2u:
17872           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
17873           i += 2;
17874           break;
17875
17876         case DW_OP_const2s:
17877           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
17878           i += 2;
17879           break;
17880
17881         case DW_OP_const4u:
17882           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
17883           i += 4;
17884           break;
17885
17886         case DW_OP_const4s:
17887           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
17888           i += 4;
17889           break;
17890
17891         case DW_OP_const8u:
17892           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
17893           i += 8;
17894           break;
17895
17896         case DW_OP_constu:
17897           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
17898                                                   &bytes_read);
17899           i += bytes_read;
17900           break;
17901
17902         case DW_OP_consts:
17903           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
17904           i += bytes_read;
17905           break;
17906
17907         case DW_OP_dup:
17908           stack[stacki + 1] = stack[stacki];
17909           stacki++;
17910           break;
17911
17912         case DW_OP_plus:
17913           stack[stacki - 1] += stack[stacki];
17914           stacki--;
17915           break;
17916
17917         case DW_OP_plus_uconst:
17918           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
17919                                                  &bytes_read);
17920           i += bytes_read;
17921           break;
17922
17923         case DW_OP_minus:
17924           stack[stacki - 1] -= stack[stacki];
17925           stacki--;
17926           break;
17927
17928         case DW_OP_deref:
17929           /* If we're not the last op, then we definitely can't encode
17930              this using GDB's address_class enum.  This is valid for partial
17931              global symbols, although the variable's address will be bogus
17932              in the psymtab.  */
17933           if (i < size)
17934             dwarf2_complex_location_expr_complaint ();
17935           break;
17936
17937         case DW_OP_GNU_push_tls_address:
17938           /* The top of the stack has the offset from the beginning
17939              of the thread control block at which the variable is located.  */
17940           /* Nothing should follow this operator, so the top of stack would
17941              be returned.  */
17942           /* This is valid for partial global symbols, but the variable's
17943              address will be bogus in the psymtab.  Make it always at least
17944              non-zero to not look as a variable garbage collected by linker
17945              which have DW_OP_addr 0.  */
17946           if (i < size)
17947             dwarf2_complex_location_expr_complaint ();
17948           stack[stacki]++;
17949           break;
17950
17951         case DW_OP_GNU_uninit:
17952           break;
17953
17954         case DW_OP_GNU_addr_index:
17955         case DW_OP_GNU_const_index:
17956           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
17957                                                          &bytes_read);
17958           i += bytes_read;
17959           break;
17960
17961         default:
17962           {
17963             const char *name = get_DW_OP_name (op);
17964
17965             if (name)
17966               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
17967                          name);
17968             else
17969               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
17970                          op);
17971           }
17972
17973           return (stack[stacki]);
17974         }
17975
17976       /* Enforce maximum stack depth of SIZE-1 to avoid writing
17977          outside of the allocated space.  Also enforce minimum>0.  */
17978       if (stacki >= ARRAY_SIZE (stack) - 1)
17979         {
17980           complaint (&symfile_complaints,
17981                      _("location description stack overflow"));
17982           return 0;
17983         }
17984
17985       if (stacki <= 0)
17986         {
17987           complaint (&symfile_complaints,
17988                      _("location description stack underflow"));
17989           return 0;
17990         }
17991     }
17992   return (stack[stacki]);
17993 }
17994
17995 /* memory allocation interface */
17996
17997 static struct dwarf_block *
17998 dwarf_alloc_block (struct dwarf2_cu *cu)
17999 {
18000   struct dwarf_block *blk;
18001
18002   blk = (struct dwarf_block *)
18003     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18004   return (blk);
18005 }
18006
18007 static struct die_info *
18008 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18009 {
18010   struct die_info *die;
18011   size_t size = sizeof (struct die_info);
18012
18013   if (num_attrs > 1)
18014     size += (num_attrs - 1) * sizeof (struct attribute);
18015
18016   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18017   memset (die, 0, sizeof (struct die_info));
18018   return (die);
18019 }
18020
18021 \f
18022 /* Macro support.  */
18023
18024 /* Return the full name of file number I in *LH's file name table.
18025    Use COMP_DIR as the name of the current directory of the
18026    compilation.  The result is allocated using xmalloc; the caller is
18027    responsible for freeing it.  */
18028 static char *
18029 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18030 {
18031   /* Is the file number a valid index into the line header's file name
18032      table?  Remember that file numbers start with one, not zero.  */
18033   if (1 <= file && file <= lh->num_file_names)
18034     {
18035       struct file_entry *fe = &lh->file_names[file - 1];
18036
18037       if (IS_ABSOLUTE_PATH (fe->name))
18038         return xstrdup (fe->name);
18039       else
18040         {
18041           const char *dir;
18042           int dir_len;
18043           char *full_name;
18044
18045           if (fe->dir_index)
18046             dir = lh->include_dirs[fe->dir_index - 1];
18047           else
18048             dir = comp_dir;
18049
18050           if (dir)
18051             {
18052               dir_len = strlen (dir);
18053               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
18054               strcpy (full_name, dir);
18055               full_name[dir_len] = '/';
18056               strcpy (full_name + dir_len + 1, fe->name);
18057               return full_name;
18058             }
18059           else
18060             return xstrdup (fe->name);
18061         }
18062     }
18063   else
18064     {
18065       /* The compiler produced a bogus file number.  We can at least
18066          record the macro definitions made in the file, even if we
18067          won't be able to find the file by name.  */
18068       char fake_name[80];
18069
18070       xsnprintf (fake_name, sizeof (fake_name),
18071                  "<bad macro file number %d>", file);
18072
18073       complaint (&symfile_complaints,
18074                  _("bad file number in macro information (%d)"),
18075                  file);
18076
18077       return xstrdup (fake_name);
18078     }
18079 }
18080
18081
18082 static struct macro_source_file *
18083 macro_start_file (int file, int line,
18084                   struct macro_source_file *current_file,
18085                   const char *comp_dir,
18086                   struct line_header *lh, struct objfile *objfile)
18087 {
18088   /* The full name of this source file.  */
18089   char *full_name = file_full_name (file, lh, comp_dir);
18090
18091   /* We don't create a macro table for this compilation unit
18092      at all until we actually get a filename.  */
18093   if (! pending_macros)
18094     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18095                                       objfile->per_bfd->macro_cache);
18096
18097   if (! current_file)
18098     {
18099       /* If we have no current file, then this must be the start_file
18100          directive for the compilation unit's main source file.  */
18101       current_file = macro_set_main (pending_macros, full_name);
18102       macro_define_special (pending_macros);
18103     }
18104   else
18105     current_file = macro_include (current_file, line, full_name);
18106
18107   xfree (full_name);
18108
18109   return current_file;
18110 }
18111
18112
18113 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18114    followed by a null byte.  */
18115 static char *
18116 copy_string (const char *buf, int len)
18117 {
18118   char *s = xmalloc (len + 1);
18119
18120   memcpy (s, buf, len);
18121   s[len] = '\0';
18122   return s;
18123 }
18124
18125
18126 static const char *
18127 consume_improper_spaces (const char *p, const char *body)
18128 {
18129   if (*p == ' ')
18130     {
18131       complaint (&symfile_complaints,
18132                  _("macro definition contains spaces "
18133                    "in formal argument list:\n`%s'"),
18134                  body);
18135
18136       while (*p == ' ')
18137         p++;
18138     }
18139
18140   return p;
18141 }
18142
18143
18144 static void
18145 parse_macro_definition (struct macro_source_file *file, int line,
18146                         const char *body)
18147 {
18148   const char *p;
18149
18150   /* The body string takes one of two forms.  For object-like macro
18151      definitions, it should be:
18152
18153         <macro name> " " <definition>
18154
18155      For function-like macro definitions, it should be:
18156
18157         <macro name> "() " <definition>
18158      or
18159         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18160
18161      Spaces may appear only where explicitly indicated, and in the
18162      <definition>.
18163
18164      The Dwarf 2 spec says that an object-like macro's name is always
18165      followed by a space, but versions of GCC around March 2002 omit
18166      the space when the macro's definition is the empty string.
18167
18168      The Dwarf 2 spec says that there should be no spaces between the
18169      formal arguments in a function-like macro's formal argument list,
18170      but versions of GCC around March 2002 include spaces after the
18171      commas.  */
18172
18173
18174   /* Find the extent of the macro name.  The macro name is terminated
18175      by either a space or null character (for an object-like macro) or
18176      an opening paren (for a function-like macro).  */
18177   for (p = body; *p; p++)
18178     if (*p == ' ' || *p == '(')
18179       break;
18180
18181   if (*p == ' ' || *p == '\0')
18182     {
18183       /* It's an object-like macro.  */
18184       int name_len = p - body;
18185       char *name = copy_string (body, name_len);
18186       const char *replacement;
18187
18188       if (*p == ' ')
18189         replacement = body + name_len + 1;
18190       else
18191         {
18192           dwarf2_macro_malformed_definition_complaint (body);
18193           replacement = body + name_len;
18194         }
18195
18196       macro_define_object (file, line, name, replacement);
18197
18198       xfree (name);
18199     }
18200   else if (*p == '(')
18201     {
18202       /* It's a function-like macro.  */
18203       char *name = copy_string (body, p - body);
18204       int argc = 0;
18205       int argv_size = 1;
18206       char **argv = xmalloc (argv_size * sizeof (*argv));
18207
18208       p++;
18209
18210       p = consume_improper_spaces (p, body);
18211
18212       /* Parse the formal argument list.  */
18213       while (*p && *p != ')')
18214         {
18215           /* Find the extent of the current argument name.  */
18216           const char *arg_start = p;
18217
18218           while (*p && *p != ',' && *p != ')' && *p != ' ')
18219             p++;
18220
18221           if (! *p || p == arg_start)
18222             dwarf2_macro_malformed_definition_complaint (body);
18223           else
18224             {
18225               /* Make sure argv has room for the new argument.  */
18226               if (argc >= argv_size)
18227                 {
18228                   argv_size *= 2;
18229                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18230                 }
18231
18232               argv[argc++] = copy_string (arg_start, p - arg_start);
18233             }
18234
18235           p = consume_improper_spaces (p, body);
18236
18237           /* Consume the comma, if present.  */
18238           if (*p == ',')
18239             {
18240               p++;
18241
18242               p = consume_improper_spaces (p, body);
18243             }
18244         }
18245
18246       if (*p == ')')
18247         {
18248           p++;
18249
18250           if (*p == ' ')
18251             /* Perfectly formed definition, no complaints.  */
18252             macro_define_function (file, line, name,
18253                                    argc, (const char **) argv,
18254                                    p + 1);
18255           else if (*p == '\0')
18256             {
18257               /* Complain, but do define it.  */
18258               dwarf2_macro_malformed_definition_complaint (body);
18259               macro_define_function (file, line, name,
18260                                      argc, (const char **) argv,
18261                                      p);
18262             }
18263           else
18264             /* Just complain.  */
18265             dwarf2_macro_malformed_definition_complaint (body);
18266         }
18267       else
18268         /* Just complain.  */
18269         dwarf2_macro_malformed_definition_complaint (body);
18270
18271       xfree (name);
18272       {
18273         int i;
18274
18275         for (i = 0; i < argc; i++)
18276           xfree (argv[i]);
18277       }
18278       xfree (argv);
18279     }
18280   else
18281     dwarf2_macro_malformed_definition_complaint (body);
18282 }
18283
18284 /* Skip some bytes from BYTES according to the form given in FORM.
18285    Returns the new pointer.  */
18286
18287 static gdb_byte *
18288 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
18289                  enum dwarf_form form,
18290                  unsigned int offset_size,
18291                  struct dwarf2_section_info *section)
18292 {
18293   unsigned int bytes_read;
18294
18295   switch (form)
18296     {
18297     case DW_FORM_data1:
18298     case DW_FORM_flag:
18299       ++bytes;
18300       break;
18301
18302     case DW_FORM_data2:
18303       bytes += 2;
18304       break;
18305
18306     case DW_FORM_data4:
18307       bytes += 4;
18308       break;
18309
18310     case DW_FORM_data8:
18311       bytes += 8;
18312       break;
18313
18314     case DW_FORM_string:
18315       read_direct_string (abfd, bytes, &bytes_read);
18316       bytes += bytes_read;
18317       break;
18318
18319     case DW_FORM_sec_offset:
18320     case DW_FORM_strp:
18321     case DW_FORM_GNU_strp_alt:
18322       bytes += offset_size;
18323       break;
18324
18325     case DW_FORM_block:
18326       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18327       bytes += bytes_read;
18328       break;
18329
18330     case DW_FORM_block1:
18331       bytes += 1 + read_1_byte (abfd, bytes);
18332       break;
18333     case DW_FORM_block2:
18334       bytes += 2 + read_2_bytes (abfd, bytes);
18335       break;
18336     case DW_FORM_block4:
18337       bytes += 4 + read_4_bytes (abfd, bytes);
18338       break;
18339
18340     case DW_FORM_sdata:
18341     case DW_FORM_udata:
18342     case DW_FORM_GNU_addr_index:
18343     case DW_FORM_GNU_str_index:
18344       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
18345       if (bytes == NULL)
18346         {
18347           dwarf2_section_buffer_overflow_complaint (section);
18348           return NULL;
18349         }
18350       break;
18351
18352     default:
18353       {
18354       complain:
18355         complaint (&symfile_complaints,
18356                    _("invalid form 0x%x in `%s'"),
18357                    form,
18358                    section->asection->name);
18359         return NULL;
18360       }
18361     }
18362
18363   return bytes;
18364 }
18365
18366 /* A helper for dwarf_decode_macros that handles skipping an unknown
18367    opcode.  Returns an updated pointer to the macro data buffer; or,
18368    on error, issues a complaint and returns NULL.  */
18369
18370 static gdb_byte *
18371 skip_unknown_opcode (unsigned int opcode,
18372                      gdb_byte **opcode_definitions,
18373                      gdb_byte *mac_ptr, gdb_byte *mac_end,
18374                      bfd *abfd,
18375                      unsigned int offset_size,
18376                      struct dwarf2_section_info *section)
18377 {
18378   unsigned int bytes_read, i;
18379   unsigned long arg;
18380   gdb_byte *defn;
18381
18382   if (opcode_definitions[opcode] == NULL)
18383     {
18384       complaint (&symfile_complaints,
18385                  _("unrecognized DW_MACFINO opcode 0x%x"),
18386                  opcode);
18387       return NULL;
18388     }
18389
18390   defn = opcode_definitions[opcode];
18391   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18392   defn += bytes_read;
18393
18394   for (i = 0; i < arg; ++i)
18395     {
18396       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18397                                  section);
18398       if (mac_ptr == NULL)
18399         {
18400           /* skip_form_bytes already issued the complaint.  */
18401           return NULL;
18402         }
18403     }
18404
18405   return mac_ptr;
18406 }
18407
18408 /* A helper function which parses the header of a macro section.
18409    If the macro section is the extended (for now called "GNU") type,
18410    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18411    the header, or issues a complaint and returns NULL on error.  */
18412
18413 static gdb_byte *
18414 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
18415                           bfd *abfd,
18416                           gdb_byte *mac_ptr,
18417                           unsigned int *offset_size,
18418                           int section_is_gnu)
18419 {
18420   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18421
18422   if (section_is_gnu)
18423     {
18424       unsigned int version, flags;
18425
18426       version = read_2_bytes (abfd, mac_ptr);
18427       if (version != 4)
18428         {
18429           complaint (&symfile_complaints,
18430                      _("unrecognized version `%d' in .debug_macro section"),
18431                      version);
18432           return NULL;
18433         }
18434       mac_ptr += 2;
18435
18436       flags = read_1_byte (abfd, mac_ptr);
18437       ++mac_ptr;
18438       *offset_size = (flags & 1) ? 8 : 4;
18439
18440       if ((flags & 2) != 0)
18441         /* We don't need the line table offset.  */
18442         mac_ptr += *offset_size;
18443
18444       /* Vendor opcode descriptions.  */
18445       if ((flags & 4) != 0)
18446         {
18447           unsigned int i, count;
18448
18449           count = read_1_byte (abfd, mac_ptr);
18450           ++mac_ptr;
18451           for (i = 0; i < count; ++i)
18452             {
18453               unsigned int opcode, bytes_read;
18454               unsigned long arg;
18455
18456               opcode = read_1_byte (abfd, mac_ptr);
18457               ++mac_ptr;
18458               opcode_definitions[opcode] = mac_ptr;
18459               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18460               mac_ptr += bytes_read;
18461               mac_ptr += arg;
18462             }
18463         }
18464     }
18465
18466   return mac_ptr;
18467 }
18468
18469 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18470    including DW_MACRO_GNU_transparent_include.  */
18471
18472 static void
18473 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
18474                           struct macro_source_file *current_file,
18475                           struct line_header *lh, const char *comp_dir,
18476                           struct dwarf2_section_info *section,
18477                           int section_is_gnu, int section_is_dwz,
18478                           unsigned int offset_size,
18479                           struct objfile *objfile,
18480                           htab_t include_hash)
18481 {
18482   enum dwarf_macro_record_type macinfo_type;
18483   int at_commandline;
18484   gdb_byte *opcode_definitions[256];
18485
18486   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18487                                       &offset_size, section_is_gnu);
18488   if (mac_ptr == NULL)
18489     {
18490       /* We already issued a complaint.  */
18491       return;
18492     }
18493
18494   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18495      GDB is still reading the definitions from command line.  First
18496      DW_MACINFO_start_file will need to be ignored as it was already executed
18497      to create CURRENT_FILE for the main source holding also the command line
18498      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18499      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18500
18501   at_commandline = 1;
18502
18503   do
18504     {
18505       /* Do we at least have room for a macinfo type byte?  */
18506       if (mac_ptr >= mac_end)
18507         {
18508           dwarf2_section_buffer_overflow_complaint (section);
18509           break;
18510         }
18511
18512       macinfo_type = read_1_byte (abfd, mac_ptr);
18513       mac_ptr++;
18514
18515       /* Note that we rely on the fact that the corresponding GNU and
18516          DWARF constants are the same.  */
18517       switch (macinfo_type)
18518         {
18519           /* A zero macinfo type indicates the end of the macro
18520              information.  */
18521         case 0:
18522           break;
18523
18524         case DW_MACRO_GNU_define:
18525         case DW_MACRO_GNU_undef:
18526         case DW_MACRO_GNU_define_indirect:
18527         case DW_MACRO_GNU_undef_indirect:
18528         case DW_MACRO_GNU_define_indirect_alt:
18529         case DW_MACRO_GNU_undef_indirect_alt:
18530           {
18531             unsigned int bytes_read;
18532             int line;
18533             char *body;
18534             int is_define;
18535
18536             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18537             mac_ptr += bytes_read;
18538
18539             if (macinfo_type == DW_MACRO_GNU_define
18540                 || macinfo_type == DW_MACRO_GNU_undef)
18541               {
18542                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18543                 mac_ptr += bytes_read;
18544               }
18545             else
18546               {
18547                 LONGEST str_offset;
18548
18549                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18550                 mac_ptr += offset_size;
18551
18552                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18553                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18554                     || section_is_dwz)
18555                   {
18556                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18557
18558                     body = read_indirect_string_from_dwz (dwz, str_offset);
18559                   }
18560                 else
18561                   body = read_indirect_string_at_offset (abfd, str_offset);
18562               }
18563
18564             is_define = (macinfo_type == DW_MACRO_GNU_define
18565                          || macinfo_type == DW_MACRO_GNU_define_indirect
18566                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18567             if (! current_file)
18568               {
18569                 /* DWARF violation as no main source is present.  */
18570                 complaint (&symfile_complaints,
18571                            _("debug info with no main source gives macro %s "
18572                              "on line %d: %s"),
18573                            is_define ? _("definition") : _("undefinition"),
18574                            line, body);
18575                 break;
18576               }
18577             if ((line == 0 && !at_commandline)
18578                 || (line != 0 && at_commandline))
18579               complaint (&symfile_complaints,
18580                          _("debug info gives %s macro %s with %s line %d: %s"),
18581                          at_commandline ? _("command-line") : _("in-file"),
18582                          is_define ? _("definition") : _("undefinition"),
18583                          line == 0 ? _("zero") : _("non-zero"), line, body);
18584
18585             if (is_define)
18586               parse_macro_definition (current_file, line, body);
18587             else
18588               {
18589                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18590                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18591                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18592                 macro_undef (current_file, line, body);
18593               }
18594           }
18595           break;
18596
18597         case DW_MACRO_GNU_start_file:
18598           {
18599             unsigned int bytes_read;
18600             int line, file;
18601
18602             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18603             mac_ptr += bytes_read;
18604             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18605             mac_ptr += bytes_read;
18606
18607             if ((line == 0 && !at_commandline)
18608                 || (line != 0 && at_commandline))
18609               complaint (&symfile_complaints,
18610                          _("debug info gives source %d included "
18611                            "from %s at %s line %d"),
18612                          file, at_commandline ? _("command-line") : _("file"),
18613                          line == 0 ? _("zero") : _("non-zero"), line);
18614
18615             if (at_commandline)
18616               {
18617                 /* This DW_MACRO_GNU_start_file was executed in the
18618                    pass one.  */
18619                 at_commandline = 0;
18620               }
18621             else
18622               current_file = macro_start_file (file, line,
18623                                                current_file, comp_dir,
18624                                                lh, objfile);
18625           }
18626           break;
18627
18628         case DW_MACRO_GNU_end_file:
18629           if (! current_file)
18630             complaint (&symfile_complaints,
18631                        _("macro debug info has an unmatched "
18632                          "`close_file' directive"));
18633           else
18634             {
18635               current_file = current_file->included_by;
18636               if (! current_file)
18637                 {
18638                   enum dwarf_macro_record_type next_type;
18639
18640                   /* GCC circa March 2002 doesn't produce the zero
18641                      type byte marking the end of the compilation
18642                      unit.  Complain if it's not there, but exit no
18643                      matter what.  */
18644
18645                   /* Do we at least have room for a macinfo type byte?  */
18646                   if (mac_ptr >= mac_end)
18647                     {
18648                       dwarf2_section_buffer_overflow_complaint (section);
18649                       return;
18650                     }
18651
18652                   /* We don't increment mac_ptr here, so this is just
18653                      a look-ahead.  */
18654                   next_type = read_1_byte (abfd, mac_ptr);
18655                   if (next_type != 0)
18656                     complaint (&symfile_complaints,
18657                                _("no terminating 0-type entry for "
18658                                  "macros in `.debug_macinfo' section"));
18659
18660                   return;
18661                 }
18662             }
18663           break;
18664
18665         case DW_MACRO_GNU_transparent_include:
18666         case DW_MACRO_GNU_transparent_include_alt:
18667           {
18668             LONGEST offset;
18669             void **slot;
18670             bfd *include_bfd = abfd;
18671             struct dwarf2_section_info *include_section = section;
18672             struct dwarf2_section_info alt_section;
18673             gdb_byte *include_mac_end = mac_end;
18674             int is_dwz = section_is_dwz;
18675             gdb_byte *new_mac_ptr;
18676
18677             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18678             mac_ptr += offset_size;
18679
18680             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18681               {
18682                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18683
18684                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18685                                      &dwz->macro);
18686
18687                 include_bfd = dwz->macro.asection->owner;
18688                 include_section = &dwz->macro;
18689                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18690                 is_dwz = 1;
18691               }
18692
18693             new_mac_ptr = include_section->buffer + offset;
18694             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18695
18696             if (*slot != NULL)
18697               {
18698                 /* This has actually happened; see
18699                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18700                 complaint (&symfile_complaints,
18701                            _("recursive DW_MACRO_GNU_transparent_include in "
18702                              ".debug_macro section"));
18703               }
18704             else
18705               {
18706                 *slot = new_mac_ptr;
18707
18708                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18709                                           include_mac_end, current_file,
18710                                           lh, comp_dir,
18711                                           section, section_is_gnu, is_dwz,
18712                                           offset_size, objfile, include_hash);
18713
18714                 htab_remove_elt (include_hash, new_mac_ptr);
18715               }
18716           }
18717           break;
18718
18719         case DW_MACINFO_vendor_ext:
18720           if (!section_is_gnu)
18721             {
18722               unsigned int bytes_read;
18723               int constant;
18724
18725               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18726               mac_ptr += bytes_read;
18727               read_direct_string (abfd, mac_ptr, &bytes_read);
18728               mac_ptr += bytes_read;
18729
18730               /* We don't recognize any vendor extensions.  */
18731               break;
18732             }
18733           /* FALLTHROUGH */
18734
18735         default:
18736           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18737                                          mac_ptr, mac_end, abfd, offset_size,
18738                                          section);
18739           if (mac_ptr == NULL)
18740             return;
18741           break;
18742         }
18743     } while (macinfo_type != 0);
18744 }
18745
18746 static void
18747 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18748                      const char *comp_dir, int section_is_gnu)
18749 {
18750   struct objfile *objfile = dwarf2_per_objfile->objfile;
18751   struct line_header *lh = cu->line_header;
18752   bfd *abfd;
18753   gdb_byte *mac_ptr, *mac_end;
18754   struct macro_source_file *current_file = 0;
18755   enum dwarf_macro_record_type macinfo_type;
18756   unsigned int offset_size = cu->header.offset_size;
18757   gdb_byte *opcode_definitions[256];
18758   struct cleanup *cleanup;
18759   htab_t include_hash;
18760   void **slot;
18761   struct dwarf2_section_info *section;
18762   const char *section_name;
18763
18764   if (cu->dwo_unit != NULL)
18765     {
18766       if (section_is_gnu)
18767         {
18768           section = &cu->dwo_unit->dwo_file->sections.macro;
18769           section_name = ".debug_macro.dwo";
18770         }
18771       else
18772         {
18773           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18774           section_name = ".debug_macinfo.dwo";
18775         }
18776     }
18777   else
18778     {
18779       if (section_is_gnu)
18780         {
18781           section = &dwarf2_per_objfile->macro;
18782           section_name = ".debug_macro";
18783         }
18784       else
18785         {
18786           section = &dwarf2_per_objfile->macinfo;
18787           section_name = ".debug_macinfo";
18788         }
18789     }
18790
18791   dwarf2_read_section (objfile, section);
18792   if (section->buffer == NULL)
18793     {
18794       complaint (&symfile_complaints, _("missing %s section"), section_name);
18795       return;
18796     }
18797   abfd = section->asection->owner;
18798
18799   /* First pass: Find the name of the base filename.
18800      This filename is needed in order to process all macros whose definition
18801      (or undefinition) comes from the command line.  These macros are defined
18802      before the first DW_MACINFO_start_file entry, and yet still need to be
18803      associated to the base file.
18804
18805      To determine the base file name, we scan the macro definitions until we
18806      reach the first DW_MACINFO_start_file entry.  We then initialize
18807      CURRENT_FILE accordingly so that any macro definition found before the
18808      first DW_MACINFO_start_file can still be associated to the base file.  */
18809
18810   mac_ptr = section->buffer + offset;
18811   mac_end = section->buffer + section->size;
18812
18813   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18814                                       &offset_size, section_is_gnu);
18815   if (mac_ptr == NULL)
18816     {
18817       /* We already issued a complaint.  */
18818       return;
18819     }
18820
18821   do
18822     {
18823       /* Do we at least have room for a macinfo type byte?  */
18824       if (mac_ptr >= mac_end)
18825         {
18826           /* Complaint is printed during the second pass as GDB will probably
18827              stop the first pass earlier upon finding
18828              DW_MACINFO_start_file.  */
18829           break;
18830         }
18831
18832       macinfo_type = read_1_byte (abfd, mac_ptr);
18833       mac_ptr++;
18834
18835       /* Note that we rely on the fact that the corresponding GNU and
18836          DWARF constants are the same.  */
18837       switch (macinfo_type)
18838         {
18839           /* A zero macinfo type indicates the end of the macro
18840              information.  */
18841         case 0:
18842           break;
18843
18844         case DW_MACRO_GNU_define:
18845         case DW_MACRO_GNU_undef:
18846           /* Only skip the data by MAC_PTR.  */
18847           {
18848             unsigned int bytes_read;
18849
18850             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18851             mac_ptr += bytes_read;
18852             read_direct_string (abfd, mac_ptr, &bytes_read);
18853             mac_ptr += bytes_read;
18854           }
18855           break;
18856
18857         case DW_MACRO_GNU_start_file:
18858           {
18859             unsigned int bytes_read;
18860             int line, file;
18861
18862             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18863             mac_ptr += bytes_read;
18864             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18865             mac_ptr += bytes_read;
18866
18867             current_file = macro_start_file (file, line, current_file,
18868                                              comp_dir, lh, objfile);
18869           }
18870           break;
18871
18872         case DW_MACRO_GNU_end_file:
18873           /* No data to skip by MAC_PTR.  */
18874           break;
18875
18876         case DW_MACRO_GNU_define_indirect:
18877         case DW_MACRO_GNU_undef_indirect:
18878         case DW_MACRO_GNU_define_indirect_alt:
18879         case DW_MACRO_GNU_undef_indirect_alt:
18880           {
18881             unsigned int bytes_read;
18882
18883             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18884             mac_ptr += bytes_read;
18885             mac_ptr += offset_size;
18886           }
18887           break;
18888
18889         case DW_MACRO_GNU_transparent_include:
18890         case DW_MACRO_GNU_transparent_include_alt:
18891           /* Note that, according to the spec, a transparent include
18892              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
18893              skip this opcode.  */
18894           mac_ptr += offset_size;
18895           break;
18896
18897         case DW_MACINFO_vendor_ext:
18898           /* Only skip the data by MAC_PTR.  */
18899           if (!section_is_gnu)
18900             {
18901               unsigned int bytes_read;
18902
18903               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18904               mac_ptr += bytes_read;
18905               read_direct_string (abfd, mac_ptr, &bytes_read);
18906               mac_ptr += bytes_read;
18907             }
18908           /* FALLTHROUGH */
18909
18910         default:
18911           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18912                                          mac_ptr, mac_end, abfd, offset_size,
18913                                          section);
18914           if (mac_ptr == NULL)
18915             return;
18916           break;
18917         }
18918     } while (macinfo_type != 0 && current_file == NULL);
18919
18920   /* Second pass: Process all entries.
18921
18922      Use the AT_COMMAND_LINE flag to determine whether we are still processing
18923      command-line macro definitions/undefinitions.  This flag is unset when we
18924      reach the first DW_MACINFO_start_file entry.  */
18925
18926   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
18927                                     NULL, xcalloc, xfree);
18928   cleanup = make_cleanup_htab_delete (include_hash);
18929   mac_ptr = section->buffer + offset;
18930   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
18931   *slot = mac_ptr;
18932   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
18933                             current_file, lh, comp_dir, section,
18934                             section_is_gnu, 0,
18935                             offset_size, objfile, include_hash);
18936   do_cleanups (cleanup);
18937 }
18938
18939 /* Check if the attribute's form is a DW_FORM_block*
18940    if so return true else false.  */
18941
18942 static int
18943 attr_form_is_block (struct attribute *attr)
18944 {
18945   return (attr == NULL ? 0 :
18946       attr->form == DW_FORM_block1
18947       || attr->form == DW_FORM_block2
18948       || attr->form == DW_FORM_block4
18949       || attr->form == DW_FORM_block
18950       || attr->form == DW_FORM_exprloc);
18951 }
18952
18953 /* Return non-zero if ATTR's value is a section offset --- classes
18954    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
18955    You may use DW_UNSND (attr) to retrieve such offsets.
18956
18957    Section 7.5.4, "Attribute Encodings", explains that no attribute
18958    may have a value that belongs to more than one of these classes; it
18959    would be ambiguous if we did, because we use the same forms for all
18960    of them.  */
18961
18962 static int
18963 attr_form_is_section_offset (struct attribute *attr)
18964 {
18965   return (attr->form == DW_FORM_data4
18966           || attr->form == DW_FORM_data8
18967           || attr->form == DW_FORM_sec_offset);
18968 }
18969
18970 /* Return non-zero if ATTR's value falls in the 'constant' class, or
18971    zero otherwise.  When this function returns true, you can apply
18972    dwarf2_get_attr_constant_value to it.
18973
18974    However, note that for some attributes you must check
18975    attr_form_is_section_offset before using this test.  DW_FORM_data4
18976    and DW_FORM_data8 are members of both the constant class, and of
18977    the classes that contain offsets into other debug sections
18978    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
18979    that, if an attribute's can be either a constant or one of the
18980    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
18981    taken as section offsets, not constants.  */
18982
18983 static int
18984 attr_form_is_constant (struct attribute *attr)
18985 {
18986   switch (attr->form)
18987     {
18988     case DW_FORM_sdata:
18989     case DW_FORM_udata:
18990     case DW_FORM_data1:
18991     case DW_FORM_data2:
18992     case DW_FORM_data4:
18993     case DW_FORM_data8:
18994       return 1;
18995     default:
18996       return 0;
18997     }
18998 }
18999
19000 /* Return the .debug_loc section to use for CU.
19001    For DWO files use .debug_loc.dwo.  */
19002
19003 static struct dwarf2_section_info *
19004 cu_debug_loc_section (struct dwarf2_cu *cu)
19005 {
19006   if (cu->dwo_unit)
19007     return &cu->dwo_unit->dwo_file->sections.loc;
19008   return &dwarf2_per_objfile->loc;
19009 }
19010
19011 /* A helper function that fills in a dwarf2_loclist_baton.  */
19012
19013 static void
19014 fill_in_loclist_baton (struct dwarf2_cu *cu,
19015                        struct dwarf2_loclist_baton *baton,
19016                        struct attribute *attr)
19017 {
19018   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19019
19020   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19021
19022   baton->per_cu = cu->per_cu;
19023   gdb_assert (baton->per_cu);
19024   /* We don't know how long the location list is, but make sure we
19025      don't run off the edge of the section.  */
19026   baton->size = section->size - DW_UNSND (attr);
19027   baton->data = section->buffer + DW_UNSND (attr);
19028   baton->base_address = cu->base_address;
19029   baton->from_dwo = cu->dwo_unit != NULL;
19030 }
19031
19032 static void
19033 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19034                              struct dwarf2_cu *cu)
19035 {
19036   struct objfile *objfile = dwarf2_per_objfile->objfile;
19037   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19038
19039   if (attr_form_is_section_offset (attr)
19040       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19041          the section.  If so, fall through to the complaint in the
19042          other branch.  */
19043       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19044     {
19045       struct dwarf2_loclist_baton *baton;
19046
19047       baton = obstack_alloc (&objfile->objfile_obstack,
19048                              sizeof (struct dwarf2_loclist_baton));
19049
19050       fill_in_loclist_baton (cu, baton, attr);
19051
19052       if (cu->base_known == 0)
19053         complaint (&symfile_complaints,
19054                    _("Location list used without "
19055                      "specifying the CU base address."));
19056
19057       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
19058       SYMBOL_LOCATION_BATON (sym) = baton;
19059     }
19060   else
19061     {
19062       struct dwarf2_locexpr_baton *baton;
19063
19064       baton = obstack_alloc (&objfile->objfile_obstack,
19065                              sizeof (struct dwarf2_locexpr_baton));
19066       baton->per_cu = cu->per_cu;
19067       gdb_assert (baton->per_cu);
19068
19069       if (attr_form_is_block (attr))
19070         {
19071           /* Note that we're just copying the block's data pointer
19072              here, not the actual data.  We're still pointing into the
19073              info_buffer for SYM's objfile; right now we never release
19074              that buffer, but when we do clean up properly this may
19075              need to change.  */
19076           baton->size = DW_BLOCK (attr)->size;
19077           baton->data = DW_BLOCK (attr)->data;
19078         }
19079       else
19080         {
19081           dwarf2_invalid_attrib_class_complaint ("location description",
19082                                                  SYMBOL_NATURAL_NAME (sym));
19083           baton->size = 0;
19084         }
19085
19086       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
19087       SYMBOL_LOCATION_BATON (sym) = baton;
19088     }
19089 }
19090
19091 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19092    came from a separate debuginfo file, then the master objfile is
19093    returned.  */
19094
19095 struct objfile *
19096 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19097 {
19098   struct objfile *objfile = per_cu->objfile;
19099
19100   /* Return the master objfile, so that we can report and look up the
19101      correct file containing this variable.  */
19102   if (objfile->separate_debug_objfile_backlink)
19103     objfile = objfile->separate_debug_objfile_backlink;
19104
19105   return objfile;
19106 }
19107
19108 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19109    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19110    CU_HEADERP first.  */
19111
19112 static const struct comp_unit_head *
19113 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19114                        struct dwarf2_per_cu_data *per_cu)
19115 {
19116   gdb_byte *info_ptr;
19117
19118   if (per_cu->cu)
19119     return &per_cu->cu->header;
19120
19121   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
19122
19123   memset (cu_headerp, 0, sizeof (*cu_headerp));
19124   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19125
19126   return cu_headerp;
19127 }
19128
19129 /* Return the address size given in the compilation unit header for CU.  */
19130
19131 int
19132 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19133 {
19134   struct comp_unit_head cu_header_local;
19135   const struct comp_unit_head *cu_headerp;
19136
19137   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19138
19139   return cu_headerp->addr_size;
19140 }
19141
19142 /* Return the offset size given in the compilation unit header for CU.  */
19143
19144 int
19145 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19146 {
19147   struct comp_unit_head cu_header_local;
19148   const struct comp_unit_head *cu_headerp;
19149
19150   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19151
19152   return cu_headerp->offset_size;
19153 }
19154
19155 /* See its dwarf2loc.h declaration.  */
19156
19157 int
19158 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19159 {
19160   struct comp_unit_head cu_header_local;
19161   const struct comp_unit_head *cu_headerp;
19162
19163   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19164
19165   if (cu_headerp->version == 2)
19166     return cu_headerp->addr_size;
19167   else
19168     return cu_headerp->offset_size;
19169 }
19170
19171 /* Return the text offset of the CU.  The returned offset comes from
19172    this CU's objfile.  If this objfile came from a separate debuginfo
19173    file, then the offset may be different from the corresponding
19174    offset in the parent objfile.  */
19175
19176 CORE_ADDR
19177 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19178 {
19179   struct objfile *objfile = per_cu->objfile;
19180
19181   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19182 }
19183
19184 /* Locate the .debug_info compilation unit from CU's objfile which contains
19185    the DIE at OFFSET.  Raises an error on failure.  */
19186
19187 static struct dwarf2_per_cu_data *
19188 dwarf2_find_containing_comp_unit (sect_offset offset,
19189                                   unsigned int offset_in_dwz,
19190                                   struct objfile *objfile)
19191 {
19192   struct dwarf2_per_cu_data *this_cu;
19193   int low, high;
19194   const sect_offset *cu_off;
19195
19196   low = 0;
19197   high = dwarf2_per_objfile->n_comp_units - 1;
19198   while (high > low)
19199     {
19200       struct dwarf2_per_cu_data *mid_cu;
19201       int mid = low + (high - low) / 2;
19202
19203       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19204       cu_off = &mid_cu->offset;
19205       if (mid_cu->is_dwz > offset_in_dwz
19206           || (mid_cu->is_dwz == offset_in_dwz
19207               && cu_off->sect_off >= offset.sect_off))
19208         high = mid;
19209       else
19210         low = mid + 1;
19211     }
19212   gdb_assert (low == high);
19213   this_cu = dwarf2_per_objfile->all_comp_units[low];
19214   cu_off = &this_cu->offset;
19215   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19216     {
19217       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19218         error (_("Dwarf Error: could not find partial DIE containing "
19219                "offset 0x%lx [in module %s]"),
19220                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19221
19222       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19223                   <= offset.sect_off);
19224       return dwarf2_per_objfile->all_comp_units[low-1];
19225     }
19226   else
19227     {
19228       this_cu = dwarf2_per_objfile->all_comp_units[low];
19229       if (low == dwarf2_per_objfile->n_comp_units - 1
19230           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19231         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19232       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19233       return this_cu;
19234     }
19235 }
19236
19237 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19238
19239 static void
19240 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19241 {
19242   memset (cu, 0, sizeof (*cu));
19243   per_cu->cu = cu;
19244   cu->per_cu = per_cu;
19245   cu->objfile = per_cu->objfile;
19246   obstack_init (&cu->comp_unit_obstack);
19247 }
19248
19249 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19250
19251 static void
19252 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19253                        enum language pretend_language)
19254 {
19255   struct attribute *attr;
19256
19257   /* Set the language we're debugging.  */
19258   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19259   if (attr)
19260     set_cu_language (DW_UNSND (attr), cu);
19261   else
19262     {
19263       cu->language = pretend_language;
19264       cu->language_defn = language_def (cu->language);
19265     }
19266
19267   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19268   if (attr)
19269     cu->producer = DW_STRING (attr);
19270 }
19271
19272 /* Release one cached compilation unit, CU.  We unlink it from the tree
19273    of compilation units, but we don't remove it from the read_in_chain;
19274    the caller is responsible for that.
19275    NOTE: DATA is a void * because this function is also used as a
19276    cleanup routine.  */
19277
19278 static void
19279 free_heap_comp_unit (void *data)
19280 {
19281   struct dwarf2_cu *cu = data;
19282
19283   gdb_assert (cu->per_cu != NULL);
19284   cu->per_cu->cu = NULL;
19285   cu->per_cu = NULL;
19286
19287   obstack_free (&cu->comp_unit_obstack, NULL);
19288
19289   xfree (cu);
19290 }
19291
19292 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19293    when we're finished with it.  We can't free the pointer itself, but be
19294    sure to unlink it from the cache.  Also release any associated storage.  */
19295
19296 static void
19297 free_stack_comp_unit (void *data)
19298 {
19299   struct dwarf2_cu *cu = data;
19300
19301   gdb_assert (cu->per_cu != NULL);
19302   cu->per_cu->cu = NULL;
19303   cu->per_cu = NULL;
19304
19305   obstack_free (&cu->comp_unit_obstack, NULL);
19306   cu->partial_dies = NULL;
19307 }
19308
19309 /* Free all cached compilation units.  */
19310
19311 static void
19312 free_cached_comp_units (void *data)
19313 {
19314   struct dwarf2_per_cu_data *per_cu, **last_chain;
19315
19316   per_cu = dwarf2_per_objfile->read_in_chain;
19317   last_chain = &dwarf2_per_objfile->read_in_chain;
19318   while (per_cu != NULL)
19319     {
19320       struct dwarf2_per_cu_data *next_cu;
19321
19322       next_cu = per_cu->cu->read_in_chain;
19323
19324       free_heap_comp_unit (per_cu->cu);
19325       *last_chain = next_cu;
19326
19327       per_cu = next_cu;
19328     }
19329 }
19330
19331 /* Increase the age counter on each cached compilation unit, and free
19332    any that are too old.  */
19333
19334 static void
19335 age_cached_comp_units (void)
19336 {
19337   struct dwarf2_per_cu_data *per_cu, **last_chain;
19338
19339   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19340   per_cu = dwarf2_per_objfile->read_in_chain;
19341   while (per_cu != NULL)
19342     {
19343       per_cu->cu->last_used ++;
19344       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19345         dwarf2_mark (per_cu->cu);
19346       per_cu = per_cu->cu->read_in_chain;
19347     }
19348
19349   per_cu = dwarf2_per_objfile->read_in_chain;
19350   last_chain = &dwarf2_per_objfile->read_in_chain;
19351   while (per_cu != NULL)
19352     {
19353       struct dwarf2_per_cu_data *next_cu;
19354
19355       next_cu = per_cu->cu->read_in_chain;
19356
19357       if (!per_cu->cu->mark)
19358         {
19359           free_heap_comp_unit (per_cu->cu);
19360           *last_chain = next_cu;
19361         }
19362       else
19363         last_chain = &per_cu->cu->read_in_chain;
19364
19365       per_cu = next_cu;
19366     }
19367 }
19368
19369 /* Remove a single compilation unit from the cache.  */
19370
19371 static void
19372 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19373 {
19374   struct dwarf2_per_cu_data *per_cu, **last_chain;
19375
19376   per_cu = dwarf2_per_objfile->read_in_chain;
19377   last_chain = &dwarf2_per_objfile->read_in_chain;
19378   while (per_cu != NULL)
19379     {
19380       struct dwarf2_per_cu_data *next_cu;
19381
19382       next_cu = per_cu->cu->read_in_chain;
19383
19384       if (per_cu == target_per_cu)
19385         {
19386           free_heap_comp_unit (per_cu->cu);
19387           per_cu->cu = NULL;
19388           *last_chain = next_cu;
19389           break;
19390         }
19391       else
19392         last_chain = &per_cu->cu->read_in_chain;
19393
19394       per_cu = next_cu;
19395     }
19396 }
19397
19398 /* Release all extra memory associated with OBJFILE.  */
19399
19400 void
19401 dwarf2_free_objfile (struct objfile *objfile)
19402 {
19403   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19404
19405   if (dwarf2_per_objfile == NULL)
19406     return;
19407
19408   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19409   free_cached_comp_units (NULL);
19410
19411   if (dwarf2_per_objfile->quick_file_names_table)
19412     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19413
19414   /* Everything else should be on the objfile obstack.  */
19415 }
19416
19417 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19418    We store these in a hash table separate from the DIEs, and preserve them
19419    when the DIEs are flushed out of cache.
19420
19421    The CU "per_cu" pointer is needed because offset alone is not enough to
19422    uniquely identify the type.  A file may have multiple .debug_types sections,
19423    or the type may come from a DWO file.  We have to use something in
19424    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
19425    routine, get_die_type_at_offset, from outside this file, and thus won't
19426    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
19427    of the objfile.  */
19428
19429 struct dwarf2_per_cu_offset_and_type
19430 {
19431   const struct dwarf2_per_cu_data *per_cu;
19432   sect_offset offset;
19433   struct type *type;
19434 };
19435
19436 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19437
19438 static hashval_t
19439 per_cu_offset_and_type_hash (const void *item)
19440 {
19441   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19442
19443   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19444 }
19445
19446 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19447
19448 static int
19449 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19450 {
19451   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19452   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19453
19454   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19455           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19456 }
19457
19458 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19459    table if necessary.  For convenience, return TYPE.
19460
19461    The DIEs reading must have careful ordering to:
19462     * Not cause infite loops trying to read in DIEs as a prerequisite for
19463       reading current DIE.
19464     * Not trying to dereference contents of still incompletely read in types
19465       while reading in other DIEs.
19466     * Enable referencing still incompletely read in types just by a pointer to
19467       the type without accessing its fields.
19468
19469    Therefore caller should follow these rules:
19470      * Try to fetch any prerequisite types we may need to build this DIE type
19471        before building the type and calling set_die_type.
19472      * After building type call set_die_type for current DIE as soon as
19473        possible before fetching more types to complete the current type.
19474      * Make the type as complete as possible before fetching more types.  */
19475
19476 static struct type *
19477 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19478 {
19479   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19480   struct objfile *objfile = cu->objfile;
19481
19482   /* For Ada types, make sure that the gnat-specific data is always
19483      initialized (if not already set).  There are a few types where
19484      we should not be doing so, because the type-specific area is
19485      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19486      where the type-specific area is used to store the floatformat).
19487      But this is not a problem, because the gnat-specific information
19488      is actually not needed for these types.  */
19489   if (need_gnat_info (cu)
19490       && TYPE_CODE (type) != TYPE_CODE_FUNC
19491       && TYPE_CODE (type) != TYPE_CODE_FLT
19492       && !HAVE_GNAT_AUX_INFO (type))
19493     INIT_GNAT_SPECIFIC (type);
19494
19495   if (dwarf2_per_objfile->die_type_hash == NULL)
19496     {
19497       dwarf2_per_objfile->die_type_hash =
19498         htab_create_alloc_ex (127,
19499                               per_cu_offset_and_type_hash,
19500                               per_cu_offset_and_type_eq,
19501                               NULL,
19502                               &objfile->objfile_obstack,
19503                               hashtab_obstack_allocate,
19504                               dummy_obstack_deallocate);
19505     }
19506
19507   ofs.per_cu = cu->per_cu;
19508   ofs.offset = die->offset;
19509   ofs.type = type;
19510   slot = (struct dwarf2_per_cu_offset_and_type **)
19511     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19512   if (*slot)
19513     complaint (&symfile_complaints,
19514                _("A problem internal to GDB: DIE 0x%x has type already set"),
19515                die->offset.sect_off);
19516   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19517   **slot = ofs;
19518   return type;
19519 }
19520
19521 /* Look up the type for the die at OFFSET in the appropriate type_hash
19522    table, or return NULL if the die does not have a saved type.  */
19523
19524 static struct type *
19525 get_die_type_at_offset (sect_offset offset,
19526                         struct dwarf2_per_cu_data *per_cu)
19527 {
19528   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19529
19530   if (dwarf2_per_objfile->die_type_hash == NULL)
19531     return NULL;
19532
19533   ofs.per_cu = per_cu;
19534   ofs.offset = offset;
19535   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19536   if (slot)
19537     return slot->type;
19538   else
19539     return NULL;
19540 }
19541
19542 /* Look up the type for DIE in the appropriate type_hash table,
19543    or return NULL if DIE does not have a saved type.  */
19544
19545 static struct type *
19546 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19547 {
19548   return get_die_type_at_offset (die->offset, cu->per_cu);
19549 }
19550
19551 /* Add a dependence relationship from CU to REF_PER_CU.  */
19552
19553 static void
19554 dwarf2_add_dependence (struct dwarf2_cu *cu,
19555                        struct dwarf2_per_cu_data *ref_per_cu)
19556 {
19557   void **slot;
19558
19559   if (cu->dependencies == NULL)
19560     cu->dependencies
19561       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19562                               NULL, &cu->comp_unit_obstack,
19563                               hashtab_obstack_allocate,
19564                               dummy_obstack_deallocate);
19565
19566   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19567   if (*slot == NULL)
19568     *slot = ref_per_cu;
19569 }
19570
19571 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19572    Set the mark field in every compilation unit in the
19573    cache that we must keep because we are keeping CU.  */
19574
19575 static int
19576 dwarf2_mark_helper (void **slot, void *data)
19577 {
19578   struct dwarf2_per_cu_data *per_cu;
19579
19580   per_cu = (struct dwarf2_per_cu_data *) *slot;
19581
19582   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19583      reading of the chain.  As such dependencies remain valid it is not much
19584      useful to track and undo them during QUIT cleanups.  */
19585   if (per_cu->cu == NULL)
19586     return 1;
19587
19588   if (per_cu->cu->mark)
19589     return 1;
19590   per_cu->cu->mark = 1;
19591
19592   if (per_cu->cu->dependencies != NULL)
19593     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19594
19595   return 1;
19596 }
19597
19598 /* Set the mark field in CU and in every other compilation unit in the
19599    cache that we must keep because we are keeping CU.  */
19600
19601 static void
19602 dwarf2_mark (struct dwarf2_cu *cu)
19603 {
19604   if (cu->mark)
19605     return;
19606   cu->mark = 1;
19607   if (cu->dependencies != NULL)
19608     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19609 }
19610
19611 static void
19612 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19613 {
19614   while (per_cu)
19615     {
19616       per_cu->cu->mark = 0;
19617       per_cu = per_cu->cu->read_in_chain;
19618     }
19619 }
19620
19621 /* Trivial hash function for partial_die_info: the hash value of a DIE
19622    is its offset in .debug_info for this objfile.  */
19623
19624 static hashval_t
19625 partial_die_hash (const void *item)
19626 {
19627   const struct partial_die_info *part_die = item;
19628
19629   return part_die->offset.sect_off;
19630 }
19631
19632 /* Trivial comparison function for partial_die_info structures: two DIEs
19633    are equal if they have the same offset.  */
19634
19635 static int
19636 partial_die_eq (const void *item_lhs, const void *item_rhs)
19637 {
19638   const struct partial_die_info *part_die_lhs = item_lhs;
19639   const struct partial_die_info *part_die_rhs = item_rhs;
19640
19641   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19642 }
19643
19644 static struct cmd_list_element *set_dwarf2_cmdlist;
19645 static struct cmd_list_element *show_dwarf2_cmdlist;
19646
19647 static void
19648 set_dwarf2_cmd (char *args, int from_tty)
19649 {
19650   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19651 }
19652
19653 static void
19654 show_dwarf2_cmd (char *args, int from_tty)
19655 {
19656   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19657 }
19658
19659 /* Free data associated with OBJFILE, if necessary.  */
19660
19661 static void
19662 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19663 {
19664   struct dwarf2_per_objfile *data = d;
19665   int ix;
19666
19667   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19668     VEC_free (dwarf2_per_cu_ptr,
19669               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19670
19671   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19672     VEC_free (dwarf2_per_cu_ptr,
19673               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19674
19675   VEC_free (dwarf2_section_info_def, data->types);
19676
19677   if (data->dwo_files)
19678     free_dwo_files (data->dwo_files, objfile);
19679
19680   if (data->dwz_file && data->dwz_file->dwz_bfd)
19681     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19682 }
19683
19684 \f
19685 /* The "save gdb-index" command.  */
19686
19687 /* The contents of the hash table we create when building the string
19688    table.  */
19689 struct strtab_entry
19690 {
19691   offset_type offset;
19692   const char *str;
19693 };
19694
19695 /* Hash function for a strtab_entry.
19696
19697    Function is used only during write_hash_table so no index format backward
19698    compatibility is needed.  */
19699
19700 static hashval_t
19701 hash_strtab_entry (const void *e)
19702 {
19703   const struct strtab_entry *entry = e;
19704   return mapped_index_string_hash (INT_MAX, entry->str);
19705 }
19706
19707 /* Equality function for a strtab_entry.  */
19708
19709 static int
19710 eq_strtab_entry (const void *a, const void *b)
19711 {
19712   const struct strtab_entry *ea = a;
19713   const struct strtab_entry *eb = b;
19714   return !strcmp (ea->str, eb->str);
19715 }
19716
19717 /* Create a strtab_entry hash table.  */
19718
19719 static htab_t
19720 create_strtab (void)
19721 {
19722   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19723                             xfree, xcalloc, xfree);
19724 }
19725
19726 /* Add a string to the constant pool.  Return the string's offset in
19727    host order.  */
19728
19729 static offset_type
19730 add_string (htab_t table, struct obstack *cpool, const char *str)
19731 {
19732   void **slot;
19733   struct strtab_entry entry;
19734   struct strtab_entry *result;
19735
19736   entry.str = str;
19737   slot = htab_find_slot (table, &entry, INSERT);
19738   if (*slot)
19739     result = *slot;
19740   else
19741     {
19742       result = XNEW (struct strtab_entry);
19743       result->offset = obstack_object_size (cpool);
19744       result->str = str;
19745       obstack_grow_str0 (cpool, str);
19746       *slot = result;
19747     }
19748   return result->offset;
19749 }
19750
19751 /* An entry in the symbol table.  */
19752 struct symtab_index_entry
19753 {
19754   /* The name of the symbol.  */
19755   const char *name;
19756   /* The offset of the name in the constant pool.  */
19757   offset_type index_offset;
19758   /* A sorted vector of the indices of all the CUs that hold an object
19759      of this name.  */
19760   VEC (offset_type) *cu_indices;
19761 };
19762
19763 /* The symbol table.  This is a power-of-2-sized hash table.  */
19764 struct mapped_symtab
19765 {
19766   offset_type n_elements;
19767   offset_type size;
19768   struct symtab_index_entry **data;
19769 };
19770
19771 /* Hash function for a symtab_index_entry.  */
19772
19773 static hashval_t
19774 hash_symtab_entry (const void *e)
19775 {
19776   const struct symtab_index_entry *entry = e;
19777   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19778                          sizeof (offset_type) * VEC_length (offset_type,
19779                                                             entry->cu_indices),
19780                          0);
19781 }
19782
19783 /* Equality function for a symtab_index_entry.  */
19784
19785 static int
19786 eq_symtab_entry (const void *a, const void *b)
19787 {
19788   const struct symtab_index_entry *ea = a;
19789   const struct symtab_index_entry *eb = b;
19790   int len = VEC_length (offset_type, ea->cu_indices);
19791   if (len != VEC_length (offset_type, eb->cu_indices))
19792     return 0;
19793   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19794                   VEC_address (offset_type, eb->cu_indices),
19795                   sizeof (offset_type) * len);
19796 }
19797
19798 /* Destroy a symtab_index_entry.  */
19799
19800 static void
19801 delete_symtab_entry (void *p)
19802 {
19803   struct symtab_index_entry *entry = p;
19804   VEC_free (offset_type, entry->cu_indices);
19805   xfree (entry);
19806 }
19807
19808 /* Create a hash table holding symtab_index_entry objects.  */
19809
19810 static htab_t
19811 create_symbol_hash_table (void)
19812 {
19813   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19814                             delete_symtab_entry, xcalloc, xfree);
19815 }
19816
19817 /* Create a new mapped symtab object.  */
19818
19819 static struct mapped_symtab *
19820 create_mapped_symtab (void)
19821 {
19822   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
19823   symtab->n_elements = 0;
19824   symtab->size = 1024;
19825   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19826   return symtab;
19827 }
19828
19829 /* Destroy a mapped_symtab.  */
19830
19831 static void
19832 cleanup_mapped_symtab (void *p)
19833 {
19834   struct mapped_symtab *symtab = p;
19835   /* The contents of the array are freed when the other hash table is
19836      destroyed.  */
19837   xfree (symtab->data);
19838   xfree (symtab);
19839 }
19840
19841 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
19842    the slot.
19843    
19844    Function is used only during write_hash_table so no index format backward
19845    compatibility is needed.  */
19846
19847 static struct symtab_index_entry **
19848 find_slot (struct mapped_symtab *symtab, const char *name)
19849 {
19850   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
19851
19852   index = hash & (symtab->size - 1);
19853   step = ((hash * 17) & (symtab->size - 1)) | 1;
19854
19855   for (;;)
19856     {
19857       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
19858         return &symtab->data[index];
19859       index = (index + step) & (symtab->size - 1);
19860     }
19861 }
19862
19863 /* Expand SYMTAB's hash table.  */
19864
19865 static void
19866 hash_expand (struct mapped_symtab *symtab)
19867 {
19868   offset_type old_size = symtab->size;
19869   offset_type i;
19870   struct symtab_index_entry **old_entries = symtab->data;
19871
19872   symtab->size *= 2;
19873   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19874
19875   for (i = 0; i < old_size; ++i)
19876     {
19877       if (old_entries[i])
19878         {
19879           struct symtab_index_entry **slot = find_slot (symtab,
19880                                                         old_entries[i]->name);
19881           *slot = old_entries[i];
19882         }
19883     }
19884
19885   xfree (old_entries);
19886 }
19887
19888 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
19889    CU_INDEX is the index of the CU in which the symbol appears.
19890    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
19891
19892 static void
19893 add_index_entry (struct mapped_symtab *symtab, const char *name,
19894                  int is_static, gdb_index_symbol_kind kind,
19895                  offset_type cu_index)
19896 {
19897   struct symtab_index_entry **slot;
19898   offset_type cu_index_and_attrs;
19899
19900   ++symtab->n_elements;
19901   if (4 * symtab->n_elements / 3 >= symtab->size)
19902     hash_expand (symtab);
19903
19904   slot = find_slot (symtab, name);
19905   if (!*slot)
19906     {
19907       *slot = XNEW (struct symtab_index_entry);
19908       (*slot)->name = name;
19909       /* index_offset is set later.  */
19910       (*slot)->cu_indices = NULL;
19911     }
19912
19913   cu_index_and_attrs = 0;
19914   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
19915   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
19916   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
19917
19918   /* We don't want to record an index value twice as we want to avoid the
19919      duplication.
19920      We process all global symbols and then all static symbols
19921      (which would allow us to avoid the duplication by only having to check
19922      the last entry pushed), but a symbol could have multiple kinds in one CU.
19923      To keep things simple we don't worry about the duplication here and
19924      sort and uniqufy the list after we've processed all symbols.  */
19925   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
19926 }
19927
19928 /* qsort helper routine for uniquify_cu_indices.  */
19929
19930 static int
19931 offset_type_compare (const void *ap, const void *bp)
19932 {
19933   offset_type a = *(offset_type *) ap;
19934   offset_type b = *(offset_type *) bp;
19935
19936   return (a > b) - (b > a);
19937 }
19938
19939 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
19940
19941 static void
19942 uniquify_cu_indices (struct mapped_symtab *symtab)
19943 {
19944   int i;
19945
19946   for (i = 0; i < symtab->size; ++i)
19947     {
19948       struct symtab_index_entry *entry = symtab->data[i];
19949
19950       if (entry
19951           && entry->cu_indices != NULL)
19952         {
19953           unsigned int next_to_insert, next_to_check;
19954           offset_type last_value;
19955
19956           qsort (VEC_address (offset_type, entry->cu_indices),
19957                  VEC_length (offset_type, entry->cu_indices),
19958                  sizeof (offset_type), offset_type_compare);
19959
19960           last_value = VEC_index (offset_type, entry->cu_indices, 0);
19961           next_to_insert = 1;
19962           for (next_to_check = 1;
19963                next_to_check < VEC_length (offset_type, entry->cu_indices);
19964                ++next_to_check)
19965             {
19966               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
19967                   != last_value)
19968                 {
19969                   last_value = VEC_index (offset_type, entry->cu_indices,
19970                                           next_to_check);
19971                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
19972                                last_value);
19973                   ++next_to_insert;
19974                 }
19975             }
19976           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
19977         }
19978     }
19979 }
19980
19981 /* Add a vector of indices to the constant pool.  */
19982
19983 static offset_type
19984 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
19985                       struct symtab_index_entry *entry)
19986 {
19987   void **slot;
19988
19989   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
19990   if (!*slot)
19991     {
19992       offset_type len = VEC_length (offset_type, entry->cu_indices);
19993       offset_type val = MAYBE_SWAP (len);
19994       offset_type iter;
19995       int i;
19996
19997       *slot = entry;
19998       entry->index_offset = obstack_object_size (cpool);
19999
20000       obstack_grow (cpool, &val, sizeof (val));
20001       for (i = 0;
20002            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20003            ++i)
20004         {
20005           val = MAYBE_SWAP (iter);
20006           obstack_grow (cpool, &val, sizeof (val));
20007         }
20008     }
20009   else
20010     {
20011       struct symtab_index_entry *old_entry = *slot;
20012       entry->index_offset = old_entry->index_offset;
20013       entry = old_entry;
20014     }
20015   return entry->index_offset;
20016 }
20017
20018 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20019    constant pool entries going into the obstack CPOOL.  */
20020
20021 static void
20022 write_hash_table (struct mapped_symtab *symtab,
20023                   struct obstack *output, struct obstack *cpool)
20024 {
20025   offset_type i;
20026   htab_t symbol_hash_table;
20027   htab_t str_table;
20028
20029   symbol_hash_table = create_symbol_hash_table ();
20030   str_table = create_strtab ();
20031
20032   /* We add all the index vectors to the constant pool first, to
20033      ensure alignment is ok.  */
20034   for (i = 0; i < symtab->size; ++i)
20035     {
20036       if (symtab->data[i])
20037         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20038     }
20039
20040   /* Now write out the hash table.  */
20041   for (i = 0; i < symtab->size; ++i)
20042     {
20043       offset_type str_off, vec_off;
20044
20045       if (symtab->data[i])
20046         {
20047           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20048           vec_off = symtab->data[i]->index_offset;
20049         }
20050       else
20051         {
20052           /* While 0 is a valid constant pool index, it is not valid
20053              to have 0 for both offsets.  */
20054           str_off = 0;
20055           vec_off = 0;
20056         }
20057
20058       str_off = MAYBE_SWAP (str_off);
20059       vec_off = MAYBE_SWAP (vec_off);
20060
20061       obstack_grow (output, &str_off, sizeof (str_off));
20062       obstack_grow (output, &vec_off, sizeof (vec_off));
20063     }
20064
20065   htab_delete (str_table);
20066   htab_delete (symbol_hash_table);
20067 }
20068
20069 /* Struct to map psymtab to CU index in the index file.  */
20070 struct psymtab_cu_index_map
20071 {
20072   struct partial_symtab *psymtab;
20073   unsigned int cu_index;
20074 };
20075
20076 static hashval_t
20077 hash_psymtab_cu_index (const void *item)
20078 {
20079   const struct psymtab_cu_index_map *map = item;
20080
20081   return htab_hash_pointer (map->psymtab);
20082 }
20083
20084 static int
20085 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20086 {
20087   const struct psymtab_cu_index_map *lhs = item_lhs;
20088   const struct psymtab_cu_index_map *rhs = item_rhs;
20089
20090   return lhs->psymtab == rhs->psymtab;
20091 }
20092
20093 /* Helper struct for building the address table.  */
20094 struct addrmap_index_data
20095 {
20096   struct objfile *objfile;
20097   struct obstack *addr_obstack;
20098   htab_t cu_index_htab;
20099
20100   /* Non-zero if the previous_* fields are valid.
20101      We can't write an entry until we see the next entry (since it is only then
20102      that we know the end of the entry).  */
20103   int previous_valid;
20104   /* Index of the CU in the table of all CUs in the index file.  */
20105   unsigned int previous_cu_index;
20106   /* Start address of the CU.  */
20107   CORE_ADDR previous_cu_start;
20108 };
20109
20110 /* Write an address entry to OBSTACK.  */
20111
20112 static void
20113 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20114                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20115 {
20116   offset_type cu_index_to_write;
20117   char addr[8];
20118   CORE_ADDR baseaddr;
20119
20120   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20121
20122   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20123   obstack_grow (obstack, addr, 8);
20124   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20125   obstack_grow (obstack, addr, 8);
20126   cu_index_to_write = MAYBE_SWAP (cu_index);
20127   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20128 }
20129
20130 /* Worker function for traversing an addrmap to build the address table.  */
20131
20132 static int
20133 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20134 {
20135   struct addrmap_index_data *data = datap;
20136   struct partial_symtab *pst = obj;
20137
20138   if (data->previous_valid)
20139     add_address_entry (data->objfile, data->addr_obstack,
20140                        data->previous_cu_start, start_addr,
20141                        data->previous_cu_index);
20142
20143   data->previous_cu_start = start_addr;
20144   if (pst != NULL)
20145     {
20146       struct psymtab_cu_index_map find_map, *map;
20147       find_map.psymtab = pst;
20148       map = htab_find (data->cu_index_htab, &find_map);
20149       gdb_assert (map != NULL);
20150       data->previous_cu_index = map->cu_index;
20151       data->previous_valid = 1;
20152     }
20153   else
20154       data->previous_valid = 0;
20155
20156   return 0;
20157 }
20158
20159 /* Write OBJFILE's address map to OBSTACK.
20160    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20161    in the index file.  */
20162
20163 static void
20164 write_address_map (struct objfile *objfile, struct obstack *obstack,
20165                    htab_t cu_index_htab)
20166 {
20167   struct addrmap_index_data addrmap_index_data;
20168
20169   /* When writing the address table, we have to cope with the fact that
20170      the addrmap iterator only provides the start of a region; we have to
20171      wait until the next invocation to get the start of the next region.  */
20172
20173   addrmap_index_data.objfile = objfile;
20174   addrmap_index_data.addr_obstack = obstack;
20175   addrmap_index_data.cu_index_htab = cu_index_htab;
20176   addrmap_index_data.previous_valid = 0;
20177
20178   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20179                    &addrmap_index_data);
20180
20181   /* It's highly unlikely the last entry (end address = 0xff...ff)
20182      is valid, but we should still handle it.
20183      The end address is recorded as the start of the next region, but that
20184      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20185      anyway.  */
20186   if (addrmap_index_data.previous_valid)
20187     add_address_entry (objfile, obstack,
20188                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20189                        addrmap_index_data.previous_cu_index);
20190 }
20191
20192 /* Return the symbol kind of PSYM.  */
20193
20194 static gdb_index_symbol_kind
20195 symbol_kind (struct partial_symbol *psym)
20196 {
20197   domain_enum domain = PSYMBOL_DOMAIN (psym);
20198   enum address_class aclass = PSYMBOL_CLASS (psym);
20199
20200   switch (domain)
20201     {
20202     case VAR_DOMAIN:
20203       switch (aclass)
20204         {
20205         case LOC_BLOCK:
20206           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20207         case LOC_TYPEDEF:
20208           return GDB_INDEX_SYMBOL_KIND_TYPE;
20209         case LOC_COMPUTED:
20210         case LOC_CONST_BYTES:
20211         case LOC_OPTIMIZED_OUT:
20212         case LOC_STATIC:
20213           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20214         case LOC_CONST:
20215           /* Note: It's currently impossible to recognize psyms as enum values
20216              short of reading the type info.  For now punt.  */
20217           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20218         default:
20219           /* There are other LOC_FOO values that one might want to classify
20220              as variables, but dwarf2read.c doesn't currently use them.  */
20221           return GDB_INDEX_SYMBOL_KIND_OTHER;
20222         }
20223     case STRUCT_DOMAIN:
20224       return GDB_INDEX_SYMBOL_KIND_TYPE;
20225     default:
20226       return GDB_INDEX_SYMBOL_KIND_OTHER;
20227     }
20228 }
20229
20230 /* Add a list of partial symbols to SYMTAB.  */
20231
20232 static void
20233 write_psymbols (struct mapped_symtab *symtab,
20234                 htab_t psyms_seen,
20235                 struct partial_symbol **psymp,
20236                 int count,
20237                 offset_type cu_index,
20238                 int is_static)
20239 {
20240   for (; count-- > 0; ++psymp)
20241     {
20242       struct partial_symbol *psym = *psymp;
20243       void **slot;
20244
20245       if (SYMBOL_LANGUAGE (psym) == language_ada)
20246         error (_("Ada is not currently supported by the index"));
20247
20248       /* Only add a given psymbol once.  */
20249       slot = htab_find_slot (psyms_seen, psym, INSERT);
20250       if (!*slot)
20251         {
20252           gdb_index_symbol_kind kind = symbol_kind (psym);
20253
20254           *slot = psym;
20255           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20256                            is_static, kind, cu_index);
20257         }
20258     }
20259 }
20260
20261 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20262    exception if there is an error.  */
20263
20264 static void
20265 write_obstack (FILE *file, struct obstack *obstack)
20266 {
20267   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20268               file)
20269       != obstack_object_size (obstack))
20270     error (_("couldn't data write to file"));
20271 }
20272
20273 /* Unlink a file if the argument is not NULL.  */
20274
20275 static void
20276 unlink_if_set (void *p)
20277 {
20278   char **filename = p;
20279   if (*filename)
20280     unlink (*filename);
20281 }
20282
20283 /* A helper struct used when iterating over debug_types.  */
20284 struct signatured_type_index_data
20285 {
20286   struct objfile *objfile;
20287   struct mapped_symtab *symtab;
20288   struct obstack *types_list;
20289   htab_t psyms_seen;
20290   int cu_index;
20291 };
20292
20293 /* A helper function that writes a single signatured_type to an
20294    obstack.  */
20295
20296 static int
20297 write_one_signatured_type (void **slot, void *d)
20298 {
20299   struct signatured_type_index_data *info = d;
20300   struct signatured_type *entry = (struct signatured_type *) *slot;
20301   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
20302   struct partial_symtab *psymtab = per_cu->v.psymtab;
20303   gdb_byte val[8];
20304
20305   write_psymbols (info->symtab,
20306                   info->psyms_seen,
20307                   info->objfile->global_psymbols.list
20308                   + psymtab->globals_offset,
20309                   psymtab->n_global_syms, info->cu_index,
20310                   0);
20311   write_psymbols (info->symtab,
20312                   info->psyms_seen,
20313                   info->objfile->static_psymbols.list
20314                   + psymtab->statics_offset,
20315                   psymtab->n_static_syms, info->cu_index,
20316                   1);
20317
20318   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20319                           entry->per_cu.offset.sect_off);
20320   obstack_grow (info->types_list, val, 8);
20321   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20322                           entry->type_offset_in_tu.cu_off);
20323   obstack_grow (info->types_list, val, 8);
20324   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20325   obstack_grow (info->types_list, val, 8);
20326
20327   ++info->cu_index;
20328
20329   return 1;
20330 }
20331
20332 /* Recurse into all "included" dependencies and write their symbols as
20333    if they appeared in this psymtab.  */
20334
20335 static void
20336 recursively_write_psymbols (struct objfile *objfile,
20337                             struct partial_symtab *psymtab,
20338                             struct mapped_symtab *symtab,
20339                             htab_t psyms_seen,
20340                             offset_type cu_index)
20341 {
20342   int i;
20343
20344   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20345     if (psymtab->dependencies[i]->user != NULL)
20346       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20347                                   symtab, psyms_seen, cu_index);
20348
20349   write_psymbols (symtab,
20350                   psyms_seen,
20351                   objfile->global_psymbols.list + psymtab->globals_offset,
20352                   psymtab->n_global_syms, cu_index,
20353                   0);
20354   write_psymbols (symtab,
20355                   psyms_seen,
20356                   objfile->static_psymbols.list + psymtab->statics_offset,
20357                   psymtab->n_static_syms, cu_index,
20358                   1);
20359 }
20360
20361 /* Create an index file for OBJFILE in the directory DIR.  */
20362
20363 static void
20364 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20365 {
20366   struct cleanup *cleanup;
20367   char *filename, *cleanup_filename;
20368   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20369   struct obstack cu_list, types_cu_list;
20370   int i;
20371   FILE *out_file;
20372   struct mapped_symtab *symtab;
20373   offset_type val, size_of_contents, total_len;
20374   struct stat st;
20375   htab_t psyms_seen;
20376   htab_t cu_index_htab;
20377   struct psymtab_cu_index_map *psymtab_cu_index_map;
20378
20379   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20380     return;
20381
20382   if (dwarf2_per_objfile->using_index)
20383     error (_("Cannot use an index to create the index"));
20384
20385   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20386     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20387
20388   if (stat (objfile->name, &st) < 0)
20389     perror_with_name (objfile->name);
20390
20391   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20392                      INDEX_SUFFIX, (char *) NULL);
20393   cleanup = make_cleanup (xfree, filename);
20394
20395   out_file = fopen (filename, "wb");
20396   if (!out_file)
20397     error (_("Can't open `%s' for writing"), filename);
20398
20399   cleanup_filename = filename;
20400   make_cleanup (unlink_if_set, &cleanup_filename);
20401
20402   symtab = create_mapped_symtab ();
20403   make_cleanup (cleanup_mapped_symtab, symtab);
20404
20405   obstack_init (&addr_obstack);
20406   make_cleanup_obstack_free (&addr_obstack);
20407
20408   obstack_init (&cu_list);
20409   make_cleanup_obstack_free (&cu_list);
20410
20411   obstack_init (&types_cu_list);
20412   make_cleanup_obstack_free (&types_cu_list);
20413
20414   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20415                                   NULL, xcalloc, xfree);
20416   make_cleanup_htab_delete (psyms_seen);
20417
20418   /* While we're scanning CU's create a table that maps a psymtab pointer
20419      (which is what addrmap records) to its index (which is what is recorded
20420      in the index file).  This will later be needed to write the address
20421      table.  */
20422   cu_index_htab = htab_create_alloc (100,
20423                                      hash_psymtab_cu_index,
20424                                      eq_psymtab_cu_index,
20425                                      NULL, xcalloc, xfree);
20426   make_cleanup_htab_delete (cu_index_htab);
20427   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20428     xmalloc (sizeof (struct psymtab_cu_index_map)
20429              * dwarf2_per_objfile->n_comp_units);
20430   make_cleanup (xfree, psymtab_cu_index_map);
20431
20432   /* The CU list is already sorted, so we don't need to do additional
20433      work here.  Also, the debug_types entries do not appear in
20434      all_comp_units, but only in their own hash table.  */
20435   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20436     {
20437       struct dwarf2_per_cu_data *per_cu
20438         = dwarf2_per_objfile->all_comp_units[i];
20439       struct partial_symtab *psymtab = per_cu->v.psymtab;
20440       gdb_byte val[8];
20441       struct psymtab_cu_index_map *map;
20442       void **slot;
20443
20444       if (psymtab->user == NULL)
20445         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20446
20447       map = &psymtab_cu_index_map[i];
20448       map->psymtab = psymtab;
20449       map->cu_index = i;
20450       slot = htab_find_slot (cu_index_htab, map, INSERT);
20451       gdb_assert (slot != NULL);
20452       gdb_assert (*slot == NULL);
20453       *slot = map;
20454
20455       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20456                               per_cu->offset.sect_off);
20457       obstack_grow (&cu_list, val, 8);
20458       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20459       obstack_grow (&cu_list, val, 8);
20460     }
20461
20462   /* Dump the address map.  */
20463   write_address_map (objfile, &addr_obstack, cu_index_htab);
20464
20465   /* Write out the .debug_type entries, if any.  */
20466   if (dwarf2_per_objfile->signatured_types)
20467     {
20468       struct signatured_type_index_data sig_data;
20469
20470       sig_data.objfile = objfile;
20471       sig_data.symtab = symtab;
20472       sig_data.types_list = &types_cu_list;
20473       sig_data.psyms_seen = psyms_seen;
20474       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20475       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20476                               write_one_signatured_type, &sig_data);
20477     }
20478
20479   /* Now that we've processed all symbols we can shrink their cu_indices
20480      lists.  */
20481   uniquify_cu_indices (symtab);
20482
20483   obstack_init (&constant_pool);
20484   make_cleanup_obstack_free (&constant_pool);
20485   obstack_init (&symtab_obstack);
20486   make_cleanup_obstack_free (&symtab_obstack);
20487   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20488
20489   obstack_init (&contents);
20490   make_cleanup_obstack_free (&contents);
20491   size_of_contents = 6 * sizeof (offset_type);
20492   total_len = size_of_contents;
20493
20494   /* The version number.  */
20495   val = MAYBE_SWAP (8);
20496   obstack_grow (&contents, &val, sizeof (val));
20497
20498   /* The offset of the CU list from the start of the file.  */
20499   val = MAYBE_SWAP (total_len);
20500   obstack_grow (&contents, &val, sizeof (val));
20501   total_len += obstack_object_size (&cu_list);
20502
20503   /* The offset of the types CU list from the start of the file.  */
20504   val = MAYBE_SWAP (total_len);
20505   obstack_grow (&contents, &val, sizeof (val));
20506   total_len += obstack_object_size (&types_cu_list);
20507
20508   /* The offset of the address table from the start of the file.  */
20509   val = MAYBE_SWAP (total_len);
20510   obstack_grow (&contents, &val, sizeof (val));
20511   total_len += obstack_object_size (&addr_obstack);
20512
20513   /* The offset of the symbol table from the start of the file.  */
20514   val = MAYBE_SWAP (total_len);
20515   obstack_grow (&contents, &val, sizeof (val));
20516   total_len += obstack_object_size (&symtab_obstack);
20517
20518   /* The offset of the constant pool from the start of the file.  */
20519   val = MAYBE_SWAP (total_len);
20520   obstack_grow (&contents, &val, sizeof (val));
20521   total_len += obstack_object_size (&constant_pool);
20522
20523   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20524
20525   write_obstack (out_file, &contents);
20526   write_obstack (out_file, &cu_list);
20527   write_obstack (out_file, &types_cu_list);
20528   write_obstack (out_file, &addr_obstack);
20529   write_obstack (out_file, &symtab_obstack);
20530   write_obstack (out_file, &constant_pool);
20531
20532   fclose (out_file);
20533
20534   /* We want to keep the file, so we set cleanup_filename to NULL
20535      here.  See unlink_if_set.  */
20536   cleanup_filename = NULL;
20537
20538   do_cleanups (cleanup);
20539 }
20540
20541 /* Implementation of the `save gdb-index' command.
20542    
20543    Note that the file format used by this command is documented in the
20544    GDB manual.  Any changes here must be documented there.  */
20545
20546 static void
20547 save_gdb_index_command (char *arg, int from_tty)
20548 {
20549   struct objfile *objfile;
20550
20551   if (!arg || !*arg)
20552     error (_("usage: save gdb-index DIRECTORY"));
20553
20554   ALL_OBJFILES (objfile)
20555   {
20556     struct stat st;
20557
20558     /* If the objfile does not correspond to an actual file, skip it.  */
20559     if (stat (objfile->name, &st) < 0)
20560       continue;
20561
20562     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20563     if (dwarf2_per_objfile)
20564       {
20565         volatile struct gdb_exception except;
20566
20567         TRY_CATCH (except, RETURN_MASK_ERROR)
20568           {
20569             write_psymtabs_to_index (objfile, arg);
20570           }
20571         if (except.reason < 0)
20572           exception_fprintf (gdb_stderr, except,
20573                              _("Error while writing index for `%s': "),
20574                              objfile->name);
20575       }
20576   }
20577 }
20578
20579 \f
20580
20581 int dwarf2_always_disassemble;
20582
20583 static void
20584 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20585                                 struct cmd_list_element *c, const char *value)
20586 {
20587   fprintf_filtered (file,
20588                     _("Whether to always disassemble "
20589                       "DWARF expressions is %s.\n"),
20590                     value);
20591 }
20592
20593 static void
20594 show_check_physname (struct ui_file *file, int from_tty,
20595                      struct cmd_list_element *c, const char *value)
20596 {
20597   fprintf_filtered (file,
20598                     _("Whether to check \"physname\" is %s.\n"),
20599                     value);
20600 }
20601
20602 void _initialize_dwarf2_read (void);
20603
20604 void
20605 _initialize_dwarf2_read (void)
20606 {
20607   struct cmd_list_element *c;
20608
20609   dwarf2_objfile_data_key
20610     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20611
20612   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20613 Set DWARF 2 specific variables.\n\
20614 Configure DWARF 2 variables such as the cache size"),
20615                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20616                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20617
20618   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20619 Show DWARF 2 specific variables\n\
20620 Show DWARF 2 variables such as the cache size"),
20621                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20622                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20623
20624   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20625                             &dwarf2_max_cache_age, _("\
20626 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20627 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20628 A higher limit means that cached compilation units will be stored\n\
20629 in memory longer, and more total memory will be used.  Zero disables\n\
20630 caching, which can slow down startup."),
20631                             NULL,
20632                             show_dwarf2_max_cache_age,
20633                             &set_dwarf2_cmdlist,
20634                             &show_dwarf2_cmdlist);
20635
20636   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20637                            &dwarf2_always_disassemble, _("\
20638 Set whether `info address' always disassembles DWARF expressions."), _("\
20639 Show whether `info address' always disassembles DWARF expressions."), _("\
20640 When enabled, DWARF expressions are always printed in an assembly-like\n\
20641 syntax.  When disabled, expressions will be printed in a more\n\
20642 conversational style, when possible."),
20643                            NULL,
20644                            show_dwarf2_always_disassemble,
20645                            &set_dwarf2_cmdlist,
20646                            &show_dwarf2_cmdlist);
20647
20648   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20649 Set debugging of the dwarf2 reader."), _("\
20650 Show debugging of the dwarf2 reader."), _("\
20651 When enabled, debugging messages are printed during dwarf2 reading\n\
20652 and symtab expansion."),
20653                             NULL,
20654                             NULL,
20655                             &setdebuglist, &showdebuglist);
20656
20657   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20658 Set debugging of the dwarf2 DIE reader."), _("\
20659 Show debugging of the dwarf2 DIE reader."), _("\
20660 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20661 The value is the maximum depth to print."),
20662                              NULL,
20663                              NULL,
20664                              &setdebuglist, &showdebuglist);
20665
20666   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20667 Set cross-checking of \"physname\" code against demangler."), _("\
20668 Show cross-checking of \"physname\" code against demangler."), _("\
20669 When enabled, GDB's internal \"physname\" code is checked against\n\
20670 the demangler."),
20671                            NULL, show_check_physname,
20672                            &setdebuglist, &showdebuglist);
20673
20674   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20675                            no_class, &use_deprecated_index_sections, _("\
20676 Set whether to use deprecated gdb_index sections."), _("\
20677 Show whether to use deprecated gdb_index sections."), _("\
20678 When enabled, deprecated .gdb_index sections are used anyway.\n\
20679 Normally they are ignored either because of a missing feature or\n\
20680 performance issue.\n\
20681 Warning: This option must be enabled before gdb reads the file."),
20682                            NULL,
20683                            NULL,
20684                            &setlist, &showlist);
20685
20686   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20687                _("\
20688 Save a gdb-index file.\n\
20689 Usage: save gdb-index DIRECTORY"),
20690                &save_cmdlist);
20691   set_cmd_completer (c, filename_completer);
20692 }