2012-07-18 Sergio Durigan Junior <sergiodj@redhat.com>
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2012 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 "symtab.h"
34 #include "gdbtypes.h"
35 #include "objfiles.h"
36 #include "dwarf2.h"
37 #include "buildsym.h"
38 #include "demangle.h"
39 #include "gdb-demangle.h"
40 #include "expression.h"
41 #include "filenames.h"  /* for DOSish file names */
42 #include "macrotab.h"
43 #include "language.h"
44 #include "complaints.h"
45 #include "bcache.h"
46 #include "dwarf2expr.h"
47 #include "dwarf2loc.h"
48 #include "cp-support.h"
49 #include "hashtab.h"
50 #include "command.h"
51 #include "gdbcmd.h"
52 #include "block.h"
53 #include "addrmap.h"
54 #include "typeprint.h"
55 #include "jv-lang.h"
56 #include "psympriv.h"
57 #include "exceptions.h"
58 #include "gdb_stat.h"
59 #include "completer.h"
60 #include "vec.h"
61 #include "c-lang.h"
62 #include "go-lang.h"
63 #include "valprint.h"
64 #include "gdbcore.h" /* for gnutarget */
65 #include "gdb/gdb-index.h"
66 #include <ctype.h>
67
68 #include <fcntl.h>
69 #include "gdb_string.h"
70 #include "gdb_assert.h"
71 #include <sys/types.h>
72 #ifdef HAVE_ZLIB_H
73 #include <zlib.h>
74 #endif
75 #ifdef HAVE_MMAP
76 #include <sys/mman.h>
77 #ifndef MAP_FAILED
78 #define MAP_FAILED ((void *) -1)
79 #endif
80 #endif
81
82 typedef struct symbol *symbolp;
83 DEF_VEC_P (symbolp);
84
85 /* When non-zero, print basic high level tracing messages.
86    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
87 static int dwarf2_read_debug = 0;
88
89 /* When non-zero, dump DIEs after they are read in.  */
90 static int dwarf2_die_debug = 0;
91
92 /* When non-zero, cross-check physname against demangler.  */
93 static int check_physname = 0;
94
95 /* When non-zero, do not reject deprecated .gdb_index sections.  */
96 int use_deprecated_index_sections = 0;
97
98 static int pagesize;
99
100 /* When set, the file that we're processing is known to have debugging
101    info for C++ namespaces.  GCC 3.3.x did not produce this information,
102    but later versions do.  */
103
104 static int processing_has_namespace_info;
105
106 static const struct objfile_data *dwarf2_objfile_data_key;
107
108 struct dwarf2_section_info
109 {
110   asection *asection;
111   gdb_byte *buffer;
112   bfd_size_type size;
113   /* Not NULL if the section was actually mmapped.  */
114   void *map_addr;
115   /* Page aligned size of mmapped area.  */
116   bfd_size_type map_len;
117   /* True if we have tried to read this section.  */
118   int readin;
119 };
120
121 typedef struct dwarf2_section_info dwarf2_section_info_def;
122 DEF_VEC_O (dwarf2_section_info_def);
123
124 /* All offsets in the index are of this type.  It must be
125    architecture-independent.  */
126 typedef uint32_t offset_type;
127
128 DEF_VEC_I (offset_type);
129
130 /* Ensure only legit values are used.  */
131 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
132   do { \
133     gdb_assert ((unsigned int) (value) <= 1); \
134     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
135   } while (0)
136
137 /* Ensure only legit values are used.  */
138 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
139   do { \
140     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
141                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
142     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
143   } while (0)
144
145 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
146 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
147   do { \
148     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
149     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
150   } while (0)
151
152 /* A description of the mapped index.  The file format is described in
153    a comment by the code that writes the index.  */
154 struct mapped_index
155 {
156   /* Index data format version.  */
157   int version;
158
159   /* The total length of the buffer.  */
160   off_t total_size;
161
162   /* A pointer to the address table data.  */
163   const gdb_byte *address_table;
164
165   /* Size of the address table data in bytes.  */
166   offset_type address_table_size;
167
168   /* The symbol table, implemented as a hash table.  */
169   const offset_type *symbol_table;
170
171   /* Size in slots, each slot is 2 offset_types.  */
172   offset_type symbol_table_slots;
173
174   /* A pointer to the constant pool.  */
175   const char *constant_pool;
176 };
177
178 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
179 DEF_VEC_P (dwarf2_per_cu_ptr);
180
181 /* Collection of data recorded per objfile.
182    This hangs off of dwarf2_objfile_data_key.  */
183
184 struct dwarf2_per_objfile
185 {
186   struct dwarf2_section_info info;
187   struct dwarf2_section_info abbrev;
188   struct dwarf2_section_info line;
189   struct dwarf2_section_info loc;
190   struct dwarf2_section_info macinfo;
191   struct dwarf2_section_info macro;
192   struct dwarf2_section_info str;
193   struct dwarf2_section_info ranges;
194   struct dwarf2_section_info addr;
195   struct dwarf2_section_info frame;
196   struct dwarf2_section_info eh_frame;
197   struct dwarf2_section_info gdb_index;
198
199   VEC (dwarf2_section_info_def) *types;
200
201   /* Back link.  */
202   struct objfile *objfile;
203
204   /* Table of all the compilation units.  This is used to locate
205      the target compilation unit of a particular reference.  */
206   struct dwarf2_per_cu_data **all_comp_units;
207
208   /* The number of compilation units in ALL_COMP_UNITS.  */
209   int n_comp_units;
210
211   /* The number of .debug_types-related CUs.  */
212   int n_type_units;
213
214   /* The .debug_types-related CUs (TUs).  */
215   struct signatured_type **all_type_units;
216
217   /* The number of entries in all_type_unit_groups.  */
218   int n_type_unit_groups;
219
220   /* Table of type unit groups.
221      This exists to make it easy to iterate over all CUs and TU groups.  */
222   struct type_unit_group **all_type_unit_groups;
223
224   /* Table of struct type_unit_group objects.
225      The hash key is the DW_AT_stmt_list value.  */
226   htab_t type_unit_groups;
227
228   /* A table mapping .debug_types signatures to its signatured_type entry.
229      This is NULL if the .debug_types section hasn't been read in yet.  */
230   htab_t signatured_types;
231
232   /* Type unit statistics, to see how well the scaling improvements
233      are doing.  */
234   struct tu_stats
235   {
236     int nr_uniq_abbrev_tables;
237     int nr_symtabs;
238     int nr_symtab_sharers;
239     int nr_stmt_less_type_units;
240   } tu_stats;
241
242   /* A chain of compilation units that are currently read in, so that
243      they can be freed later.  */
244   struct dwarf2_per_cu_data *read_in_chain;
245
246   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
247      This is NULL if the table hasn't been allocated yet.  */
248   htab_t dwo_files;
249
250   /* A flag indicating wether this objfile has a section loaded at a
251      VMA of 0.  */
252   int has_section_at_zero;
253
254   /* True if we are using the mapped index,
255      or we are faking it for OBJF_READNOW's sake.  */
256   unsigned char using_index;
257
258   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
259   struct mapped_index *index_table;
260
261   /* When using index_table, this keeps track of all quick_file_names entries.
262      TUs can share line table entries with CUs or other TUs, and there can be
263      a lot more TUs than unique line tables, so we maintain a separate table
264      of all line table entries to support the sharing.  */
265   htab_t quick_file_names_table;
266
267   /* Set during partial symbol reading, to prevent queueing of full
268      symbols.  */
269   int reading_partial_symbols;
270
271   /* Table mapping type DIEs to their struct type *.
272      This is NULL if not allocated yet.
273      The mapping is done via (CU/TU signature + DIE offset) -> type.  */
274   htab_t die_type_hash;
275
276   /* The CUs we recently read.  */
277   VEC (dwarf2_per_cu_ptr) *just_read_cus;
278 };
279
280 static struct dwarf2_per_objfile *dwarf2_per_objfile;
281
282 /* Default names of the debugging sections.  */
283
284 /* Note that if the debugging section has been compressed, it might
285    have a name like .zdebug_info.  */
286
287 static const struct dwarf2_debug_sections dwarf2_elf_names =
288 {
289   { ".debug_info", ".zdebug_info" },
290   { ".debug_abbrev", ".zdebug_abbrev" },
291   { ".debug_line", ".zdebug_line" },
292   { ".debug_loc", ".zdebug_loc" },
293   { ".debug_macinfo", ".zdebug_macinfo" },
294   { ".debug_macro", ".zdebug_macro" },
295   { ".debug_str", ".zdebug_str" },
296   { ".debug_ranges", ".zdebug_ranges" },
297   { ".debug_types", ".zdebug_types" },
298   { ".debug_addr", ".zdebug_addr" },
299   { ".debug_frame", ".zdebug_frame" },
300   { ".eh_frame", NULL },
301   { ".gdb_index", ".zgdb_index" },
302   23
303 };
304
305 /* List of DWO sections.  */
306
307 static const struct dwo_section_names
308 {
309   struct dwarf2_section_names abbrev_dwo;
310   struct dwarf2_section_names info_dwo;
311   struct dwarf2_section_names line_dwo;
312   struct dwarf2_section_names loc_dwo;
313   struct dwarf2_section_names macinfo_dwo;
314   struct dwarf2_section_names macro_dwo;
315   struct dwarf2_section_names str_dwo;
316   struct dwarf2_section_names str_offsets_dwo;
317   struct dwarf2_section_names types_dwo;
318 }
319 dwo_section_names =
320 {
321   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
322   { ".debug_info.dwo", ".zdebug_info.dwo" },
323   { ".debug_line.dwo", ".zdebug_line.dwo" },
324   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
325   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
326   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
327   { ".debug_str.dwo", ".zdebug_str.dwo" },
328   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
329   { ".debug_types.dwo", ".zdebug_types.dwo" },
330 };
331
332 /* local data types */
333
334 /* The data in a compilation unit header, after target2host
335    translation, looks like this.  */
336 struct comp_unit_head
337 {
338   unsigned int length;
339   short version;
340   unsigned char addr_size;
341   unsigned char signed_addr_p;
342   sect_offset abbrev_offset;
343
344   /* Size of file offsets; either 4 or 8.  */
345   unsigned int offset_size;
346
347   /* Size of the length field; either 4 or 12.  */
348   unsigned int initial_length_size;
349
350   /* Offset to the first byte of this compilation unit header in the
351      .debug_info section, for resolving relative reference dies.  */
352   sect_offset offset;
353
354   /* Offset to first die in this cu from the start of the cu.
355      This will be the first byte following the compilation unit header.  */
356   cu_offset first_die_offset;
357 };
358
359 /* Type used for delaying computation of method physnames.
360    See comments for compute_delayed_physnames.  */
361 struct delayed_method_info
362 {
363   /* The type to which the method is attached, i.e., its parent class.  */
364   struct type *type;
365
366   /* The index of the method in the type's function fieldlists.  */
367   int fnfield_index;
368
369   /* The index of the method in the fieldlist.  */
370   int index;
371
372   /* The name of the DIE.  */
373   const char *name;
374
375   /*  The DIE associated with this method.  */
376   struct die_info *die;
377 };
378
379 typedef struct delayed_method_info delayed_method_info;
380 DEF_VEC_O (delayed_method_info);
381
382 /* Internal state when decoding a particular compilation unit.  */
383 struct dwarf2_cu
384 {
385   /* The objfile containing this compilation unit.  */
386   struct objfile *objfile;
387
388   /* The header of the compilation unit.  */
389   struct comp_unit_head header;
390
391   /* Base address of this compilation unit.  */
392   CORE_ADDR base_address;
393
394   /* Non-zero if base_address has been set.  */
395   int base_known;
396
397   /* The language we are debugging.  */
398   enum language language;
399   const struct language_defn *language_defn;
400
401   const char *producer;
402
403   /* The generic symbol table building routines have separate lists for
404      file scope symbols and all all other scopes (local scopes).  So
405      we need to select the right one to pass to add_symbol_to_list().
406      We do it by keeping a pointer to the correct list in list_in_scope.
407
408      FIXME: The original dwarf code just treated the file scope as the
409      first local scope, and all other local scopes as nested local
410      scopes, and worked fine.  Check to see if we really need to
411      distinguish these in buildsym.c.  */
412   struct pending **list_in_scope;
413
414   /* The abbrev table for this CU.
415      Normally this points to the abbrev table in the objfile.
416      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
417   struct abbrev_table *abbrev_table;
418
419   /* Hash table holding all the loaded partial DIEs
420      with partial_die->offset.SECT_OFF as hash.  */
421   htab_t partial_dies;
422
423   /* Storage for things with the same lifetime as this read-in compilation
424      unit, including partial DIEs.  */
425   struct obstack comp_unit_obstack;
426
427   /* When multiple dwarf2_cu structures are living in memory, this field
428      chains them all together, so that they can be released efficiently.
429      We will probably also want a generation counter so that most-recently-used
430      compilation units are cached...  */
431   struct dwarf2_per_cu_data *read_in_chain;
432
433   /* Backchain to our per_cu entry if the tree has been built.  */
434   struct dwarf2_per_cu_data *per_cu;
435
436   /* How many compilation units ago was this CU last referenced?  */
437   int last_used;
438
439   /* A hash table of DIE cu_offset for following references with
440      die_info->offset.sect_off as hash.  */
441   htab_t die_hash;
442
443   /* Full DIEs if read in.  */
444   struct die_info *dies;
445
446   /* A set of pointers to dwarf2_per_cu_data objects for compilation
447      units referenced by this one.  Only set during full symbol processing;
448      partial symbol tables do not have dependencies.  */
449   htab_t dependencies;
450
451   /* Header data from the line table, during full symbol processing.  */
452   struct line_header *line_header;
453
454   /* A list of methods which need to have physnames computed
455      after all type information has been read.  */
456   VEC (delayed_method_info) *method_list;
457
458   /* To be copied to symtab->call_site_htab.  */
459   htab_t call_site_htab;
460
461   /* Non-NULL if this CU came from a DWO file.
462      There is an invariant here that is important to remember:
463      Except for attributes copied from the top level DIE in the "main"
464      (or "stub") file in preparation for reading the DWO file
465      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
466      Either there isn't a DWO file (in which case this is NULL and the point
467      is moot), or there is and either we're not going to read it (in which
468      case this is NULL) or there is and we are reading it (in which case this
469      is non-NULL).  */
470   struct dwo_unit *dwo_unit;
471
472   /* The DW_AT_addr_base attribute if present, zero otherwise
473      (zero is a valid value though).
474      Note this value comes from the stub CU/TU's DIE.  */
475   ULONGEST addr_base;
476
477   /* The DW_AT_ranges_base attribute if present, zero otherwise
478      (zero is a valid value though).
479      Note this value comes from the stub CU/TU's DIE.
480      Also note that the value is zero in the non-DWO case so this value can
481      be used without needing to know whether DWO files are in use or not.  */
482   ULONGEST ranges_base;
483
484   /* Mark used when releasing cached dies.  */
485   unsigned int mark : 1;
486
487   /* This CU references .debug_loc.  See the symtab->locations_valid field.
488      This test is imperfect as there may exist optimized debug code not using
489      any location list and still facing inlining issues if handled as
490      unoptimized code.  For a future better test see GCC PR other/32998.  */
491   unsigned int has_loclist : 1;
492
493   /* These cache the results for producer_is_gxx_lt_4_6 and producer_is_icc.
494      CHECKED_PRODUCER is set if both PRODUCER_IS_GXX_LT_4_6 and PRODUCER_IS_ICC
495      are valid.  This information is cached because profiling CU expansion
496      showed excessive time spent in producer_is_gxx_lt_4_6.  */
497   unsigned int checked_producer : 1;
498   unsigned int producer_is_gxx_lt_4_6 : 1;
499   unsigned int producer_is_icc : 1;
500 };
501
502 /* Persistent data held for a compilation unit, even when not
503    processing it.  We put a pointer to this structure in the
504    read_symtab_private field of the psymtab.  */
505
506 struct dwarf2_per_cu_data
507 {
508   /* The start offset and length of this compilation unit.  2**29-1
509      bytes should suffice to store the length of any compilation unit
510      - if it doesn't, GDB will fall over anyway.
511      NOTE: Unlike comp_unit_head.length, this length includes
512      initial_length_size.
513      If the DIE refers to a DWO file, this is always of the original die,
514      not the DWO file.  */
515   sect_offset offset;
516   unsigned int length : 29;
517
518   /* Flag indicating this compilation unit will be read in before
519      any of the current compilation units are processed.  */
520   unsigned int queued : 1;
521
522   /* This flag will be set when reading partial DIEs if we need to load
523      absolutely all DIEs for this compilation unit, instead of just the ones
524      we think are interesting.  It gets set if we look for a DIE in the
525      hash table and don't find it.  */
526   unsigned int load_all_dies : 1;
527
528   /* Non-zero if this CU is from .debug_types.  */
529   unsigned int is_debug_types : 1;
530
531   /* The section this CU/TU lives in.
532      If the DIE refers to a DWO file, this is always the original die,
533      not the DWO file.  */
534   struct dwarf2_section_info *info_or_types_section;
535
536   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
537      of the CU cache it gets reset to NULL again.  */
538   struct dwarf2_cu *cu;
539
540   /* The corresponding objfile.
541      Normally we can get the objfile from dwarf2_per_objfile.
542      However we can enter this file with just a "per_cu" handle.  */
543   struct objfile *objfile;
544
545   /* When using partial symbol tables, the 'psymtab' field is active.
546      Otherwise the 'quick' field is active.  */
547   union
548   {
549     /* The partial symbol table associated with this compilation unit,
550        or NULL for unread partial units.  */
551     struct partial_symtab *psymtab;
552
553     /* Data needed by the "quick" functions.  */
554     struct dwarf2_per_cu_quick_data *quick;
555   } v;
556
557   union
558   {
559     /* The CUs we import using DW_TAG_imported_unit.  This is filled in
560        while reading psymtabs, used to compute the psymtab dependencies,
561        and then cleared.  Then it is filled in again while reading full
562        symbols, and only deleted when the objfile is destroyed.  */
563     VEC (dwarf2_per_cu_ptr) *imported_symtabs;
564
565     /* Type units are grouped by their DW_AT_stmt_list entry so that they
566        can share them.  If this is a TU, this points to the containing
567        symtab.  */
568     struct type_unit_group *type_unit_group;
569   } s;
570 };
571
572 /* Entry in the signatured_types hash table.  */
573
574 struct signatured_type
575 {
576   /* The "per_cu" object of this type.
577      N.B.: This is the first member so that it's easy to convert pointers
578      between them.  */
579   struct dwarf2_per_cu_data per_cu;
580
581   /* The type's signature.  */
582   ULONGEST signature;
583
584   /* Offset in the TU of the type's DIE, as read from the TU header.
585      If the definition lives in a DWO file, this value is unusable.  */
586   cu_offset type_offset_in_tu;
587
588   /* Offset in the section of the type's DIE.
589      If the definition lives in a DWO file, this is the offset in the
590      .debug_types.dwo section.
591      The value is zero until the actual value is known.
592      Zero is otherwise not a valid section offset.  */
593   sect_offset type_offset_in_section;
594 };
595
596 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
597    This includes type_unit_group and quick_file_names.  */
598
599 struct stmt_list_hash
600 {
601   /* The DWO unit this table is from or NULL if there is none.  */
602   struct dwo_unit *dwo_unit;
603
604   /* Offset in .debug_line or .debug_line.dwo.  */
605   sect_offset line_offset;
606 };
607
608 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
609    an object of this type.  */
610
611 struct type_unit_group
612 {
613   /* dwarf2read.c's main "handle" on the symtab.
614      To simplify things we create an artificial CU that "includes" all the
615      type units using this stmt_list so that the rest of the code still has
616      a "per_cu" handle on the symtab.
617      This PER_CU is recognized by having no section.  */
618 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->info_or_types_section == NULL)
619   struct dwarf2_per_cu_data per_cu;
620
621   union
622   {
623     /* The TUs that share this DW_AT_stmt_list entry.
624        This is added to while parsing type units to build partial symtabs,
625        and is deleted afterwards and not used again.  */
626     VEC (dwarf2_per_cu_ptr) *tus;
627
628     /* When reading the line table in "quick" functions, we need a real TU.
629        Any will do, we know they all share the same DW_AT_stmt_list entry.
630        For simplicity's sake, we pick the first one.  */
631     struct dwarf2_per_cu_data *first_tu;
632   } t;
633
634   /* The primary symtab.
635      Type units in a group needn't all be defined in the same source file,
636      so we create an essentially anonymous symtab as the primary symtab.  */
637   struct symtab *primary_symtab;
638
639   /* The data used to construct the hash key.  */
640   struct stmt_list_hash hash;
641
642   /* The number of symtabs from the line header.
643      The value here must match line_header.num_file_names.  */
644   unsigned int num_symtabs;
645
646   /* The symbol tables for this TU (obtained from the files listed in
647      DW_AT_stmt_list).
648      WARNING: The order of entries here must match the order of entries
649      in the line header.  After the first TU using this type_unit_group, the
650      line header for the subsequent TUs is recreated from this.  This is done
651      because we need to use the same symtabs for each TU using the same
652      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
653      there's no guarantee the line header doesn't have duplicate entries.  */
654   struct symtab **symtabs;
655 };
656
657 /* These sections are what may appear in a "dwo" file.  */
658
659 struct dwo_sections
660 {
661   struct dwarf2_section_info abbrev;
662   struct dwarf2_section_info info;
663   struct dwarf2_section_info line;
664   struct dwarf2_section_info loc;
665   struct dwarf2_section_info macinfo;
666   struct dwarf2_section_info macro;
667   struct dwarf2_section_info str;
668   struct dwarf2_section_info str_offsets;
669   VEC (dwarf2_section_info_def) *types;
670 };
671
672 /* Common bits of DWO CUs/TUs.  */
673
674 struct dwo_unit
675 {
676   /* Backlink to the containing struct dwo_file.  */
677   struct dwo_file *dwo_file;
678
679   /* The "id" that distinguishes this CU/TU.
680      .debug_info calls this "dwo_id", .debug_types calls this "signature".
681      Since signatures came first, we stick with it for consistency.  */
682   ULONGEST signature;
683
684   /* The section this CU/TU lives in, in the DWO file.  */
685   struct dwarf2_section_info *info_or_types_section;
686
687   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
688   sect_offset offset;
689   unsigned int length;
690
691   /* For types, offset in the type's DIE of the type defined by this TU.  */
692   cu_offset type_offset_in_tu;
693 };
694
695 /* Data for one DWO file.  */
696
697 struct dwo_file
698 {
699   /* The DW_AT_GNU_dwo_name attribute.
700      We don't manage space for this, it's an attribute.  */
701   const char *dwo_name;
702
703   /* The bfd, when the file is open.  Otherwise this is NULL.  */
704   bfd *dwo_bfd;
705
706   /* Section info for this file.  */
707   struct dwo_sections sections;
708
709   /* Table of CUs in the file.
710      Each element is a struct dwo_unit.  */
711   htab_t cus;
712
713   /* Table of TUs in the file.
714      Each element is a struct dwo_unit.  */
715   htab_t tus;
716 };
717
718 /* Struct used to pass misc. parameters to read_die_and_children, et
719    al.  which are used for both .debug_info and .debug_types dies.
720    All parameters here are unchanging for the life of the call.  This
721    struct exists to abstract away the constant parameters of die reading.  */
722
723 struct die_reader_specs
724 {
725   /* die_section->asection->owner.  */
726   bfd* abfd;
727
728   /* The CU of the DIE we are parsing.  */
729   struct dwarf2_cu *cu;
730
731   /* Non-NULL if reading a DWO file.  */
732   struct dwo_file *dwo_file;
733
734   /* The section the die comes from.
735      This is either .debug_info or .debug_types, or the .dwo variants.  */
736   struct dwarf2_section_info *die_section;
737
738   /* die_section->buffer.  */
739   gdb_byte *buffer;
740
741   /* The end of the buffer.  */
742   const gdb_byte *buffer_end;
743 };
744
745 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
746 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
747                                       gdb_byte *info_ptr,
748                                       struct die_info *comp_unit_die,
749                                       int has_children,
750                                       void *data);
751
752 /* The line number information for a compilation unit (found in the
753    .debug_line section) begins with a "statement program header",
754    which contains the following information.  */
755 struct line_header
756 {
757   unsigned int total_length;
758   unsigned short version;
759   unsigned int header_length;
760   unsigned char minimum_instruction_length;
761   unsigned char maximum_ops_per_instruction;
762   unsigned char default_is_stmt;
763   int line_base;
764   unsigned char line_range;
765   unsigned char opcode_base;
766
767   /* standard_opcode_lengths[i] is the number of operands for the
768      standard opcode whose value is i.  This means that
769      standard_opcode_lengths[0] is unused, and the last meaningful
770      element is standard_opcode_lengths[opcode_base - 1].  */
771   unsigned char *standard_opcode_lengths;
772
773   /* The include_directories table.  NOTE!  These strings are not
774      allocated with xmalloc; instead, they are pointers into
775      debug_line_buffer.  If you try to free them, `free' will get
776      indigestion.  */
777   unsigned int num_include_dirs, include_dirs_size;
778   char **include_dirs;
779
780   /* The file_names table.  NOTE!  These strings are not allocated
781      with xmalloc; instead, they are pointers into debug_line_buffer.
782      Don't try to free them directly.  */
783   unsigned int num_file_names, file_names_size;
784   struct file_entry
785   {
786     char *name;
787     unsigned int dir_index;
788     unsigned int mod_time;
789     unsigned int length;
790     int included_p; /* Non-zero if referenced by the Line Number Program.  */
791     struct symtab *symtab; /* The associated symbol table, if any.  */
792   } *file_names;
793
794   /* The start and end of the statement program following this
795      header.  These point into dwarf2_per_objfile->line_buffer.  */
796   gdb_byte *statement_program_start, *statement_program_end;
797 };
798
799 /* When we construct a partial symbol table entry we only
800    need this much information.  */
801 struct partial_die_info
802   {
803     /* Offset of this DIE.  */
804     sect_offset offset;
805
806     /* DWARF-2 tag for this DIE.  */
807     ENUM_BITFIELD(dwarf_tag) tag : 16;
808
809     /* Assorted flags describing the data found in this DIE.  */
810     unsigned int has_children : 1;
811     unsigned int is_external : 1;
812     unsigned int is_declaration : 1;
813     unsigned int has_type : 1;
814     unsigned int has_specification : 1;
815     unsigned int has_pc_info : 1;
816     unsigned int may_be_inlined : 1;
817
818     /* Flag set if the SCOPE field of this structure has been
819        computed.  */
820     unsigned int scope_set : 1;
821
822     /* Flag set if the DIE has a byte_size attribute.  */
823     unsigned int has_byte_size : 1;
824
825     /* Flag set if any of the DIE's children are template arguments.  */
826     unsigned int has_template_arguments : 1;
827
828     /* Flag set if fixup_partial_die has been called on this die.  */
829     unsigned int fixup_called : 1;
830
831     /* The name of this DIE.  Normally the value of DW_AT_name, but
832        sometimes a default name for unnamed DIEs.  */
833     char *name;
834
835     /* The linkage name, if present.  */
836     const char *linkage_name;
837
838     /* The scope to prepend to our children.  This is generally
839        allocated on the comp_unit_obstack, so will disappear
840        when this compilation unit leaves the cache.  */
841     char *scope;
842
843     /* Some data associated with the partial DIE.  The tag determines
844        which field is live.  */
845     union
846     {
847       /* The location description associated with this DIE, if any.  */
848       struct dwarf_block *locdesc;
849       /* The offset of an import, for DW_TAG_imported_unit.  */
850       sect_offset offset;
851     } d;
852
853     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
854     CORE_ADDR lowpc;
855     CORE_ADDR highpc;
856
857     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
858        DW_AT_sibling, if any.  */
859     /* NOTE: This member isn't strictly necessary, read_partial_die could
860        return DW_AT_sibling values to its caller load_partial_dies.  */
861     gdb_byte *sibling;
862
863     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
864        DW_AT_specification (or DW_AT_abstract_origin or
865        DW_AT_extension).  */
866     sect_offset spec_offset;
867
868     /* Pointers to this DIE's parent, first child, and next sibling,
869        if any.  */
870     struct partial_die_info *die_parent, *die_child, *die_sibling;
871   };
872
873 /* This data structure holds the information of an abbrev.  */
874 struct abbrev_info
875   {
876     unsigned int number;        /* number identifying abbrev */
877     enum dwarf_tag tag;         /* dwarf tag */
878     unsigned short has_children;                /* boolean */
879     unsigned short num_attrs;   /* number of attributes */
880     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
881     struct abbrev_info *next;   /* next in chain */
882   };
883
884 struct attr_abbrev
885   {
886     ENUM_BITFIELD(dwarf_attribute) name : 16;
887     ENUM_BITFIELD(dwarf_form) form : 16;
888   };
889
890 /* Size of abbrev_table.abbrev_hash_table.  */
891 #define ABBREV_HASH_SIZE 121
892
893 /* Top level data structure to contain an abbreviation table.  */
894
895 struct abbrev_table
896 {
897   /* Where the abbrev table came from.
898      This is used as a sanity check when the table is used.  */
899   sect_offset offset;
900
901   /* Storage for the abbrev table.  */
902   struct obstack abbrev_obstack;
903
904   /* Hash table of abbrevs.
905      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
906      It could be statically allocated, but the previous code didn't so we
907      don't either.  */
908   struct abbrev_info **abbrevs;
909 };
910
911 /* Attributes have a name and a value.  */
912 struct attribute
913   {
914     ENUM_BITFIELD(dwarf_attribute) name : 16;
915     ENUM_BITFIELD(dwarf_form) form : 15;
916
917     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
918        field should be in u.str (existing only for DW_STRING) but it is kept
919        here for better struct attribute alignment.  */
920     unsigned int string_is_canonical : 1;
921
922     union
923       {
924         char *str;
925         struct dwarf_block *blk;
926         ULONGEST unsnd;
927         LONGEST snd;
928         CORE_ADDR addr;
929         struct signatured_type *signatured_type;
930       }
931     u;
932   };
933
934 /* This data structure holds a complete die structure.  */
935 struct die_info
936   {
937     /* DWARF-2 tag for this DIE.  */
938     ENUM_BITFIELD(dwarf_tag) tag : 16;
939
940     /* Number of attributes */
941     unsigned char num_attrs;
942
943     /* True if we're presently building the full type name for the
944        type derived from this DIE.  */
945     unsigned char building_fullname : 1;
946
947     /* Abbrev number */
948     unsigned int abbrev;
949
950     /* Offset in .debug_info or .debug_types section.  */
951     sect_offset offset;
952
953     /* The dies in a compilation unit form an n-ary tree.  PARENT
954        points to this die's parent; CHILD points to the first child of
955        this node; and all the children of a given node are chained
956        together via their SIBLING fields.  */
957     struct die_info *child;     /* Its first child, if any.  */
958     struct die_info *sibling;   /* Its next sibling, if any.  */
959     struct die_info *parent;    /* Its parent, if any.  */
960
961     /* An array of attributes, with NUM_ATTRS elements.  There may be
962        zero, but it's not common and zero-sized arrays are not
963        sufficiently portable C.  */
964     struct attribute attrs[1];
965   };
966
967 /* Get at parts of an attribute structure.  */
968
969 #define DW_STRING(attr)    ((attr)->u.str)
970 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
971 #define DW_UNSND(attr)     ((attr)->u.unsnd)
972 #define DW_BLOCK(attr)     ((attr)->u.blk)
973 #define DW_SND(attr)       ((attr)->u.snd)
974 #define DW_ADDR(attr)      ((attr)->u.addr)
975 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
976
977 /* Blocks are a bunch of untyped bytes.  */
978 struct dwarf_block
979   {
980     unsigned int size;
981
982     /* Valid only if SIZE is not zero.  */
983     gdb_byte *data;
984   };
985
986 #ifndef ATTR_ALLOC_CHUNK
987 #define ATTR_ALLOC_CHUNK 4
988 #endif
989
990 /* Allocate fields for structs, unions and enums in this size.  */
991 #ifndef DW_FIELD_ALLOC_CHUNK
992 #define DW_FIELD_ALLOC_CHUNK 4
993 #endif
994
995 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
996    but this would require a corresponding change in unpack_field_as_long
997    and friends.  */
998 static int bits_per_byte = 8;
999
1000 /* The routines that read and process dies for a C struct or C++ class
1001    pass lists of data member fields and lists of member function fields
1002    in an instance of a field_info structure, as defined below.  */
1003 struct field_info
1004   {
1005     /* List of data member and baseclasses fields.  */
1006     struct nextfield
1007       {
1008         struct nextfield *next;
1009         int accessibility;
1010         int virtuality;
1011         struct field field;
1012       }
1013      *fields, *baseclasses;
1014
1015     /* Number of fields (including baseclasses).  */
1016     int nfields;
1017
1018     /* Number of baseclasses.  */
1019     int nbaseclasses;
1020
1021     /* Set if the accesibility of one of the fields is not public.  */
1022     int non_public_fields;
1023
1024     /* Member function fields array, entries are allocated in the order they
1025        are encountered in the object file.  */
1026     struct nextfnfield
1027       {
1028         struct nextfnfield *next;
1029         struct fn_field fnfield;
1030       }
1031      *fnfields;
1032
1033     /* Member function fieldlist array, contains name of possibly overloaded
1034        member function, number of overloaded member functions and a pointer
1035        to the head of the member function field chain.  */
1036     struct fnfieldlist
1037       {
1038         char *name;
1039         int length;
1040         struct nextfnfield *head;
1041       }
1042      *fnfieldlists;
1043
1044     /* Number of entries in the fnfieldlists array.  */
1045     int nfnfields;
1046
1047     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1048        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1049     struct typedef_field_list
1050       {
1051         struct typedef_field field;
1052         struct typedef_field_list *next;
1053       }
1054     *typedef_field_list;
1055     unsigned typedef_field_list_count;
1056   };
1057
1058 /* One item on the queue of compilation units to read in full symbols
1059    for.  */
1060 struct dwarf2_queue_item
1061 {
1062   struct dwarf2_per_cu_data *per_cu;
1063   enum language pretend_language;
1064   struct dwarf2_queue_item *next;
1065 };
1066
1067 /* The current queue.  */
1068 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1069
1070 /* Loaded secondary compilation units are kept in memory until they
1071    have not been referenced for the processing of this many
1072    compilation units.  Set this to zero to disable caching.  Cache
1073    sizes of up to at least twenty will improve startup time for
1074    typical inter-CU-reference binaries, at an obvious memory cost.  */
1075 static int dwarf2_max_cache_age = 5;
1076 static void
1077 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1078                            struct cmd_list_element *c, const char *value)
1079 {
1080   fprintf_filtered (file, _("The upper bound on the age of cached "
1081                             "dwarf2 compilation units is %s.\n"),
1082                     value);
1083 }
1084
1085
1086 /* Various complaints about symbol reading that don't abort the process.  */
1087
1088 static void
1089 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1090 {
1091   complaint (&symfile_complaints,
1092              _("statement list doesn't fit in .debug_line section"));
1093 }
1094
1095 static void
1096 dwarf2_debug_line_missing_file_complaint (void)
1097 {
1098   complaint (&symfile_complaints,
1099              _(".debug_line section has line data without a file"));
1100 }
1101
1102 static void
1103 dwarf2_debug_line_missing_end_sequence_complaint (void)
1104 {
1105   complaint (&symfile_complaints,
1106              _(".debug_line section has line "
1107                "program sequence without an end"));
1108 }
1109
1110 static void
1111 dwarf2_complex_location_expr_complaint (void)
1112 {
1113   complaint (&symfile_complaints, _("location expression too complex"));
1114 }
1115
1116 static void
1117 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1118                                               int arg3)
1119 {
1120   complaint (&symfile_complaints,
1121              _("const value length mismatch for '%s', got %d, expected %d"),
1122              arg1, arg2, arg3);
1123 }
1124
1125 static void
1126 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1127 {
1128   complaint (&symfile_complaints,
1129              _("debug info runs off end of %s section"
1130                " [in module %s]"),
1131              section->asection->name,
1132              bfd_get_filename (section->asection->owner));
1133 }
1134
1135 static void
1136 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1137 {
1138   complaint (&symfile_complaints,
1139              _("macro debug info contains a "
1140                "malformed macro definition:\n`%s'"),
1141              arg1);
1142 }
1143
1144 static void
1145 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1146 {
1147   complaint (&symfile_complaints,
1148              _("invalid attribute class or form for '%s' in '%s'"),
1149              arg1, arg2);
1150 }
1151
1152 /* local function prototypes */
1153
1154 static void dwarf2_locate_sections (bfd *, asection *, void *);
1155
1156 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1157                                            struct objfile *);
1158
1159 static void dwarf2_find_base_address (struct die_info *die,
1160                                       struct dwarf2_cu *cu);
1161
1162 static void dwarf2_build_psymtabs_hard (struct objfile *);
1163
1164 static void scan_partial_symbols (struct partial_die_info *,
1165                                   CORE_ADDR *, CORE_ADDR *,
1166                                   int, struct dwarf2_cu *);
1167
1168 static void add_partial_symbol (struct partial_die_info *,
1169                                 struct dwarf2_cu *);
1170
1171 static void add_partial_namespace (struct partial_die_info *pdi,
1172                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1173                                    int need_pc, struct dwarf2_cu *cu);
1174
1175 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1176                                 CORE_ADDR *highpc, int need_pc,
1177                                 struct dwarf2_cu *cu);
1178
1179 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1180                                      struct dwarf2_cu *cu);
1181
1182 static void add_partial_subprogram (struct partial_die_info *pdi,
1183                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1184                                     int need_pc, struct dwarf2_cu *cu);
1185
1186 static void dwarf2_psymtab_to_symtab (struct partial_symtab *);
1187
1188 static void psymtab_to_symtab_1 (struct partial_symtab *);
1189
1190 static struct abbrev_info *abbrev_table_lookup_abbrev
1191   (const struct abbrev_table *, unsigned int);
1192
1193 static struct abbrev_table *abbrev_table_read_table
1194   (struct dwarf2_section_info *, sect_offset);
1195
1196 static void abbrev_table_free (struct abbrev_table *);
1197
1198 static void abbrev_table_free_cleanup (void *);
1199
1200 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1201                                  struct dwarf2_section_info *);
1202
1203 static void dwarf2_free_abbrev_table (void *);
1204
1205 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1206
1207 static struct partial_die_info *load_partial_dies
1208   (const struct die_reader_specs *, gdb_byte *, int);
1209
1210 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1211                                    struct partial_die_info *,
1212                                    struct abbrev_info *,
1213                                    unsigned int,
1214                                    gdb_byte *);
1215
1216 static struct partial_die_info *find_partial_die (sect_offset,
1217                                                   struct dwarf2_cu *);
1218
1219 static void fixup_partial_die (struct partial_die_info *,
1220                                struct dwarf2_cu *);
1221
1222 static gdb_byte *read_attribute (const struct die_reader_specs *,
1223                                  struct attribute *, struct attr_abbrev *,
1224                                  gdb_byte *);
1225
1226 static unsigned int read_1_byte (bfd *, gdb_byte *);
1227
1228 static int read_1_signed_byte (bfd *, gdb_byte *);
1229
1230 static unsigned int read_2_bytes (bfd *, gdb_byte *);
1231
1232 static unsigned int read_4_bytes (bfd *, gdb_byte *);
1233
1234 static ULONGEST read_8_bytes (bfd *, gdb_byte *);
1235
1236 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1237                                unsigned int *);
1238
1239 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1240
1241 static LONGEST read_checked_initial_length_and_offset
1242   (bfd *, gdb_byte *, const struct comp_unit_head *,
1243    unsigned int *, unsigned int *);
1244
1245 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1246                             unsigned int *);
1247
1248 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1249
1250 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1251                                        sect_offset);
1252
1253 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1254
1255 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1256
1257 static char *read_indirect_string (bfd *, gdb_byte *,
1258                                    const struct comp_unit_head *,
1259                                    unsigned int *);
1260
1261 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1262
1263 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1264
1265 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1266                                               unsigned int *);
1267
1268 static char *read_str_index (const struct die_reader_specs *reader,
1269                              struct dwarf2_cu *cu, ULONGEST str_index);
1270
1271 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1272
1273 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1274                                       struct dwarf2_cu *);
1275
1276 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1277                                                 unsigned int);
1278
1279 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1280                                struct dwarf2_cu *cu);
1281
1282 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1283
1284 static struct die_info *die_specification (struct die_info *die,
1285                                            struct dwarf2_cu **);
1286
1287 static void free_line_header (struct line_header *lh);
1288
1289 static void add_file_name (struct line_header *, char *, unsigned int,
1290                            unsigned int, unsigned int);
1291
1292 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1293                                                      struct dwarf2_cu *cu);
1294
1295 static void dwarf_decode_lines (struct line_header *, const char *,
1296                                 struct dwarf2_cu *, struct partial_symtab *,
1297                                 int);
1298
1299 static void dwarf2_start_subfile (char *, const char *, const char *);
1300
1301 static void dwarf2_start_symtab (struct dwarf2_cu *,
1302                                  char *, char *, CORE_ADDR);
1303
1304 static struct symbol *new_symbol (struct die_info *, struct type *,
1305                                   struct dwarf2_cu *);
1306
1307 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1308                                        struct dwarf2_cu *, struct symbol *);
1309
1310 static void dwarf2_const_value (struct attribute *, struct symbol *,
1311                                 struct dwarf2_cu *);
1312
1313 static void dwarf2_const_value_attr (struct attribute *attr,
1314                                      struct type *type,
1315                                      const char *name,
1316                                      struct obstack *obstack,
1317                                      struct dwarf2_cu *cu, LONGEST *value,
1318                                      gdb_byte **bytes,
1319                                      struct dwarf2_locexpr_baton **baton);
1320
1321 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1322
1323 static int need_gnat_info (struct dwarf2_cu *);
1324
1325 static struct type *die_descriptive_type (struct die_info *,
1326                                           struct dwarf2_cu *);
1327
1328 static void set_descriptive_type (struct type *, struct die_info *,
1329                                   struct dwarf2_cu *);
1330
1331 static struct type *die_containing_type (struct die_info *,
1332                                          struct dwarf2_cu *);
1333
1334 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1335                                      struct dwarf2_cu *);
1336
1337 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1338
1339 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1340
1341 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1342
1343 static char *typename_concat (struct obstack *obs, const char *prefix,
1344                               const char *suffix, int physname,
1345                               struct dwarf2_cu *cu);
1346
1347 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1348
1349 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1350
1351 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1352
1353 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1354
1355 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1356
1357 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1358                                struct dwarf2_cu *, struct partial_symtab *);
1359
1360 static int dwarf2_get_pc_bounds (struct die_info *,
1361                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1362                                  struct partial_symtab *);
1363
1364 static void get_scope_pc_bounds (struct die_info *,
1365                                  CORE_ADDR *, CORE_ADDR *,
1366                                  struct dwarf2_cu *);
1367
1368 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1369                                         CORE_ADDR, struct dwarf2_cu *);
1370
1371 static void dwarf2_add_field (struct field_info *, struct die_info *,
1372                               struct dwarf2_cu *);
1373
1374 static void dwarf2_attach_fields_to_type (struct field_info *,
1375                                           struct type *, struct dwarf2_cu *);
1376
1377 static void dwarf2_add_member_fn (struct field_info *,
1378                                   struct die_info *, struct type *,
1379                                   struct dwarf2_cu *);
1380
1381 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1382                                              struct type *,
1383                                              struct dwarf2_cu *);
1384
1385 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1386
1387 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1388
1389 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1390
1391 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1392
1393 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1394
1395 static struct type *read_module_type (struct die_info *die,
1396                                       struct dwarf2_cu *cu);
1397
1398 static const char *namespace_name (struct die_info *die,
1399                                    int *is_anonymous, struct dwarf2_cu *);
1400
1401 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1402
1403 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1404
1405 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1406                                                        struct dwarf2_cu *);
1407
1408 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1409                                                gdb_byte *info_ptr,
1410                                                gdb_byte **new_info_ptr,
1411                                                struct die_info *parent);
1412
1413 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1414                                                gdb_byte *info_ptr,
1415                                                gdb_byte **new_info_ptr,
1416                                                struct die_info *parent);
1417
1418 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1419                                   struct die_info **, gdb_byte *, int *, int);
1420
1421 static gdb_byte *read_full_die (const struct die_reader_specs *,
1422                                 struct die_info **, gdb_byte *, int *);
1423
1424 static void process_die (struct die_info *, struct dwarf2_cu *);
1425
1426 static char *dwarf2_canonicalize_name (char *, struct dwarf2_cu *,
1427                                        struct obstack *);
1428
1429 static char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1430
1431 static const char *dwarf2_full_name (char *name,
1432                                      struct die_info *die,
1433                                      struct dwarf2_cu *cu);
1434
1435 static struct die_info *dwarf2_extension (struct die_info *die,
1436                                           struct dwarf2_cu **);
1437
1438 static const char *dwarf_tag_name (unsigned int);
1439
1440 static const char *dwarf_attr_name (unsigned int);
1441
1442 static const char *dwarf_form_name (unsigned int);
1443
1444 static char *dwarf_bool_name (unsigned int);
1445
1446 static const char *dwarf_type_encoding_name (unsigned int);
1447
1448 static struct die_info *sibling_die (struct die_info *);
1449
1450 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1451
1452 static void dump_die_for_error (struct die_info *);
1453
1454 static void dump_die_1 (struct ui_file *, int level, int max_level,
1455                         struct die_info *);
1456
1457 /*static*/ void dump_die (struct die_info *, int max_level);
1458
1459 static void store_in_ref_table (struct die_info *,
1460                                 struct dwarf2_cu *);
1461
1462 static int is_ref_attr (struct attribute *);
1463
1464 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1465
1466 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1467
1468 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1469                                                struct attribute *,
1470                                                struct dwarf2_cu **);
1471
1472 static struct die_info *follow_die_ref (struct die_info *,
1473                                         struct attribute *,
1474                                         struct dwarf2_cu **);
1475
1476 static struct die_info *follow_die_sig (struct die_info *,
1477                                         struct attribute *,
1478                                         struct dwarf2_cu **);
1479
1480 static struct signatured_type *lookup_signatured_type_at_offset
1481     (struct objfile *objfile,
1482      struct dwarf2_section_info *section, sect_offset offset);
1483
1484 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1485
1486 static void read_signatured_type (struct signatured_type *);
1487
1488 static struct type_unit_group *get_type_unit_group
1489     (struct dwarf2_cu *, struct attribute *);
1490
1491 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1492
1493 /* memory allocation interface */
1494
1495 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1496
1497 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1498
1499 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1500                                  char *, int);
1501
1502 static int attr_form_is_block (struct attribute *);
1503
1504 static int attr_form_is_section_offset (struct attribute *);
1505
1506 static int attr_form_is_constant (struct attribute *);
1507
1508 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1509                                    struct dwarf2_loclist_baton *baton,
1510                                    struct attribute *attr);
1511
1512 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1513                                          struct symbol *sym,
1514                                          struct dwarf2_cu *cu);
1515
1516 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1517                                gdb_byte *info_ptr,
1518                                struct abbrev_info *abbrev);
1519
1520 static void free_stack_comp_unit (void *);
1521
1522 static hashval_t partial_die_hash (const void *item);
1523
1524 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1525
1526 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1527   (sect_offset offset, struct objfile *objfile);
1528
1529 static void init_one_comp_unit (struct dwarf2_cu *cu,
1530                                 struct dwarf2_per_cu_data *per_cu);
1531
1532 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1533                                    struct die_info *comp_unit_die,
1534                                    enum language pretend_language);
1535
1536 static void free_heap_comp_unit (void *);
1537
1538 static void free_cached_comp_units (void *);
1539
1540 static void age_cached_comp_units (void);
1541
1542 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1543
1544 static struct type *set_die_type (struct die_info *, struct type *,
1545                                   struct dwarf2_cu *);
1546
1547 static void create_all_comp_units (struct objfile *);
1548
1549 static int create_all_type_units (struct objfile *);
1550
1551 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1552                                  enum language);
1553
1554 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1555                                     enum language);
1556
1557 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1558                                     enum language);
1559
1560 static void dwarf2_add_dependence (struct dwarf2_cu *,
1561                                    struct dwarf2_per_cu_data *);
1562
1563 static void dwarf2_mark (struct dwarf2_cu *);
1564
1565 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1566
1567 static struct type *get_die_type_at_offset (sect_offset,
1568                                             struct dwarf2_per_cu_data *per_cu);
1569
1570 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1571
1572 static void dwarf2_release_queue (void *dummy);
1573
1574 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1575                              enum language pretend_language);
1576
1577 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1578                                   struct dwarf2_per_cu_data *per_cu,
1579                                   enum language pretend_language);
1580
1581 static void process_queue (void);
1582
1583 static void find_file_and_directory (struct die_info *die,
1584                                      struct dwarf2_cu *cu,
1585                                      char **name, char **comp_dir);
1586
1587 static char *file_full_name (int file, struct line_header *lh,
1588                              const char *comp_dir);
1589
1590 static void init_cutu_and_read_dies
1591   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1592    int use_existing_cu, int keep,
1593    die_reader_func_ftype *die_reader_func, void *data);
1594
1595 static void init_cutu_and_read_dies_simple
1596   (struct dwarf2_per_cu_data *this_cu,
1597    die_reader_func_ftype *die_reader_func, void *data);
1598
1599 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1600
1601 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1602
1603 static struct dwo_unit *lookup_dwo_comp_unit
1604   (struct dwarf2_per_cu_data *, char *, const char *, ULONGEST);
1605
1606 static struct dwo_unit *lookup_dwo_type_unit
1607   (struct signatured_type *, char *, const char *);
1608
1609 static void free_dwo_file_cleanup (void *);
1610
1611 static void munmap_section_buffer (struct dwarf2_section_info *);
1612
1613 static void process_cu_includes (void);
1614
1615 #if WORDS_BIGENDIAN
1616
1617 /* Convert VALUE between big- and little-endian.  */
1618 static offset_type
1619 byte_swap (offset_type value)
1620 {
1621   offset_type result;
1622
1623   result = (value & 0xff) << 24;
1624   result |= (value & 0xff00) << 8;
1625   result |= (value & 0xff0000) >> 8;
1626   result |= (value & 0xff000000) >> 24;
1627   return result;
1628 }
1629
1630 #define MAYBE_SWAP(V)  byte_swap (V)
1631
1632 #else
1633 #define MAYBE_SWAP(V) (V)
1634 #endif /* WORDS_BIGENDIAN */
1635
1636 /* The suffix for an index file.  */
1637 #define INDEX_SUFFIX ".gdb-index"
1638
1639 static const char *dwarf2_physname (char *name, struct die_info *die,
1640                                     struct dwarf2_cu *cu);
1641
1642 /* Try to locate the sections we need for DWARF 2 debugging
1643    information and return true if we have enough to do something.
1644    NAMES points to the dwarf2 section names, or is NULL if the standard
1645    ELF names are used.  */
1646
1647 int
1648 dwarf2_has_info (struct objfile *objfile,
1649                  const struct dwarf2_debug_sections *names)
1650 {
1651   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1652   if (!dwarf2_per_objfile)
1653     {
1654       /* Initialize per-objfile state.  */
1655       struct dwarf2_per_objfile *data
1656         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1657
1658       memset (data, 0, sizeof (*data));
1659       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1660       dwarf2_per_objfile = data;
1661
1662       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1663                              (void *) names);
1664       dwarf2_per_objfile->objfile = objfile;
1665     }
1666   return (dwarf2_per_objfile->info.asection != NULL
1667           && dwarf2_per_objfile->abbrev.asection != NULL);
1668 }
1669
1670 /* When loading sections, we look either for uncompressed section or for
1671    compressed section names.  */
1672
1673 static int
1674 section_is_p (const char *section_name,
1675               const struct dwarf2_section_names *names)
1676 {
1677   if (names->normal != NULL
1678       && strcmp (section_name, names->normal) == 0)
1679     return 1;
1680   if (names->compressed != NULL
1681       && strcmp (section_name, names->compressed) == 0)
1682     return 1;
1683   return 0;
1684 }
1685
1686 /* This function is mapped across the sections and remembers the
1687    offset and size of each of the debugging sections we are interested
1688    in.  */
1689
1690 static void
1691 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1692 {
1693   const struct dwarf2_debug_sections *names;
1694
1695   if (vnames == NULL)
1696     names = &dwarf2_elf_names;
1697   else
1698     names = (const struct dwarf2_debug_sections *) vnames;
1699
1700   if (section_is_p (sectp->name, &names->info))
1701     {
1702       dwarf2_per_objfile->info.asection = sectp;
1703       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1704     }
1705   else if (section_is_p (sectp->name, &names->abbrev))
1706     {
1707       dwarf2_per_objfile->abbrev.asection = sectp;
1708       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1709     }
1710   else if (section_is_p (sectp->name, &names->line))
1711     {
1712       dwarf2_per_objfile->line.asection = sectp;
1713       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1714     }
1715   else if (section_is_p (sectp->name, &names->loc))
1716     {
1717       dwarf2_per_objfile->loc.asection = sectp;
1718       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1719     }
1720   else if (section_is_p (sectp->name, &names->macinfo))
1721     {
1722       dwarf2_per_objfile->macinfo.asection = sectp;
1723       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1724     }
1725   else if (section_is_p (sectp->name, &names->macro))
1726     {
1727       dwarf2_per_objfile->macro.asection = sectp;
1728       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1729     }
1730   else if (section_is_p (sectp->name, &names->str))
1731     {
1732       dwarf2_per_objfile->str.asection = sectp;
1733       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1734     }
1735   else if (section_is_p (sectp->name, &names->addr))
1736     {
1737       dwarf2_per_objfile->addr.asection = sectp;
1738       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1739     }
1740   else if (section_is_p (sectp->name, &names->frame))
1741     {
1742       dwarf2_per_objfile->frame.asection = sectp;
1743       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1744     }
1745   else if (section_is_p (sectp->name, &names->eh_frame))
1746     {
1747       flagword aflag = bfd_get_section_flags (abfd, sectp);
1748
1749       if (aflag & SEC_HAS_CONTENTS)
1750         {
1751           dwarf2_per_objfile->eh_frame.asection = sectp;
1752           dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1753         }
1754     }
1755   else if (section_is_p (sectp->name, &names->ranges))
1756     {
1757       dwarf2_per_objfile->ranges.asection = sectp;
1758       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1759     }
1760   else if (section_is_p (sectp->name, &names->types))
1761     {
1762       struct dwarf2_section_info type_section;
1763
1764       memset (&type_section, 0, sizeof (type_section));
1765       type_section.asection = sectp;
1766       type_section.size = bfd_get_section_size (sectp);
1767
1768       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1769                      &type_section);
1770     }
1771   else if (section_is_p (sectp->name, &names->gdb_index))
1772     {
1773       dwarf2_per_objfile->gdb_index.asection = sectp;
1774       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1775     }
1776
1777   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1778       && bfd_section_vma (abfd, sectp) == 0)
1779     dwarf2_per_objfile->has_section_at_zero = 1;
1780 }
1781
1782 /* Decompress a section that was compressed using zlib.  Store the
1783    decompressed buffer, and its size, in OUTBUF and OUTSIZE.  */
1784
1785 static void
1786 zlib_decompress_section (struct objfile *objfile, asection *sectp,
1787                          gdb_byte **outbuf, bfd_size_type *outsize)
1788 {
1789   bfd *abfd = sectp->owner;
1790 #ifndef HAVE_ZLIB_H
1791   error (_("Support for zlib-compressed DWARF data (from '%s') "
1792            "is disabled in this copy of GDB"),
1793          bfd_get_filename (abfd));
1794 #else
1795   bfd_size_type compressed_size = bfd_get_section_size (sectp);
1796   gdb_byte *compressed_buffer = xmalloc (compressed_size);
1797   struct cleanup *cleanup = make_cleanup (xfree, compressed_buffer);
1798   bfd_size_type uncompressed_size;
1799   gdb_byte *uncompressed_buffer;
1800   z_stream strm;
1801   int rc;
1802   int header_size = 12;
1803
1804   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1805       || bfd_bread (compressed_buffer,
1806                     compressed_size, abfd) != compressed_size)
1807     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1808            bfd_get_filename (abfd));
1809
1810   /* Read the zlib header.  In this case, it should be "ZLIB" followed
1811      by the uncompressed section size, 8 bytes in big-endian order.  */
1812   if (compressed_size < header_size
1813       || strncmp (compressed_buffer, "ZLIB", 4) != 0)
1814     error (_("Dwarf Error: Corrupt DWARF ZLIB header from '%s'"),
1815            bfd_get_filename (abfd));
1816   uncompressed_size = compressed_buffer[4]; uncompressed_size <<= 8;
1817   uncompressed_size += compressed_buffer[5]; uncompressed_size <<= 8;
1818   uncompressed_size += compressed_buffer[6]; uncompressed_size <<= 8;
1819   uncompressed_size += compressed_buffer[7]; uncompressed_size <<= 8;
1820   uncompressed_size += compressed_buffer[8]; uncompressed_size <<= 8;
1821   uncompressed_size += compressed_buffer[9]; uncompressed_size <<= 8;
1822   uncompressed_size += compressed_buffer[10]; uncompressed_size <<= 8;
1823   uncompressed_size += compressed_buffer[11];
1824
1825   /* It is possible the section consists of several compressed
1826      buffers concatenated together, so we uncompress in a loop.  */
1827   strm.zalloc = NULL;
1828   strm.zfree = NULL;
1829   strm.opaque = NULL;
1830   strm.avail_in = compressed_size - header_size;
1831   strm.next_in = (Bytef*) compressed_buffer + header_size;
1832   strm.avail_out = uncompressed_size;
1833   uncompressed_buffer = obstack_alloc (&objfile->objfile_obstack,
1834                                        uncompressed_size);
1835   rc = inflateInit (&strm);
1836   while (strm.avail_in > 0)
1837     {
1838       if (rc != Z_OK)
1839         error (_("Dwarf Error: setting up DWARF uncompression in '%s': %d"),
1840                bfd_get_filename (abfd), rc);
1841       strm.next_out = ((Bytef*) uncompressed_buffer
1842                        + (uncompressed_size - strm.avail_out));
1843       rc = inflate (&strm, Z_FINISH);
1844       if (rc != Z_STREAM_END)
1845         error (_("Dwarf Error: zlib error uncompressing from '%s': %d"),
1846                bfd_get_filename (abfd), rc);
1847       rc = inflateReset (&strm);
1848     }
1849   rc = inflateEnd (&strm);
1850   if (rc != Z_OK
1851       || strm.avail_out != 0)
1852     error (_("Dwarf Error: concluding DWARF uncompression in '%s': %d"),
1853            bfd_get_filename (abfd), rc);
1854
1855   do_cleanups (cleanup);
1856   *outbuf = uncompressed_buffer;
1857   *outsize = uncompressed_size;
1858 #endif
1859 }
1860
1861 /* A helper function that decides whether a section is empty,
1862    or not present.  */
1863
1864 static int
1865 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1866 {
1867   return info->asection == NULL || info->size == 0;
1868 }
1869
1870 /* Read the contents of the section INFO.
1871    OBJFILE is the main object file, but not necessarily the file where
1872    the section comes from.  E.g., for DWO files INFO->asection->owner
1873    is the bfd of the DWO file.
1874    If the section is compressed, uncompress it before returning.  */
1875
1876 static void
1877 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1878 {
1879   asection *sectp = info->asection;
1880   bfd *abfd;
1881   gdb_byte *buf, *retbuf;
1882   unsigned char header[4];
1883
1884   if (info->readin)
1885     return;
1886   info->buffer = NULL;
1887   info->map_addr = NULL;
1888   info->readin = 1;
1889
1890   if (dwarf2_section_empty_p (info))
1891     return;
1892
1893   /* Note that ABFD may not be from OBJFILE, e.g. a DWO section.  */
1894   abfd = sectp->owner;
1895
1896   /* Check if the file has a 4-byte header indicating compression.  */
1897   if (info->size > sizeof (header)
1898       && bfd_seek (abfd, sectp->filepos, SEEK_SET) == 0
1899       && bfd_bread (header, sizeof (header), abfd) == sizeof (header))
1900     {
1901       /* Upon decompression, update the buffer and its size.  */
1902       if (strncmp (header, "ZLIB", sizeof (header)) == 0)
1903         {
1904           zlib_decompress_section (objfile, sectp, &info->buffer,
1905                                    &info->size);
1906           return;
1907         }
1908     }
1909
1910 #ifdef HAVE_MMAP
1911   if (pagesize == 0)
1912     pagesize = getpagesize ();
1913
1914   /* Only try to mmap sections which are large enough: we don't want to
1915      waste space due to fragmentation.  Also, only try mmap for sections
1916      without relocations.  */
1917
1918   if (info->size > 4 * pagesize && (sectp->flags & SEC_RELOC) == 0)
1919     {
1920       info->buffer = bfd_mmap (abfd, 0, info->size, PROT_READ,
1921                          MAP_PRIVATE, sectp->filepos,
1922                          &info->map_addr, &info->map_len);
1923
1924       if ((caddr_t)info->buffer != MAP_FAILED)
1925         {
1926 #if HAVE_POSIX_MADVISE
1927           posix_madvise (info->map_addr, info->map_len, POSIX_MADV_WILLNEED);
1928 #endif
1929           return;
1930         }
1931     }
1932 #endif
1933
1934   /* If we get here, we are a normal, not-compressed section.  */
1935   info->buffer = buf
1936     = obstack_alloc (&objfile->objfile_obstack, info->size);
1937
1938   /* When debugging .o files, we may need to apply relocations; see
1939      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1940      We never compress sections in .o files, so we only need to
1941      try this when the section is not compressed.  */
1942   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1943   if (retbuf != NULL)
1944     {
1945       info->buffer = retbuf;
1946       return;
1947     }
1948
1949   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1950       || bfd_bread (buf, info->size, abfd) != info->size)
1951     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1952            bfd_get_filename (abfd));
1953 }
1954
1955 /* A helper function that returns the size of a section in a safe way.
1956    If you are positive that the section has been read before using the
1957    size, then it is safe to refer to the dwarf2_section_info object's
1958    "size" field directly.  In other cases, you must call this
1959    function, because for compressed sections the size field is not set
1960    correctly until the section has been read.  */
1961
1962 static bfd_size_type
1963 dwarf2_section_size (struct objfile *objfile,
1964                      struct dwarf2_section_info *info)
1965 {
1966   if (!info->readin)
1967     dwarf2_read_section (objfile, info);
1968   return info->size;
1969 }
1970
1971 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1972    SECTION_NAME.  */
1973
1974 void
1975 dwarf2_get_section_info (struct objfile *objfile,
1976                          enum dwarf2_section_enum sect,
1977                          asection **sectp, gdb_byte **bufp,
1978                          bfd_size_type *sizep)
1979 {
1980   struct dwarf2_per_objfile *data
1981     = objfile_data (objfile, dwarf2_objfile_data_key);
1982   struct dwarf2_section_info *info;
1983
1984   /* We may see an objfile without any DWARF, in which case we just
1985      return nothing.  */
1986   if (data == NULL)
1987     {
1988       *sectp = NULL;
1989       *bufp = NULL;
1990       *sizep = 0;
1991       return;
1992     }
1993   switch (sect)
1994     {
1995     case DWARF2_DEBUG_FRAME:
1996       info = &data->frame;
1997       break;
1998     case DWARF2_EH_FRAME:
1999       info = &data->eh_frame;
2000       break;
2001     default:
2002       gdb_assert_not_reached ("unexpected section");
2003     }
2004
2005   dwarf2_read_section (objfile, info);
2006
2007   *sectp = info->asection;
2008   *bufp = info->buffer;
2009   *sizep = info->size;
2010 }
2011
2012 \f
2013 /* DWARF quick_symbols_functions support.  */
2014
2015 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2016    unique line tables, so we maintain a separate table of all .debug_line
2017    derived entries to support the sharing.
2018    All the quick functions need is the list of file names.  We discard the
2019    line_header when we're done and don't need to record it here.  */
2020 struct quick_file_names
2021 {
2022   /* The data used to construct the hash key.  */
2023   struct stmt_list_hash hash;
2024
2025   /* The number of entries in file_names, real_names.  */
2026   unsigned int num_file_names;
2027
2028   /* The file names from the line table, after being run through
2029      file_full_name.  */
2030   const char **file_names;
2031
2032   /* The file names from the line table after being run through
2033      gdb_realpath.  These are computed lazily.  */
2034   const char **real_names;
2035 };
2036
2037 /* When using the index (and thus not using psymtabs), each CU has an
2038    object of this type.  This is used to hold information needed by
2039    the various "quick" methods.  */
2040 struct dwarf2_per_cu_quick_data
2041 {
2042   /* The file table.  This can be NULL if there was no file table
2043      or it's currently not read in.
2044      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2045   struct quick_file_names *file_names;
2046
2047   /* The corresponding symbol table.  This is NULL if symbols for this
2048      CU have not yet been read.  */
2049   struct symtab *symtab;
2050
2051   /* A temporary mark bit used when iterating over all CUs in
2052      expand_symtabs_matching.  */
2053   unsigned int mark : 1;
2054
2055   /* True if we've tried to read the file table and found there isn't one.
2056      There will be no point in trying to read it again next time.  */
2057   unsigned int no_file_data : 1;
2058 };
2059
2060 /* Utility hash function for a stmt_list_hash.  */
2061
2062 static hashval_t
2063 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2064 {
2065   hashval_t v = 0;
2066
2067   if (stmt_list_hash->dwo_unit != NULL)
2068     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2069   v += stmt_list_hash->line_offset.sect_off;
2070   return v;
2071 }
2072
2073 /* Utility equality function for a stmt_list_hash.  */
2074
2075 static int
2076 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2077                     const struct stmt_list_hash *rhs)
2078 {
2079   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2080     return 0;
2081   if (lhs->dwo_unit != NULL
2082       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2083     return 0;
2084
2085   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2086 }
2087
2088 /* Hash function for a quick_file_names.  */
2089
2090 static hashval_t
2091 hash_file_name_entry (const void *e)
2092 {
2093   const struct quick_file_names *file_data = e;
2094
2095   return hash_stmt_list_entry (&file_data->hash);
2096 }
2097
2098 /* Equality function for a quick_file_names.  */
2099
2100 static int
2101 eq_file_name_entry (const void *a, const void *b)
2102 {
2103   const struct quick_file_names *ea = a;
2104   const struct quick_file_names *eb = b;
2105
2106   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2107 }
2108
2109 /* Delete function for a quick_file_names.  */
2110
2111 static void
2112 delete_file_name_entry (void *e)
2113 {
2114   struct quick_file_names *file_data = e;
2115   int i;
2116
2117   for (i = 0; i < file_data->num_file_names; ++i)
2118     {
2119       xfree ((void*) file_data->file_names[i]);
2120       if (file_data->real_names)
2121         xfree ((void*) file_data->real_names[i]);
2122     }
2123
2124   /* The space for the struct itself lives on objfile_obstack,
2125      so we don't free it here.  */
2126 }
2127
2128 /* Create a quick_file_names hash table.  */
2129
2130 static htab_t
2131 create_quick_file_names_table (unsigned int nr_initial_entries)
2132 {
2133   return htab_create_alloc (nr_initial_entries,
2134                             hash_file_name_entry, eq_file_name_entry,
2135                             delete_file_name_entry, xcalloc, xfree);
2136 }
2137
2138 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2139    have to be created afterwards.  You should call age_cached_comp_units after
2140    processing PER_CU->CU.  dw2_setup must have been already called.  */
2141
2142 static void
2143 load_cu (struct dwarf2_per_cu_data *per_cu)
2144 {
2145   if (per_cu->is_debug_types)
2146     load_full_type_unit (per_cu);
2147   else
2148     load_full_comp_unit (per_cu, language_minimal);
2149
2150   gdb_assert (per_cu->cu != NULL);
2151
2152   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2153 }
2154
2155 /* Read in the symbols for PER_CU.  */
2156
2157 static void
2158 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2159 {
2160   struct cleanup *back_to;
2161
2162   /* Skip type_unit_groups, reading the type units they contain
2163      is handled elsewhere.  */
2164   if (IS_TYPE_UNIT_GROUP (per_cu))
2165     return;
2166
2167   back_to = make_cleanup (dwarf2_release_queue, NULL);
2168
2169   if (dwarf2_per_objfile->using_index
2170       ? per_cu->v.quick->symtab == NULL
2171       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2172     {
2173       queue_comp_unit (per_cu, language_minimal);
2174       load_cu (per_cu);
2175     }
2176
2177   process_queue ();
2178
2179   /* Age the cache, releasing compilation units that have not
2180      been used recently.  */
2181   age_cached_comp_units ();
2182
2183   do_cleanups (back_to);
2184 }
2185
2186 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2187    the objfile from which this CU came.  Returns the resulting symbol
2188    table.  */
2189
2190 static struct symtab *
2191 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2192 {
2193   gdb_assert (dwarf2_per_objfile->using_index);
2194   if (!per_cu->v.quick->symtab)
2195     {
2196       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2197       increment_reading_symtab ();
2198       dw2_do_instantiate_symtab (per_cu);
2199       process_cu_includes ();
2200       do_cleanups (back_to);
2201     }
2202   return per_cu->v.quick->symtab;
2203 }
2204
2205 /* Return the CU given its index.
2206
2207    This is intended for loops like:
2208
2209    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2210                     + dwarf2_per_objfile->n_type_units); ++i)
2211      {
2212        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2213
2214        ...;
2215      }
2216 */
2217
2218 static struct dwarf2_per_cu_data *
2219 dw2_get_cu (int index)
2220 {
2221   if (index >= dwarf2_per_objfile->n_comp_units)
2222     {
2223       index -= dwarf2_per_objfile->n_comp_units;
2224       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2225       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2226     }
2227
2228   return dwarf2_per_objfile->all_comp_units[index];
2229 }
2230
2231 /* Return the primary CU given its index.
2232    The difference between this function and dw2_get_cu is in the handling
2233    of type units (TUs).  Here we return the type_unit_group object.
2234
2235    This is intended for loops like:
2236
2237    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2238                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2239      {
2240        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2241
2242        ...;
2243      }
2244 */
2245
2246 static struct dwarf2_per_cu_data *
2247 dw2_get_primary_cu (int index)
2248 {
2249   if (index >= dwarf2_per_objfile->n_comp_units)
2250     {
2251       index -= dwarf2_per_objfile->n_comp_units;
2252       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2253       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2254     }
2255
2256   return dwarf2_per_objfile->all_comp_units[index];
2257 }
2258
2259 /* A helper function that knows how to read a 64-bit value in a way
2260    that doesn't make gdb die.  Returns 1 if the conversion went ok, 0
2261    otherwise.  */
2262
2263 static int
2264 extract_cu_value (const char *bytes, ULONGEST *result)
2265 {
2266   if (sizeof (ULONGEST) < 8)
2267     {
2268       int i;
2269
2270       /* Ignore the upper 4 bytes if they are all zero.  */
2271       for (i = 0; i < 4; ++i)
2272         if (bytes[i + 4] != 0)
2273           return 0;
2274
2275       *result = extract_unsigned_integer (bytes, 4, BFD_ENDIAN_LITTLE);
2276     }
2277   else
2278     *result = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2279   return 1;
2280 }
2281
2282 /* Read the CU list from the mapped index, and use it to create all
2283    the CU objects for this objfile.  Return 0 if something went wrong,
2284    1 if everything went ok.  */
2285
2286 static int
2287 create_cus_from_index (struct objfile *objfile, const gdb_byte *cu_list,
2288                        offset_type cu_list_elements)
2289 {
2290   offset_type i;
2291
2292   dwarf2_per_objfile->n_comp_units = cu_list_elements / 2;
2293   dwarf2_per_objfile->all_comp_units
2294     = obstack_alloc (&objfile->objfile_obstack,
2295                      dwarf2_per_objfile->n_comp_units
2296                      * sizeof (struct dwarf2_per_cu_data *));
2297
2298   for (i = 0; i < cu_list_elements; i += 2)
2299     {
2300       struct dwarf2_per_cu_data *the_cu;
2301       ULONGEST offset, length;
2302
2303       if (!extract_cu_value (cu_list, &offset)
2304           || !extract_cu_value (cu_list + 8, &length))
2305         return 0;
2306       cu_list += 2 * 8;
2307
2308       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2309                                struct dwarf2_per_cu_data);
2310       the_cu->offset.sect_off = offset;
2311       the_cu->length = length;
2312       the_cu->objfile = objfile;
2313       the_cu->info_or_types_section = &dwarf2_per_objfile->info;
2314       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2315                                         struct dwarf2_per_cu_quick_data);
2316       dwarf2_per_objfile->all_comp_units[i / 2] = the_cu;
2317     }
2318
2319   return 1;
2320 }
2321
2322 /* Create the signatured type hash table from the index.  */
2323
2324 static int
2325 create_signatured_type_table_from_index (struct objfile *objfile,
2326                                          struct dwarf2_section_info *section,
2327                                          const gdb_byte *bytes,
2328                                          offset_type elements)
2329 {
2330   offset_type i;
2331   htab_t sig_types_hash;
2332
2333   dwarf2_per_objfile->n_type_units = elements / 3;
2334   dwarf2_per_objfile->all_type_units
2335     = obstack_alloc (&objfile->objfile_obstack,
2336                      dwarf2_per_objfile->n_type_units
2337                      * sizeof (struct signatured_type *));
2338
2339   sig_types_hash = allocate_signatured_type_table (objfile);
2340
2341   for (i = 0; i < elements; i += 3)
2342     {
2343       struct signatured_type *sig_type;
2344       ULONGEST offset, type_offset_in_tu, signature;
2345       void **slot;
2346
2347       if (!extract_cu_value (bytes, &offset)
2348           || !extract_cu_value (bytes + 8, &type_offset_in_tu))
2349         return 0;
2350       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2351       bytes += 3 * 8;
2352
2353       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2354                                  struct signatured_type);
2355       sig_type->signature = signature;
2356       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2357       sig_type->per_cu.is_debug_types = 1;
2358       sig_type->per_cu.info_or_types_section = section;
2359       sig_type->per_cu.offset.sect_off = offset;
2360       sig_type->per_cu.objfile = objfile;
2361       sig_type->per_cu.v.quick
2362         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2363                           struct dwarf2_per_cu_quick_data);
2364
2365       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2366       *slot = sig_type;
2367
2368       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2369     }
2370
2371   dwarf2_per_objfile->signatured_types = sig_types_hash;
2372
2373   return 1;
2374 }
2375
2376 /* Read the address map data from the mapped index, and use it to
2377    populate the objfile's psymtabs_addrmap.  */
2378
2379 static void
2380 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2381 {
2382   const gdb_byte *iter, *end;
2383   struct obstack temp_obstack;
2384   struct addrmap *mutable_map;
2385   struct cleanup *cleanup;
2386   CORE_ADDR baseaddr;
2387
2388   obstack_init (&temp_obstack);
2389   cleanup = make_cleanup_obstack_free (&temp_obstack);
2390   mutable_map = addrmap_create_mutable (&temp_obstack);
2391
2392   iter = index->address_table;
2393   end = iter + index->address_table_size;
2394
2395   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2396
2397   while (iter < end)
2398     {
2399       ULONGEST hi, lo, cu_index;
2400       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2401       iter += 8;
2402       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2403       iter += 8;
2404       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2405       iter += 4;
2406       
2407       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2408                          dw2_get_cu (cu_index));
2409     }
2410
2411   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2412                                                     &objfile->objfile_obstack);
2413   do_cleanups (cleanup);
2414 }
2415
2416 /* The hash function for strings in the mapped index.  This is the same as
2417    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2418    implementation.  This is necessary because the hash function is tied to the
2419    format of the mapped index file.  The hash values do not have to match with
2420    SYMBOL_HASH_NEXT.
2421    
2422    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2423
2424 static hashval_t
2425 mapped_index_string_hash (int index_version, const void *p)
2426 {
2427   const unsigned char *str = (const unsigned char *) p;
2428   hashval_t r = 0;
2429   unsigned char c;
2430
2431   while ((c = *str++) != 0)
2432     {
2433       if (index_version >= 5)
2434         c = tolower (c);
2435       r = r * 67 + c - 113;
2436     }
2437
2438   return r;
2439 }
2440
2441 /* Find a slot in the mapped index INDEX for the object named NAME.
2442    If NAME is found, set *VEC_OUT to point to the CU vector in the
2443    constant pool and return 1.  If NAME cannot be found, return 0.  */
2444
2445 static int
2446 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2447                           offset_type **vec_out)
2448 {
2449   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2450   offset_type hash;
2451   offset_type slot, step;
2452   int (*cmp) (const char *, const char *);
2453
2454   if (current_language->la_language == language_cplus
2455       || current_language->la_language == language_java
2456       || current_language->la_language == language_fortran)
2457     {
2458       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2459          not contain any.  */
2460       const char *paren = strchr (name, '(');
2461
2462       if (paren)
2463         {
2464           char *dup;
2465
2466           dup = xmalloc (paren - name + 1);
2467           memcpy (dup, name, paren - name);
2468           dup[paren - name] = 0;
2469
2470           make_cleanup (xfree, dup);
2471           name = dup;
2472         }
2473     }
2474
2475   /* Index version 4 did not support case insensitive searches.  But the
2476      indices for case insensitive languages are built in lowercase, therefore
2477      simulate our NAME being searched is also lowercased.  */
2478   hash = mapped_index_string_hash ((index->version == 4
2479                                     && case_sensitivity == case_sensitive_off
2480                                     ? 5 : index->version),
2481                                    name);
2482
2483   slot = hash & (index->symbol_table_slots - 1);
2484   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2485   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2486
2487   for (;;)
2488     {
2489       /* Convert a slot number to an offset into the table.  */
2490       offset_type i = 2 * slot;
2491       const char *str;
2492       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2493         {
2494           do_cleanups (back_to);
2495           return 0;
2496         }
2497
2498       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2499       if (!cmp (name, str))
2500         {
2501           *vec_out = (offset_type *) (index->constant_pool
2502                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2503           do_cleanups (back_to);
2504           return 1;
2505         }
2506
2507       slot = (slot + step) & (index->symbol_table_slots - 1);
2508     }
2509 }
2510
2511 /* Read the index file.  If everything went ok, initialize the "quick"
2512    elements of all the CUs and return 1.  Otherwise, return 0.  */
2513
2514 static int
2515 dwarf2_read_index (struct objfile *objfile)
2516 {
2517   char *addr;
2518   struct mapped_index *map;
2519   offset_type *metadata;
2520   const gdb_byte *cu_list;
2521   const gdb_byte *types_list = NULL;
2522   offset_type version, cu_list_elements;
2523   offset_type types_list_elements = 0;
2524   int i;
2525
2526   if (dwarf2_section_empty_p (&dwarf2_per_objfile->gdb_index))
2527     return 0;
2528
2529   /* Older elfutils strip versions could keep the section in the main
2530      executable while splitting it for the separate debug info file.  */
2531   if ((bfd_get_file_flags (dwarf2_per_objfile->gdb_index.asection)
2532        & SEC_HAS_CONTENTS) == 0)
2533     return 0;
2534
2535   dwarf2_read_section (objfile, &dwarf2_per_objfile->gdb_index);
2536
2537   addr = dwarf2_per_objfile->gdb_index.buffer;
2538   /* Version check.  */
2539   version = MAYBE_SWAP (*(offset_type *) addr);
2540   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2541      causes the index to behave very poorly for certain requests.  Version 3
2542      contained incomplete addrmap.  So, it seems better to just ignore such
2543      indices.  */
2544   if (version < 4)
2545     {
2546       static int warning_printed = 0;
2547       if (!warning_printed)
2548         {
2549           warning (_("Skipping obsolete .gdb_index section in %s."),
2550                    objfile->name);
2551           warning_printed = 1;
2552         }
2553       return 0;
2554     }
2555   /* Index version 4 uses a different hash function than index version
2556      5 and later.
2557
2558      Versions earlier than 6 did not emit psymbols for inlined
2559      functions.  Using these files will cause GDB not to be able to
2560      set breakpoints on inlined functions by name, so we ignore these
2561      indices unless the --use-deprecated-index-sections command line
2562      option was supplied.  */
2563   if (version < 6 && !use_deprecated_index_sections)
2564     {
2565       static int warning_printed = 0;
2566       if (!warning_printed)
2567         {
2568           warning (_("Skipping deprecated .gdb_index section in %s, pass "
2569                      "--use-deprecated-index-sections to use them anyway"),
2570                    objfile->name);
2571           warning_printed = 1;
2572         }
2573       return 0;
2574     }
2575   /* Indexes with higher version than the one supported by GDB may be no
2576      longer backward compatible.  */
2577   if (version > 7)
2578     return 0;
2579
2580   map = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct mapped_index);
2581   map->version = version;
2582   map->total_size = dwarf2_per_objfile->gdb_index.size;
2583
2584   metadata = (offset_type *) (addr + sizeof (offset_type));
2585
2586   i = 0;
2587   cu_list = addr + MAYBE_SWAP (metadata[i]);
2588   cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2589                       / 8);
2590   ++i;
2591
2592   types_list = addr + MAYBE_SWAP (metadata[i]);
2593   types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2594                           - MAYBE_SWAP (metadata[i]))
2595                          / 8);
2596   ++i;
2597
2598   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2599   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2600                              - MAYBE_SWAP (metadata[i]));
2601   ++i;
2602
2603   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2604   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2605                               - MAYBE_SWAP (metadata[i]))
2606                              / (2 * sizeof (offset_type)));
2607   ++i;
2608
2609   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2610
2611   /* Don't use the index if it's empty.  */
2612   if (map->symbol_table_slots == 0)
2613     return 0;
2614
2615   if (!create_cus_from_index (objfile, cu_list, cu_list_elements))
2616     return 0;
2617
2618   if (types_list_elements)
2619     {
2620       struct dwarf2_section_info *section;
2621
2622       /* We can only handle a single .debug_types when we have an
2623          index.  */
2624       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2625         return 0;
2626
2627       section = VEC_index (dwarf2_section_info_def,
2628                            dwarf2_per_objfile->types, 0);
2629
2630       if (!create_signatured_type_table_from_index (objfile, section,
2631                                                     types_list,
2632                                                     types_list_elements))
2633         return 0;
2634     }
2635
2636   create_addrmap_from_index (objfile, map);
2637
2638   dwarf2_per_objfile->index_table = map;
2639   dwarf2_per_objfile->using_index = 1;
2640   dwarf2_per_objfile->quick_file_names_table =
2641     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2642
2643   return 1;
2644 }
2645
2646 /* A helper for the "quick" functions which sets the global
2647    dwarf2_per_objfile according to OBJFILE.  */
2648
2649 static void
2650 dw2_setup (struct objfile *objfile)
2651 {
2652   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2653   gdb_assert (dwarf2_per_objfile);
2654 }
2655
2656 /* Reader function for dw2_build_type_unit_groups.  */
2657
2658 static void
2659 dw2_build_type_unit_groups_reader (const struct die_reader_specs *reader,
2660                                    gdb_byte *info_ptr,
2661                                    struct die_info *type_unit_die,
2662                                    int has_children,
2663                                    void *data)
2664 {
2665   struct dwarf2_cu *cu = reader->cu;
2666   struct attribute *attr;
2667   struct type_unit_group *tu_group;
2668
2669   gdb_assert (data == NULL);
2670
2671   if (! has_children)
2672     return;
2673
2674   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
2675   /* Call this for its side-effect of creating the associated
2676      struct type_unit_group if it doesn't already exist.  */
2677   tu_group = get_type_unit_group (cu, attr);
2678 }
2679
2680 /* Build dwarf2_per_objfile->type_unit_groups.
2681    This function may be called multiple times.  */
2682
2683 static void
2684 dw2_build_type_unit_groups (void)
2685 {
2686   if (dwarf2_per_objfile->type_unit_groups == NULL)
2687     build_type_unit_groups (dw2_build_type_unit_groups_reader, NULL);
2688 }
2689
2690 /* die_reader_func for dw2_get_file_names.  */
2691
2692 static void
2693 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2694                            gdb_byte *info_ptr,
2695                            struct die_info *comp_unit_die,
2696                            int has_children,
2697                            void *data)
2698 {
2699   struct dwarf2_cu *cu = reader->cu;
2700   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2701   struct objfile *objfile = dwarf2_per_objfile->objfile;
2702   struct dwarf2_per_cu_data *lh_cu;
2703   struct line_header *lh;
2704   struct attribute *attr;
2705   int i;
2706   char *name, *comp_dir;
2707   void **slot;
2708   struct quick_file_names *qfn;
2709   unsigned int line_offset;
2710
2711   /* Our callers never want to match partial units -- instead they
2712      will match the enclosing full CU.  */
2713   if (comp_unit_die->tag == DW_TAG_partial_unit)
2714     {
2715       this_cu->v.quick->no_file_data = 1;
2716       return;
2717     }
2718
2719   /* If we're reading the line header for TUs, store it in the "per_cu"
2720      for tu_group.  */
2721   if (this_cu->is_debug_types)
2722     {
2723       struct type_unit_group *tu_group = data;
2724
2725       gdb_assert (tu_group != NULL);
2726       lh_cu = &tu_group->per_cu;
2727     }
2728   else
2729     lh_cu = this_cu;
2730
2731   lh = NULL;
2732   slot = NULL;
2733   line_offset = 0;
2734
2735   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2736   if (attr)
2737     {
2738       struct quick_file_names find_entry;
2739
2740       line_offset = DW_UNSND (attr);
2741
2742       /* We may have already read in this line header (TU line header sharing).
2743          If we have we're done.  */
2744       find_entry.hash.dwo_unit = cu->dwo_unit;
2745       find_entry.hash.line_offset.sect_off = line_offset;
2746       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2747                              &find_entry, INSERT);
2748       if (*slot != NULL)
2749         {
2750           lh_cu->v.quick->file_names = *slot;
2751           return;
2752         }
2753
2754       lh = dwarf_decode_line_header (line_offset, cu);
2755     }
2756   if (lh == NULL)
2757     {
2758       lh_cu->v.quick->no_file_data = 1;
2759       return;
2760     }
2761
2762   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2763   qfn->hash.dwo_unit = cu->dwo_unit;
2764   qfn->hash.line_offset.sect_off = line_offset;
2765   gdb_assert (slot != NULL);
2766   *slot = qfn;
2767
2768   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2769
2770   qfn->num_file_names = lh->num_file_names;
2771   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2772                                    lh->num_file_names * sizeof (char *));
2773   for (i = 0; i < lh->num_file_names; ++i)
2774     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2775   qfn->real_names = NULL;
2776
2777   free_line_header (lh);
2778
2779   lh_cu->v.quick->file_names = qfn;
2780 }
2781
2782 /* A helper for the "quick" functions which attempts to read the line
2783    table for THIS_CU.  */
2784
2785 static struct quick_file_names *
2786 dw2_get_file_names (struct objfile *objfile,
2787                     struct dwarf2_per_cu_data *this_cu)
2788 {
2789   /* For TUs this should only be called on the parent group.  */
2790   if (this_cu->is_debug_types)
2791     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2792
2793   if (this_cu->v.quick->file_names != NULL)
2794     return this_cu->v.quick->file_names;
2795   /* If we know there is no line data, no point in looking again.  */
2796   if (this_cu->v.quick->no_file_data)
2797     return NULL;
2798
2799   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2800      in the stub for CUs, there's is no need to lookup the DWO file.
2801      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2802      DWO file.  */
2803   if (this_cu->is_debug_types)
2804     {
2805       struct type_unit_group *tu_group = this_cu->s.type_unit_group;
2806
2807       init_cutu_and_read_dies (tu_group->t.first_tu, NULL, 0, 0,
2808                                dw2_get_file_names_reader, tu_group);
2809     }
2810   else
2811     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2812
2813   if (this_cu->v.quick->no_file_data)
2814     return NULL;
2815   return this_cu->v.quick->file_names;
2816 }
2817
2818 /* A helper for the "quick" functions which computes and caches the
2819    real path for a given file name from the line table.  */
2820
2821 static const char *
2822 dw2_get_real_path (struct objfile *objfile,
2823                    struct quick_file_names *qfn, int index)
2824 {
2825   if (qfn->real_names == NULL)
2826     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2827                                       qfn->num_file_names, sizeof (char *));
2828
2829   if (qfn->real_names[index] == NULL)
2830     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2831
2832   return qfn->real_names[index];
2833 }
2834
2835 static struct symtab *
2836 dw2_find_last_source_symtab (struct objfile *objfile)
2837 {
2838   int index;
2839
2840   dw2_setup (objfile);
2841   index = dwarf2_per_objfile->n_comp_units - 1;
2842   return dw2_instantiate_symtab (dw2_get_cu (index));
2843 }
2844
2845 /* Traversal function for dw2_forget_cached_source_info.  */
2846
2847 static int
2848 dw2_free_cached_file_names (void **slot, void *info)
2849 {
2850   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2851
2852   if (file_data->real_names)
2853     {
2854       int i;
2855
2856       for (i = 0; i < file_data->num_file_names; ++i)
2857         {
2858           xfree ((void*) file_data->real_names[i]);
2859           file_data->real_names[i] = NULL;
2860         }
2861     }
2862
2863   return 1;
2864 }
2865
2866 static void
2867 dw2_forget_cached_source_info (struct objfile *objfile)
2868 {
2869   dw2_setup (objfile);
2870
2871   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
2872                           dw2_free_cached_file_names, NULL);
2873 }
2874
2875 /* Helper function for dw2_map_symtabs_matching_filename that expands
2876    the symtabs and calls the iterator.  */
2877
2878 static int
2879 dw2_map_expand_apply (struct objfile *objfile,
2880                       struct dwarf2_per_cu_data *per_cu,
2881                       const char *name,
2882                       const char *full_path, const char *real_path,
2883                       int (*callback) (struct symtab *, void *),
2884                       void *data)
2885 {
2886   struct symtab *last_made = objfile->symtabs;
2887
2888   /* Don't visit already-expanded CUs.  */
2889   if (per_cu->v.quick->symtab)
2890     return 0;
2891
2892   /* This may expand more than one symtab, and we want to iterate over
2893      all of them.  */
2894   dw2_instantiate_symtab (per_cu);
2895
2896   return iterate_over_some_symtabs (name, full_path, real_path, callback, data,
2897                                     objfile->symtabs, last_made);
2898 }
2899
2900 /* Implementation of the map_symtabs_matching_filename method.  */
2901
2902 static int
2903 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
2904                                    const char *full_path, const char *real_path,
2905                                    int (*callback) (struct symtab *, void *),
2906                                    void *data)
2907 {
2908   int i;
2909   const char *name_basename = lbasename (name);
2910   int name_len = strlen (name);
2911   int is_abs = IS_ABSOLUTE_PATH (name);
2912
2913   dw2_setup (objfile);
2914
2915   dw2_build_type_unit_groups ();
2916
2917   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2918                    + dwarf2_per_objfile->n_type_unit_groups); ++i)
2919     {
2920       int j;
2921       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2922       struct quick_file_names *file_data;
2923
2924       /* We only need to look at symtabs not already expanded.  */
2925       if (per_cu->v.quick->symtab)
2926         continue;
2927
2928       file_data = dw2_get_file_names (objfile, per_cu);
2929       if (file_data == NULL)
2930         continue;
2931
2932       for (j = 0; j < file_data->num_file_names; ++j)
2933         {
2934           const char *this_name = file_data->file_names[j];
2935
2936           if (FILENAME_CMP (name, this_name) == 0
2937               || (!is_abs && compare_filenames_for_search (this_name,
2938                                                            name, name_len)))
2939             {
2940               if (dw2_map_expand_apply (objfile, per_cu,
2941                                         name, full_path, real_path,
2942                                         callback, data))
2943                 return 1;
2944             }
2945
2946           /* Before we invoke realpath, which can get expensive when many
2947              files are involved, do a quick comparison of the basenames.  */
2948           if (! basenames_may_differ
2949               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
2950             continue;
2951
2952           if (full_path != NULL)
2953             {
2954               const char *this_real_name = dw2_get_real_path (objfile,
2955                                                               file_data, j);
2956
2957               if (this_real_name != NULL
2958                   && (FILENAME_CMP (full_path, this_real_name) == 0
2959                       || (!is_abs
2960                           && compare_filenames_for_search (this_real_name,
2961                                                            name, name_len))))
2962                 {
2963                   if (dw2_map_expand_apply (objfile, per_cu,
2964                                             name, full_path, real_path,
2965                                             callback, data))
2966                     return 1;
2967                 }
2968             }
2969
2970           if (real_path != NULL)
2971             {
2972               const char *this_real_name = dw2_get_real_path (objfile,
2973                                                               file_data, j);
2974
2975               if (this_real_name != NULL
2976                   && (FILENAME_CMP (real_path, this_real_name) == 0
2977                       || (!is_abs
2978                           && compare_filenames_for_search (this_real_name,
2979                                                            name, name_len))))
2980                 {
2981                   if (dw2_map_expand_apply (objfile, per_cu,
2982                                             name, full_path, real_path,
2983                                             callback, data))
2984                     return 1;
2985                 }
2986             }
2987         }
2988     }
2989
2990   return 0;
2991 }
2992
2993 static struct symtab *
2994 dw2_lookup_symbol (struct objfile *objfile, int block_index,
2995                    const char *name, domain_enum domain)
2996 {
2997   /* We do all the work in the pre_expand_symtabs_matching hook
2998      instead.  */
2999   return NULL;
3000 }
3001
3002 /* A helper function that expands all symtabs that hold an object
3003    named NAME.  If WANT_SPECIFIC_BLOCK is non-zero, only look for
3004    symbols in block BLOCK_KIND.  */
3005
3006 static void
3007 dw2_do_expand_symtabs_matching (struct objfile *objfile,
3008                                 int want_specific_block,
3009                                 enum block_enum block_kind,
3010                                 const char *name, domain_enum domain)
3011 {
3012   struct mapped_index *index;
3013
3014   dw2_setup (objfile);
3015
3016   index = dwarf2_per_objfile->index_table;
3017
3018   /* index_table is NULL if OBJF_READNOW.  */
3019   if (index)
3020     {
3021       offset_type *vec;
3022
3023       if (find_slot_in_mapped_hash (index, name, &vec))
3024         {
3025           offset_type i, len = MAYBE_SWAP (*vec);
3026           for (i = 0; i < len; ++i)
3027             {
3028               offset_type cu_index_and_attrs = MAYBE_SWAP (vec[i + 1]);
3029               offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3030               struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3031               int want_static = block_kind != GLOBAL_BLOCK;
3032               /* This value is only valid for index versions >= 7.  */
3033               int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3034               gdb_index_symbol_kind symbol_kind =
3035                 GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3036
3037               if (want_specific_block
3038                   && index->version >= 7
3039                   && want_static != is_static)
3040                 continue;
3041
3042               /* Only check the symbol's kind if it has one.
3043                  Indices prior to version 7 don't record it.  */
3044               if (index->version >= 7)
3045                 {
3046                   switch (domain)
3047                     {
3048                     case VAR_DOMAIN:
3049                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3050                           && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3051                           /* Some types are also in VAR_DOMAIN.  */
3052                           && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3053                         continue;
3054                       break;
3055                     case STRUCT_DOMAIN:
3056                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3057                         continue;
3058                       break;
3059                     case LABEL_DOMAIN:
3060                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3061                         continue;
3062                       break;
3063                     default:
3064                       break;
3065                     }
3066                 }
3067
3068               dw2_instantiate_symtab (per_cu);
3069             }
3070         }
3071     }
3072 }
3073
3074 static void
3075 dw2_pre_expand_symtabs_matching (struct objfile *objfile,
3076                                  enum block_enum block_kind, const char *name,
3077                                  domain_enum domain)
3078 {
3079   dw2_do_expand_symtabs_matching (objfile, 1, block_kind, name, domain);
3080 }
3081
3082 static void
3083 dw2_print_stats (struct objfile *objfile)
3084 {
3085   int i, count;
3086
3087   dw2_setup (objfile);
3088   count = 0;
3089   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3090                    + dwarf2_per_objfile->n_type_units); ++i)
3091     {
3092       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3093
3094       if (!per_cu->v.quick->symtab)
3095         ++count;
3096     }
3097   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3098 }
3099
3100 static void
3101 dw2_dump (struct objfile *objfile)
3102 {
3103   /* Nothing worth printing.  */
3104 }
3105
3106 static void
3107 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3108               struct section_offsets *delta)
3109 {
3110   /* There's nothing to relocate here.  */
3111 }
3112
3113 static void
3114 dw2_expand_symtabs_for_function (struct objfile *objfile,
3115                                  const char *func_name)
3116 {
3117   /* Note: It doesn't matter what we pass for block_kind here.  */
3118   dw2_do_expand_symtabs_matching (objfile, 0, GLOBAL_BLOCK, func_name,
3119                                   VAR_DOMAIN);
3120 }
3121
3122 static void
3123 dw2_expand_all_symtabs (struct objfile *objfile)
3124 {
3125   int i;
3126
3127   dw2_setup (objfile);
3128
3129   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3130                    + dwarf2_per_objfile->n_type_units); ++i)
3131     {
3132       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3133
3134       dw2_instantiate_symtab (per_cu);
3135     }
3136 }
3137
3138 static void
3139 dw2_expand_symtabs_with_filename (struct objfile *objfile,
3140                                   const char *filename)
3141 {
3142   int i;
3143
3144   dw2_setup (objfile);
3145
3146   /* We don't need to consider type units here.
3147      This is only called for examining code, e.g. expand_line_sal.
3148      There can be an order of magnitude (or more) more type units
3149      than comp units, and we avoid them if we can.  */
3150
3151   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3152     {
3153       int j;
3154       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3155       struct quick_file_names *file_data;
3156
3157       /* We only need to look at symtabs not already expanded.  */
3158       if (per_cu->v.quick->symtab)
3159         continue;
3160
3161       file_data = dw2_get_file_names (objfile, per_cu);
3162       if (file_data == NULL)
3163         continue;
3164
3165       for (j = 0; j < file_data->num_file_names; ++j)
3166         {
3167           const char *this_name = file_data->file_names[j];
3168           if (FILENAME_CMP (this_name, filename) == 0)
3169             {
3170               dw2_instantiate_symtab (per_cu);
3171               break;
3172             }
3173         }
3174     }
3175 }
3176
3177 /* A helper function for dw2_find_symbol_file that finds the primary
3178    file name for a given CU.  This is a die_reader_func.  */
3179
3180 static void
3181 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3182                                  gdb_byte *info_ptr,
3183                                  struct die_info *comp_unit_die,
3184                                  int has_children,
3185                                  void *data)
3186 {
3187   const char **result_ptr = data;
3188   struct dwarf2_cu *cu = reader->cu;
3189   struct attribute *attr;
3190
3191   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3192   if (attr == NULL)
3193     *result_ptr = NULL;
3194   else
3195     *result_ptr = DW_STRING (attr);
3196 }
3197
3198 static const char *
3199 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3200 {
3201   struct dwarf2_per_cu_data *per_cu;
3202   offset_type *vec;
3203   struct quick_file_names *file_data;
3204   const char *filename;
3205
3206   dw2_setup (objfile);
3207
3208   /* index_table is NULL if OBJF_READNOW.  */
3209   if (!dwarf2_per_objfile->index_table)
3210     {
3211       struct symtab *s;
3212
3213       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3214         {
3215           struct blockvector *bv = BLOCKVECTOR (s);
3216           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3217           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3218
3219           if (sym)
3220             return sym->symtab->filename;
3221         }
3222       return NULL;
3223     }
3224
3225   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3226                                  name, &vec))
3227     return NULL;
3228
3229   /* Note that this just looks at the very first one named NAME -- but
3230      actually we are looking for a function.  find_main_filename
3231      should be rewritten so that it doesn't require a custom hook.  It
3232      could just use the ordinary symbol tables.  */
3233   /* vec[0] is the length, which must always be >0.  */
3234   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3235
3236   if (per_cu->v.quick->symtab != NULL)
3237     return per_cu->v.quick->symtab->filename;
3238
3239   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3240                            dw2_get_primary_filename_reader, &filename);
3241
3242   return filename;
3243 }
3244
3245 static void
3246 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3247                           struct objfile *objfile, int global,
3248                           int (*callback) (struct block *,
3249                                            struct symbol *, void *),
3250                           void *data, symbol_compare_ftype *match,
3251                           symbol_compare_ftype *ordered_compare)
3252 {
3253   /* Currently unimplemented; used for Ada.  The function can be called if the
3254      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3255      does not look for non-Ada symbols this function should just return.  */
3256 }
3257
3258 static void
3259 dw2_expand_symtabs_matching
3260   (struct objfile *objfile,
3261    int (*file_matcher) (const char *, void *),
3262    int (*name_matcher) (const char *, void *),
3263    enum search_domain kind,
3264    void *data)
3265 {
3266   int i;
3267   offset_type iter;
3268   struct mapped_index *index;
3269
3270   dw2_setup (objfile);
3271
3272   /* index_table is NULL if OBJF_READNOW.  */
3273   if (!dwarf2_per_objfile->index_table)
3274     return;
3275   index = dwarf2_per_objfile->index_table;
3276
3277   if (file_matcher != NULL)
3278     {
3279       struct cleanup *cleanup;
3280       htab_t visited_found, visited_not_found;
3281
3282       dw2_build_type_unit_groups ();
3283
3284       visited_found = htab_create_alloc (10,
3285                                          htab_hash_pointer, htab_eq_pointer,
3286                                          NULL, xcalloc, xfree);
3287       cleanup = make_cleanup_htab_delete (visited_found);
3288       visited_not_found = htab_create_alloc (10,
3289                                              htab_hash_pointer, htab_eq_pointer,
3290                                              NULL, xcalloc, xfree);
3291       make_cleanup_htab_delete (visited_not_found);
3292
3293       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3294                        + dwarf2_per_objfile->n_type_unit_groups); ++i)
3295         {
3296           int j;
3297           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3298           struct quick_file_names *file_data;
3299           void **slot;
3300
3301           per_cu->v.quick->mark = 0;
3302
3303           /* We only need to look at symtabs not already expanded.  */
3304           if (per_cu->v.quick->symtab)
3305             continue;
3306
3307           file_data = dw2_get_file_names (objfile, per_cu);
3308           if (file_data == NULL)
3309             continue;
3310
3311           if (htab_find (visited_not_found, file_data) != NULL)
3312             continue;
3313           else if (htab_find (visited_found, file_data) != NULL)
3314             {
3315               per_cu->v.quick->mark = 1;
3316               continue;
3317             }
3318
3319           for (j = 0; j < file_data->num_file_names; ++j)
3320             {
3321               if (file_matcher (file_data->file_names[j], data))
3322                 {
3323                   per_cu->v.quick->mark = 1;
3324                   break;
3325                 }
3326             }
3327
3328           slot = htab_find_slot (per_cu->v.quick->mark
3329                                  ? visited_found
3330                                  : visited_not_found,
3331                                  file_data, INSERT);
3332           *slot = file_data;
3333         }
3334
3335       do_cleanups (cleanup);
3336     }
3337
3338   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3339     {
3340       offset_type idx = 2 * iter;
3341       const char *name;
3342       offset_type *vec, vec_len, vec_idx;
3343
3344       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3345         continue;
3346
3347       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3348
3349       if (! (*name_matcher) (name, data))
3350         continue;
3351
3352       /* The name was matched, now expand corresponding CUs that were
3353          marked.  */
3354       vec = (offset_type *) (index->constant_pool
3355                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3356       vec_len = MAYBE_SWAP (vec[0]);
3357       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3358         {
3359           struct dwarf2_per_cu_data *per_cu;
3360           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3361           gdb_index_symbol_kind symbol_kind =
3362             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3363           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3364
3365           /* Don't crash on bad data.  */
3366           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3367                            + dwarf2_per_objfile->n_type_units))
3368             continue;
3369
3370           /* Only check the symbol's kind if it has one.
3371              Indices prior to version 7 don't record it.  */
3372           if (index->version >= 7)
3373             {
3374               switch (kind)
3375                 {
3376                 case VARIABLES_DOMAIN:
3377                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3378                     continue;
3379                   break;
3380                 case FUNCTIONS_DOMAIN:
3381                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3382                     continue;
3383                   break;
3384                 case TYPES_DOMAIN:
3385                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3386                     continue;
3387                   break;
3388                 default:
3389                   break;
3390                 }
3391             }
3392
3393           per_cu = dw2_get_cu (cu_index);
3394           if (file_matcher == NULL || per_cu->v.quick->mark)
3395             dw2_instantiate_symtab (per_cu);
3396         }
3397     }
3398 }
3399
3400 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3401    symtab.  */
3402
3403 static struct symtab *
3404 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3405 {
3406   int i;
3407
3408   if (BLOCKVECTOR (symtab) != NULL
3409       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3410     return symtab;
3411
3412   if (symtab->includes == NULL)
3413     return NULL;
3414
3415   for (i = 0; symtab->includes[i]; ++i)
3416     {
3417       struct symtab *s = symtab->includes[i];
3418
3419       s = recursively_find_pc_sect_symtab (s, pc);
3420       if (s != NULL)
3421         return s;
3422     }
3423
3424   return NULL;
3425 }
3426
3427 static struct symtab *
3428 dw2_find_pc_sect_symtab (struct objfile *objfile,
3429                          struct minimal_symbol *msymbol,
3430                          CORE_ADDR pc,
3431                          struct obj_section *section,
3432                          int warn_if_readin)
3433 {
3434   struct dwarf2_per_cu_data *data;
3435   struct symtab *result;
3436
3437   dw2_setup (objfile);
3438
3439   if (!objfile->psymtabs_addrmap)
3440     return NULL;
3441
3442   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3443   if (!data)
3444     return NULL;
3445
3446   if (warn_if_readin && data->v.quick->symtab)
3447     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3448              paddress (get_objfile_arch (objfile), pc));
3449
3450   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3451   gdb_assert (result != NULL);
3452   return result;
3453 }
3454
3455 static void
3456 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3457                           void *data, int need_fullname)
3458 {
3459   int i;
3460   struct cleanup *cleanup;
3461   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3462                                       NULL, xcalloc, xfree);
3463
3464   cleanup = make_cleanup_htab_delete (visited);
3465   dw2_setup (objfile);
3466
3467   dw2_build_type_unit_groups ();
3468
3469   /* We can ignore file names coming from already-expanded CUs.  */
3470   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3471                    + dwarf2_per_objfile->n_type_units); ++i)
3472     {
3473       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3474
3475       if (per_cu->v.quick->symtab)
3476         {
3477           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3478                                         INSERT);
3479
3480           *slot = per_cu->v.quick->file_names;
3481         }
3482     }
3483
3484   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3485                    + dwarf2_per_objfile->n_type_unit_groups); ++i)
3486     {
3487       int j;
3488       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3489       struct quick_file_names *file_data;
3490       void **slot;
3491
3492       /* We only need to look at symtabs not already expanded.  */
3493       if (per_cu->v.quick->symtab)
3494         continue;
3495
3496       file_data = dw2_get_file_names (objfile, per_cu);
3497       if (file_data == NULL)
3498         continue;
3499
3500       slot = htab_find_slot (visited, file_data, INSERT);
3501       if (*slot)
3502         {
3503           /* Already visited.  */
3504           continue;
3505         }
3506       *slot = file_data;
3507
3508       for (j = 0; j < file_data->num_file_names; ++j)
3509         {
3510           const char *this_real_name;
3511
3512           if (need_fullname)
3513             this_real_name = dw2_get_real_path (objfile, file_data, j);
3514           else
3515             this_real_name = NULL;
3516           (*fun) (file_data->file_names[j], this_real_name, data);
3517         }
3518     }
3519
3520   do_cleanups (cleanup);
3521 }
3522
3523 static int
3524 dw2_has_symbols (struct objfile *objfile)
3525 {
3526   return 1;
3527 }
3528
3529 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3530 {
3531   dw2_has_symbols,
3532   dw2_find_last_source_symtab,
3533   dw2_forget_cached_source_info,
3534   dw2_map_symtabs_matching_filename,
3535   dw2_lookup_symbol,
3536   dw2_pre_expand_symtabs_matching,
3537   dw2_print_stats,
3538   dw2_dump,
3539   dw2_relocate,
3540   dw2_expand_symtabs_for_function,
3541   dw2_expand_all_symtabs,
3542   dw2_expand_symtabs_with_filename,
3543   dw2_find_symbol_file,
3544   dw2_map_matching_symbols,
3545   dw2_expand_symtabs_matching,
3546   dw2_find_pc_sect_symtab,
3547   dw2_map_symbol_filenames
3548 };
3549
3550 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3551    file will use psymtabs, or 1 if using the GNU index.  */
3552
3553 int
3554 dwarf2_initialize_objfile (struct objfile *objfile)
3555 {
3556   /* If we're about to read full symbols, don't bother with the
3557      indices.  In this case we also don't care if some other debug
3558      format is making psymtabs, because they are all about to be
3559      expanded anyway.  */
3560   if ((objfile->flags & OBJF_READNOW))
3561     {
3562       int i;
3563
3564       dwarf2_per_objfile->using_index = 1;
3565       create_all_comp_units (objfile);
3566       create_all_type_units (objfile);
3567       dwarf2_per_objfile->quick_file_names_table =
3568         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3569
3570       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3571                        + dwarf2_per_objfile->n_type_units); ++i)
3572         {
3573           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3574
3575           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3576                                             struct dwarf2_per_cu_quick_data);
3577         }
3578
3579       /* Return 1 so that gdb sees the "quick" functions.  However,
3580          these functions will be no-ops because we will have expanded
3581          all symtabs.  */
3582       return 1;
3583     }
3584
3585   if (dwarf2_read_index (objfile))
3586     return 1;
3587
3588   return 0;
3589 }
3590
3591 \f
3592
3593 /* Build a partial symbol table.  */
3594
3595 void
3596 dwarf2_build_psymtabs (struct objfile *objfile)
3597 {
3598   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3599     {
3600       init_psymbol_list (objfile, 1024);
3601     }
3602
3603   dwarf2_build_psymtabs_hard (objfile);
3604 }
3605
3606 /* Return the total length of the CU described by HEADER.  */
3607
3608 static unsigned int
3609 get_cu_length (const struct comp_unit_head *header)
3610 {
3611   return header->initial_length_size + header->length;
3612 }
3613
3614 /* Return TRUE if OFFSET is within CU_HEADER.  */
3615
3616 static inline int
3617 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3618 {
3619   sect_offset bottom = { cu_header->offset.sect_off };
3620   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3621
3622   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3623 }
3624
3625 /* Find the base address of the compilation unit for range lists and
3626    location lists.  It will normally be specified by DW_AT_low_pc.
3627    In DWARF-3 draft 4, the base address could be overridden by
3628    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3629    compilation units with discontinuous ranges.  */
3630
3631 static void
3632 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3633 {
3634   struct attribute *attr;
3635
3636   cu->base_known = 0;
3637   cu->base_address = 0;
3638
3639   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3640   if (attr)
3641     {
3642       cu->base_address = DW_ADDR (attr);
3643       cu->base_known = 1;
3644     }
3645   else
3646     {
3647       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3648       if (attr)
3649         {
3650           cu->base_address = DW_ADDR (attr);
3651           cu->base_known = 1;
3652         }
3653     }
3654 }
3655
3656 /* Read in the comp unit header information from the debug_info at info_ptr.
3657    NOTE: This leaves members offset, first_die_offset to be filled in
3658    by the caller.  */
3659
3660 static gdb_byte *
3661 read_comp_unit_head (struct comp_unit_head *cu_header,
3662                      gdb_byte *info_ptr, bfd *abfd)
3663 {
3664   int signed_addr;
3665   unsigned int bytes_read;
3666
3667   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3668   cu_header->initial_length_size = bytes_read;
3669   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3670   info_ptr += bytes_read;
3671   cu_header->version = read_2_bytes (abfd, info_ptr);
3672   info_ptr += 2;
3673   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3674                                              &bytes_read);
3675   info_ptr += bytes_read;
3676   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3677   info_ptr += 1;
3678   signed_addr = bfd_get_sign_extend_vma (abfd);
3679   if (signed_addr < 0)
3680     internal_error (__FILE__, __LINE__,
3681                     _("read_comp_unit_head: dwarf from non elf file"));
3682   cu_header->signed_addr_p = signed_addr;
3683
3684   return info_ptr;
3685 }
3686
3687 /* Subroutine of read_and_check_comp_unit_head and
3688    read_and_check_type_unit_head to simplify them.
3689    Perform various error checking on the header.  */
3690
3691 static void
3692 error_check_comp_unit_head (struct comp_unit_head *header,
3693                             struct dwarf2_section_info *section,
3694                             struct dwarf2_section_info *abbrev_section)
3695 {
3696   bfd *abfd = section->asection->owner;
3697   const char *filename = bfd_get_filename (abfd);
3698
3699   if (header->version != 2 && header->version != 3 && header->version != 4)
3700     error (_("Dwarf Error: wrong version in compilation unit header "
3701            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3702            filename);
3703
3704   if (header->abbrev_offset.sect_off
3705       >= dwarf2_section_size (dwarf2_per_objfile->objfile,
3706                               &dwarf2_per_objfile->abbrev))
3707     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3708            "(offset 0x%lx + 6) [in module %s]"),
3709            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3710            filename);
3711
3712   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3713      avoid potential 32-bit overflow.  */
3714   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3715       > section->size)
3716     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3717            "(offset 0x%lx + 0) [in module %s]"),
3718            (long) header->length, (long) header->offset.sect_off,
3719            filename);
3720 }
3721
3722 /* Read in a CU/TU header and perform some basic error checking.
3723    The contents of the header are stored in HEADER.
3724    The result is a pointer to the start of the first DIE.  */
3725
3726 static gdb_byte *
3727 read_and_check_comp_unit_head (struct comp_unit_head *header,
3728                                struct dwarf2_section_info *section,
3729                                struct dwarf2_section_info *abbrev_section,
3730                                gdb_byte *info_ptr,
3731                                int is_debug_types_section)
3732 {
3733   gdb_byte *beg_of_comp_unit = info_ptr;
3734   bfd *abfd = section->asection->owner;
3735
3736   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3737
3738   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3739
3740   /* If we're reading a type unit, skip over the signature and
3741      type_offset fields.  */
3742   if (is_debug_types_section)
3743     info_ptr += 8 /*signature*/ + header->offset_size;
3744
3745   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3746
3747   error_check_comp_unit_head (header, section, abbrev_section);
3748
3749   return info_ptr;
3750 }
3751
3752 /* Read in the types comp unit header information from .debug_types entry at
3753    types_ptr.  The result is a pointer to one past the end of the header.  */
3754
3755 static gdb_byte *
3756 read_and_check_type_unit_head (struct comp_unit_head *header,
3757                                struct dwarf2_section_info *section,
3758                                struct dwarf2_section_info *abbrev_section,
3759                                gdb_byte *info_ptr,
3760                                ULONGEST *signature,
3761                                cu_offset *type_offset_in_tu)
3762 {
3763   gdb_byte *beg_of_comp_unit = info_ptr;
3764   bfd *abfd = section->asection->owner;
3765
3766   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3767
3768   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3769
3770   /* If we're reading a type unit, skip over the signature and
3771      type_offset fields.  */
3772   if (signature != NULL)
3773     *signature = read_8_bytes (abfd, info_ptr);
3774   info_ptr += 8;
3775   if (type_offset_in_tu != NULL)
3776     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
3777                                                header->offset_size);
3778   info_ptr += header->offset_size;
3779
3780   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3781
3782   error_check_comp_unit_head (header, section, abbrev_section);
3783
3784   return info_ptr;
3785 }
3786
3787 /* Fetch the abbreviation table offset from a comp or type unit header.  */
3788
3789 static sect_offset
3790 read_abbrev_offset (struct dwarf2_section_info *section,
3791                     sect_offset offset)
3792 {
3793   bfd *abfd = section->asection->owner;
3794   gdb_byte *info_ptr;
3795   unsigned int length, initial_length_size, offset_size;
3796   sect_offset abbrev_offset;
3797
3798   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
3799   info_ptr = section->buffer + offset.sect_off;
3800   length = read_initial_length (abfd, info_ptr, &initial_length_size);
3801   offset_size = initial_length_size == 4 ? 4 : 8;
3802   info_ptr += initial_length_size + 2 /*version*/;
3803   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
3804   return abbrev_offset;
3805 }
3806
3807 /* Allocate a new partial symtab for file named NAME and mark this new
3808    partial symtab as being an include of PST.  */
3809
3810 static void
3811 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
3812                                struct objfile *objfile)
3813 {
3814   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
3815
3816   subpst->section_offsets = pst->section_offsets;
3817   subpst->textlow = 0;
3818   subpst->texthigh = 0;
3819
3820   subpst->dependencies = (struct partial_symtab **)
3821     obstack_alloc (&objfile->objfile_obstack,
3822                    sizeof (struct partial_symtab *));
3823   subpst->dependencies[0] = pst;
3824   subpst->number_of_dependencies = 1;
3825
3826   subpst->globals_offset = 0;
3827   subpst->n_global_syms = 0;
3828   subpst->statics_offset = 0;
3829   subpst->n_static_syms = 0;
3830   subpst->symtab = NULL;
3831   subpst->read_symtab = pst->read_symtab;
3832   subpst->readin = 0;
3833
3834   /* No private part is necessary for include psymtabs.  This property
3835      can be used to differentiate between such include psymtabs and
3836      the regular ones.  */
3837   subpst->read_symtab_private = NULL;
3838 }
3839
3840 /* Read the Line Number Program data and extract the list of files
3841    included by the source file represented by PST.  Build an include
3842    partial symtab for each of these included files.  */
3843
3844 static void
3845 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
3846                                struct die_info *die,
3847                                struct partial_symtab *pst)
3848 {
3849   struct line_header *lh = NULL;
3850   struct attribute *attr;
3851
3852   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
3853   if (attr)
3854     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
3855   if (lh == NULL)
3856     return;  /* No linetable, so no includes.  */
3857
3858   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
3859   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
3860
3861   free_line_header (lh);
3862 }
3863
3864 static hashval_t
3865 hash_signatured_type (const void *item)
3866 {
3867   const struct signatured_type *sig_type = item;
3868
3869   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
3870   return sig_type->signature;
3871 }
3872
3873 static int
3874 eq_signatured_type (const void *item_lhs, const void *item_rhs)
3875 {
3876   const struct signatured_type *lhs = item_lhs;
3877   const struct signatured_type *rhs = item_rhs;
3878
3879   return lhs->signature == rhs->signature;
3880 }
3881
3882 /* Allocate a hash table for signatured types.  */
3883
3884 static htab_t
3885 allocate_signatured_type_table (struct objfile *objfile)
3886 {
3887   return htab_create_alloc_ex (41,
3888                                hash_signatured_type,
3889                                eq_signatured_type,
3890                                NULL,
3891                                &objfile->objfile_obstack,
3892                                hashtab_obstack_allocate,
3893                                dummy_obstack_deallocate);
3894 }
3895
3896 /* A helper function to add a signatured type CU to a table.  */
3897
3898 static int
3899 add_signatured_type_cu_to_table (void **slot, void *datum)
3900 {
3901   struct signatured_type *sigt = *slot;
3902   struct signatured_type ***datap = datum;
3903
3904   **datap = sigt;
3905   ++*datap;
3906
3907   return 1;
3908 }
3909
3910 /* Create the hash table of all entries in the .debug_types section.
3911    DWO_FILE is a pointer to the DWO file for .debug_types.dwo, NULL otherwise.
3912    The result is a pointer to the hash table or NULL if there are
3913    no types.  */
3914
3915 static htab_t
3916 create_debug_types_hash_table (struct dwo_file *dwo_file,
3917                                VEC (dwarf2_section_info_def) *types)
3918 {
3919   struct objfile *objfile = dwarf2_per_objfile->objfile;
3920   htab_t types_htab = NULL;
3921   int ix;
3922   struct dwarf2_section_info *section;
3923   struct dwarf2_section_info *abbrev_section;
3924
3925   if (VEC_empty (dwarf2_section_info_def, types))
3926     return NULL;
3927
3928   abbrev_section = (dwo_file != NULL
3929                     ? &dwo_file->sections.abbrev
3930                     : &dwarf2_per_objfile->abbrev);
3931
3932   if (dwarf2_read_debug)
3933     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
3934                         dwo_file ? ".dwo" : "",
3935                         bfd_get_filename (abbrev_section->asection->owner));
3936
3937   for (ix = 0;
3938        VEC_iterate (dwarf2_section_info_def, types, ix, section);
3939        ++ix)
3940     {
3941       bfd *abfd;
3942       gdb_byte *info_ptr, *end_ptr;
3943
3944       dwarf2_read_section (objfile, section);
3945       info_ptr = section->buffer;
3946
3947       if (info_ptr == NULL)
3948         continue;
3949
3950       /* We can't set abfd until now because the section may be empty or
3951          not present, in which case section->asection will be NULL.  */
3952       abfd = section->asection->owner;
3953
3954       if (types_htab == NULL)
3955         {
3956           if (dwo_file)
3957             types_htab = allocate_dwo_unit_table (objfile);
3958           else
3959             types_htab = allocate_signatured_type_table (objfile);
3960         }
3961
3962       /* We don't use init_cutu_and_read_dies_simple, or some such, here
3963          because we don't need to read any dies: the signature is in the
3964          header.  */
3965
3966       end_ptr = info_ptr + section->size;
3967       while (info_ptr < end_ptr)
3968         {
3969           sect_offset offset;
3970           cu_offset type_offset_in_tu;
3971           ULONGEST signature;
3972           struct signatured_type *sig_type;
3973           struct dwo_unit *dwo_tu;
3974           void **slot;
3975           gdb_byte *ptr = info_ptr;
3976           struct comp_unit_head header;
3977           unsigned int length;
3978
3979           offset.sect_off = ptr - section->buffer;
3980
3981           /* We need to read the type's signature in order to build the hash
3982              table, but we don't need anything else just yet.  */
3983
3984           ptr = read_and_check_type_unit_head (&header, section,
3985                                                abbrev_section, ptr,
3986                                                &signature, &type_offset_in_tu);
3987
3988           length = get_cu_length (&header);
3989
3990           /* Skip dummy type units.  */
3991           if (ptr >= info_ptr + length
3992               || peek_abbrev_code (abfd, ptr) == 0)
3993             {
3994               info_ptr += length;
3995               continue;
3996             }
3997
3998           if (dwo_file)
3999             {
4000               sig_type = NULL;
4001               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4002                                        struct dwo_unit);
4003               dwo_tu->dwo_file = dwo_file;
4004               dwo_tu->signature = signature;
4005               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4006               dwo_tu->info_or_types_section = section;
4007               dwo_tu->offset = offset;
4008               dwo_tu->length = length;
4009             }
4010           else
4011             {
4012               /* N.B.: type_offset is not usable if this type uses a DWO file.
4013                  The real type_offset is in the DWO file.  */
4014               dwo_tu = NULL;
4015               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4016                                          struct signatured_type);
4017               sig_type->signature = signature;
4018               sig_type->type_offset_in_tu = type_offset_in_tu;
4019               sig_type->per_cu.objfile = objfile;
4020               sig_type->per_cu.is_debug_types = 1;
4021               sig_type->per_cu.info_or_types_section = section;
4022               sig_type->per_cu.offset = offset;
4023               sig_type->per_cu.length = length;
4024             }
4025
4026           slot = htab_find_slot (types_htab,
4027                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4028                                  INSERT);
4029           gdb_assert (slot != NULL);
4030           if (*slot != NULL)
4031             {
4032               sect_offset dup_offset;
4033
4034               if (dwo_file)
4035                 {
4036                   const struct dwo_unit *dup_tu = *slot;
4037
4038                   dup_offset = dup_tu->offset;
4039                 }
4040               else
4041                 {
4042                   const struct signatured_type *dup_tu = *slot;
4043
4044                   dup_offset = dup_tu->per_cu.offset;
4045                 }
4046
4047               complaint (&symfile_complaints,
4048                          _("debug type entry at offset 0x%x is duplicate to the "
4049                            "entry at offset 0x%x, signature 0x%s"),
4050                          offset.sect_off, dup_offset.sect_off,
4051                          phex (signature, sizeof (signature)));
4052             }
4053           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4054
4055           if (dwarf2_read_debug)
4056             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4057                                 offset.sect_off,
4058                                 phex (signature, sizeof (signature)));
4059
4060           info_ptr += length;
4061         }
4062     }
4063
4064   return types_htab;
4065 }
4066
4067 /* Create the hash table of all entries in the .debug_types section,
4068    and initialize all_type_units.
4069    The result is zero if there is an error (e.g. missing .debug_types section),
4070    otherwise non-zero.  */
4071
4072 static int
4073 create_all_type_units (struct objfile *objfile)
4074 {
4075   htab_t types_htab;
4076   struct signatured_type **iter;
4077
4078   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4079   if (types_htab == NULL)
4080     {
4081       dwarf2_per_objfile->signatured_types = NULL;
4082       return 0;
4083     }
4084
4085   dwarf2_per_objfile->signatured_types = types_htab;
4086
4087   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4088   dwarf2_per_objfile->all_type_units
4089     = obstack_alloc (&objfile->objfile_obstack,
4090                      dwarf2_per_objfile->n_type_units
4091                      * sizeof (struct signatured_type *));
4092   iter = &dwarf2_per_objfile->all_type_units[0];
4093   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4094   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4095               == dwarf2_per_objfile->n_type_units);
4096
4097   return 1;
4098 }
4099
4100 /* Lookup a signature based type for DW_FORM_ref_sig8.
4101    Returns NULL if signature SIG is not present in the table.  */
4102
4103 static struct signatured_type *
4104 lookup_signatured_type (ULONGEST sig)
4105 {
4106   struct signatured_type find_entry, *entry;
4107
4108   if (dwarf2_per_objfile->signatured_types == NULL)
4109     {
4110       complaint (&symfile_complaints,
4111                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4112       return NULL;
4113     }
4114
4115   find_entry.signature = sig;
4116   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4117   return entry;
4118 }
4119 \f
4120 /* Low level DIE reading support.  */
4121
4122 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4123
4124 static void
4125 init_cu_die_reader (struct die_reader_specs *reader,
4126                     struct dwarf2_cu *cu,
4127                     struct dwarf2_section_info *section,
4128                     struct dwo_file *dwo_file)
4129 {
4130   gdb_assert (section->readin && section->buffer != NULL);
4131   reader->abfd = section->asection->owner;
4132   reader->cu = cu;
4133   reader->dwo_file = dwo_file;
4134   reader->die_section = section;
4135   reader->buffer = section->buffer;
4136   reader->buffer_end = section->buffer + section->size;
4137 }
4138
4139 /* Initialize a CU (or TU) and read its DIEs.
4140    If the CU defers to a DWO file, read the DWO file as well.
4141
4142    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4143    Otherwise the table specified in the comp unit header is read in and used.
4144    This is an optimization for when we already have the abbrev table.
4145
4146    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4147    Otherwise, a new CU is allocated with xmalloc.
4148
4149    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4150    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4151
4152    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4153    linker) then DIE_READER_FUNC will not get called.  */
4154
4155 static void
4156 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4157                          struct abbrev_table *abbrev_table,
4158                          int use_existing_cu, int keep,
4159                          die_reader_func_ftype *die_reader_func,
4160                          void *data)
4161 {
4162   struct objfile *objfile = dwarf2_per_objfile->objfile;
4163   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4164   bfd *abfd = section->asection->owner;
4165   struct dwarf2_cu *cu;
4166   gdb_byte *begin_info_ptr, *info_ptr;
4167   struct die_reader_specs reader;
4168   struct die_info *comp_unit_die;
4169   int has_children;
4170   struct attribute *attr;
4171   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4172   struct signatured_type *sig_type = NULL;
4173   struct dwarf2_section_info *abbrev_section;
4174   /* Non-zero if CU currently points to a DWO file and we need to
4175      reread it.  When this happens we need to reread the skeleton die
4176      before we can reread the DWO file.  */
4177   int rereading_dwo_cu = 0;
4178
4179   if (dwarf2_die_debug)
4180     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4181                         this_cu->is_debug_types ? "type" : "comp",
4182                         this_cu->offset.sect_off);
4183
4184   if (use_existing_cu)
4185     gdb_assert (keep);
4186
4187   cleanups = make_cleanup (null_cleanup, NULL);
4188
4189   /* This is cheap if the section is already read in.  */
4190   dwarf2_read_section (objfile, section);
4191
4192   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4193   abbrev_section = &dwarf2_per_objfile->abbrev;
4194
4195   if (use_existing_cu && this_cu->cu != NULL)
4196     {
4197       cu = this_cu->cu;
4198
4199       /* If this CU is from a DWO file we need to start over, we need to
4200          refetch the attributes from the skeleton CU.
4201          This could be optimized by retrieving those attributes from when we
4202          were here the first time: the previous comp_unit_die was stored in
4203          comp_unit_obstack.  But there's no data yet that we need this
4204          optimization.  */
4205       if (cu->dwo_unit != NULL)
4206         rereading_dwo_cu = 1;
4207     }
4208   else
4209     {
4210       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4211       gdb_assert (this_cu->cu == NULL);
4212
4213       cu = xmalloc (sizeof (*cu));
4214       init_one_comp_unit (cu, this_cu);
4215
4216       /* If an error occurs while loading, release our storage.  */
4217       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4218     }
4219
4220   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4221     {
4222       /* We already have the header, there's no need to read it in again.  */
4223       info_ptr += cu->header.first_die_offset.cu_off;
4224     }
4225   else
4226     {
4227       if (this_cu->is_debug_types)
4228         {
4229           ULONGEST signature;
4230           cu_offset type_offset_in_tu;
4231
4232           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4233                                                     abbrev_section, info_ptr,
4234                                                     &signature,
4235                                                     &type_offset_in_tu);
4236
4237           /* Since per_cu is the first member of struct signatured_type,
4238              we can go from a pointer to one to a pointer to the other.  */
4239           sig_type = (struct signatured_type *) this_cu;
4240           gdb_assert (sig_type->signature == signature);
4241           gdb_assert (sig_type->type_offset_in_tu.cu_off
4242                       == type_offset_in_tu.cu_off);
4243           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4244
4245           /* LENGTH has not been set yet for type units if we're
4246              using .gdb_index.  */
4247           this_cu->length = get_cu_length (&cu->header);
4248
4249           /* Establish the type offset that can be used to lookup the type.  */
4250           sig_type->type_offset_in_section.sect_off =
4251             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4252         }
4253       else
4254         {
4255           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4256                                                     abbrev_section,
4257                                                     info_ptr, 0);
4258
4259           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4260           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4261         }
4262     }
4263
4264   /* Skip dummy compilation units.  */
4265   if (info_ptr >= begin_info_ptr + this_cu->length
4266       || peek_abbrev_code (abfd, info_ptr) == 0)
4267     {
4268       do_cleanups (cleanups);
4269       return;
4270     }
4271
4272   /* If we don't have them yet, read the abbrevs for this compilation unit.
4273      And if we need to read them now, make sure they're freed when we're
4274      done.  Note that it's important that if the CU had an abbrev table
4275      on entry we don't free it when we're done: Somewhere up the call stack
4276      it may be in use.  */
4277   if (abbrev_table != NULL)
4278     {
4279       gdb_assert (cu->abbrev_table == NULL);
4280       gdb_assert (cu->header.abbrev_offset.sect_off
4281                   == abbrev_table->offset.sect_off);
4282       cu->abbrev_table = abbrev_table;
4283     }
4284   else if (cu->abbrev_table == NULL)
4285     {
4286       dwarf2_read_abbrevs (cu, abbrev_section);
4287       make_cleanup (dwarf2_free_abbrev_table, cu);
4288     }
4289   else if (rereading_dwo_cu)
4290     {
4291       dwarf2_free_abbrev_table (cu);
4292       dwarf2_read_abbrevs (cu, abbrev_section);
4293     }
4294
4295   /* Read the top level CU/TU die.  */
4296   init_cu_die_reader (&reader, cu, section, NULL);
4297   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4298
4299   /* If we have a DWO stub, process it and then read in the DWO file.
4300      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4301      a DWO CU, that this test will fail.  */
4302   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4303   if (attr)
4304     {
4305       char *dwo_name = DW_STRING (attr);
4306       const char *comp_dir_string;
4307       struct dwo_unit *dwo_unit;
4308       ULONGEST signature; /* Or dwo_id.  */
4309       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4310       int i,num_extra_attrs;
4311       struct dwarf2_section_info *dwo_abbrev_section;
4312
4313       if (has_children)
4314         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4315                  " has children (offset 0x%x) [in module %s]"),
4316                this_cu->offset.sect_off, bfd_get_filename (abfd));
4317
4318       /* These attributes aren't processed until later:
4319          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4320          However, the attribute is found in the stub which we won't have later.
4321          In order to not impose this complication on the rest of the code,
4322          we read them here and copy them to the DWO CU/TU die.  */
4323
4324       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4325          DWO file.  */
4326       stmt_list = NULL;
4327       if (! this_cu->is_debug_types)
4328         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4329       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4330       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4331       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4332       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4333
4334       /* There should be a DW_AT_addr_base attribute here (if needed).
4335          We need the value before we can process DW_FORM_GNU_addr_index.  */
4336       cu->addr_base = 0;
4337       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4338       if (attr)
4339         cu->addr_base = DW_UNSND (attr);
4340
4341       /* There should be a DW_AT_ranges_base attribute here (if needed).
4342          We need the value before we can process DW_AT_ranges.  */
4343       cu->ranges_base = 0;
4344       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4345       if (attr)
4346         cu->ranges_base = DW_UNSND (attr);
4347
4348       if (this_cu->is_debug_types)
4349         {
4350           gdb_assert (sig_type != NULL);
4351           signature = sig_type->signature;
4352         }
4353       else
4354         {
4355           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4356           if (! attr)
4357             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4358                    dwo_name);
4359           signature = DW_UNSND (attr);
4360         }
4361
4362       /* We may need the comp_dir in order to find the DWO file.  */
4363       comp_dir_string = NULL;
4364       if (comp_dir)
4365         comp_dir_string = DW_STRING (comp_dir);
4366
4367       if (this_cu->is_debug_types)
4368         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4369       else
4370         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4371                                          signature);
4372
4373       if (dwo_unit == NULL)
4374         {
4375           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4376                    " with ID %s [in module %s]"),
4377                  this_cu->offset.sect_off,
4378                  phex (signature, sizeof (signature)),
4379                  objfile->name);
4380         }
4381
4382       /* Set up for reading the DWO CU/TU.  */
4383       cu->dwo_unit = dwo_unit;
4384       section = dwo_unit->info_or_types_section;
4385       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4386       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4387       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4388
4389       if (this_cu->is_debug_types)
4390         {
4391           ULONGEST signature;
4392
4393           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4394                                                     dwo_abbrev_section,
4395                                                     info_ptr,
4396                                                     &signature, NULL);
4397           gdb_assert (sig_type->signature == signature);
4398           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4399           gdb_assert (dwo_unit->length == get_cu_length (&cu->header));
4400
4401           /* Establish the type offset that can be used to lookup the type.
4402              For DWO files, we don't know it until now.  */
4403           sig_type->type_offset_in_section.sect_off =
4404             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4405         }
4406       else
4407         {
4408           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4409                                                     dwo_abbrev_section,
4410                                                     info_ptr, 0);
4411           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4412           gdb_assert (dwo_unit->length == get_cu_length (&cu->header));
4413         }
4414
4415       /* Discard the original CU's abbrev table, and read the DWO's.  */
4416       if (abbrev_table == NULL)
4417         {
4418           dwarf2_free_abbrev_table (cu);
4419           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4420         }
4421       else
4422         {
4423           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4424           make_cleanup (dwarf2_free_abbrev_table, cu);
4425         }
4426
4427       /* Read in the die, but leave space to copy over the attributes
4428          from the stub.  This has the benefit of simplifying the rest of
4429          the code - all the real work is done here.  */
4430       num_extra_attrs = ((stmt_list != NULL)
4431                          + (low_pc != NULL)
4432                          + (high_pc != NULL)
4433                          + (ranges != NULL)
4434                          + (comp_dir != NULL));
4435       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4436                                   &has_children, num_extra_attrs);
4437
4438       /* Copy over the attributes from the stub to the DWO die.  */
4439       i = comp_unit_die->num_attrs;
4440       if (stmt_list != NULL)
4441         comp_unit_die->attrs[i++] = *stmt_list;
4442       if (low_pc != NULL)
4443         comp_unit_die->attrs[i++] = *low_pc;
4444       if (high_pc != NULL)
4445         comp_unit_die->attrs[i++] = *high_pc;
4446       if (ranges != NULL)
4447         comp_unit_die->attrs[i++] = *ranges;
4448       if (comp_dir != NULL)
4449         comp_unit_die->attrs[i++] = *comp_dir;
4450       comp_unit_die->num_attrs += num_extra_attrs;
4451
4452       /* Skip dummy compilation units.  */
4453       if (info_ptr >= begin_info_ptr + dwo_unit->length
4454           || peek_abbrev_code (abfd, info_ptr) == 0)
4455         {
4456           do_cleanups (cleanups);
4457           return;
4458         }
4459     }
4460
4461   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4462
4463   if (free_cu_cleanup != NULL)
4464     {
4465       if (keep)
4466         {
4467           /* We've successfully allocated this compilation unit.  Let our
4468              caller clean it up when finished with it.  */
4469           discard_cleanups (free_cu_cleanup);
4470
4471           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4472              So we have to manually free the abbrev table.  */
4473           dwarf2_free_abbrev_table (cu);
4474
4475           /* Link this CU into read_in_chain.  */
4476           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4477           dwarf2_per_objfile->read_in_chain = this_cu;
4478         }
4479       else
4480         do_cleanups (free_cu_cleanup);
4481     }
4482
4483   do_cleanups (cleanups);
4484 }
4485
4486 /* Read CU/TU THIS_CU in section SECTION,
4487    but do not follow DW_AT_GNU_dwo_name if present.
4488    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed to
4489    have already done the lookup to find the DWO file).
4490
4491    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4492    THIS_CU->is_debug_types, but nothing else.
4493
4494    We fill in THIS_CU->length.
4495
4496    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4497    linker) then DIE_READER_FUNC will not get called.
4498
4499    THIS_CU->cu is always freed when done.
4500    This is done in order to not leave THIS_CU->cu in a state where we have
4501    to care whether it refers to the "main" CU or the DWO CU.  */
4502
4503 static void
4504 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4505                                    struct dwarf2_section_info *abbrev_section,
4506                                    struct dwo_file *dwo_file,
4507                                    die_reader_func_ftype *die_reader_func,
4508                                    void *data)
4509 {
4510   struct objfile *objfile = dwarf2_per_objfile->objfile;
4511   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4512   bfd *abfd = section->asection->owner;
4513   struct dwarf2_cu cu;
4514   gdb_byte *begin_info_ptr, *info_ptr;
4515   struct die_reader_specs reader;
4516   struct cleanup *cleanups;
4517   struct die_info *comp_unit_die;
4518   int has_children;
4519
4520   if (dwarf2_die_debug)
4521     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4522                         this_cu->is_debug_types ? "type" : "comp",
4523                         this_cu->offset.sect_off);
4524
4525   gdb_assert (this_cu->cu == NULL);
4526
4527   /* This is cheap if the section is already read in.  */
4528   dwarf2_read_section (objfile, section);
4529
4530   init_one_comp_unit (&cu, this_cu);
4531
4532   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4533
4534   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4535   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4536                                             abbrev_section, info_ptr,
4537                                             this_cu->is_debug_types);
4538
4539   this_cu->length = get_cu_length (&cu.header);
4540
4541   /* Skip dummy compilation units.  */
4542   if (info_ptr >= begin_info_ptr + this_cu->length
4543       || peek_abbrev_code (abfd, info_ptr) == 0)
4544     {
4545       do_cleanups (cleanups);
4546       return;
4547     }
4548
4549   dwarf2_read_abbrevs (&cu, abbrev_section);
4550   make_cleanup (dwarf2_free_abbrev_table, &cu);
4551
4552   init_cu_die_reader (&reader, &cu, section, dwo_file);
4553   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4554
4555   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4556
4557   do_cleanups (cleanups);
4558 }
4559
4560 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4561    does not lookup the specified DWO file.
4562    This cannot be used to read DWO files.
4563
4564    THIS_CU->cu is always freed when done.
4565    This is done in order to not leave THIS_CU->cu in a state where we have
4566    to care whether it refers to the "main" CU or the DWO CU.
4567    We can revisit this if the data shows there's a performance issue.  */
4568
4569 static void
4570 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4571                                 die_reader_func_ftype *die_reader_func,
4572                                 void *data)
4573 {
4574   init_cutu_and_read_dies_no_follow (this_cu,
4575                                      &dwarf2_per_objfile->abbrev,
4576                                      NULL,
4577                                      die_reader_func, data);
4578 }
4579
4580 /* Create a psymtab named NAME and assign it to PER_CU.
4581
4582    The caller must fill in the following details:
4583    dirname, textlow, texthigh.  */
4584
4585 static struct partial_symtab *
4586 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4587 {
4588   struct objfile *objfile = per_cu->objfile;
4589   struct partial_symtab *pst;
4590
4591   pst = start_psymtab_common (objfile, objfile->section_offsets,
4592                               name, 0,
4593                               objfile->global_psymbols.next,
4594                               objfile->static_psymbols.next);
4595
4596   pst->psymtabs_addrmap_supported = 1;
4597
4598   /* This is the glue that links PST into GDB's symbol API.  */
4599   pst->read_symtab_private = per_cu;
4600   pst->read_symtab = dwarf2_psymtab_to_symtab;
4601   per_cu->v.psymtab = pst;
4602
4603   return pst;
4604 }
4605
4606 /* die_reader_func for process_psymtab_comp_unit.  */
4607
4608 static void
4609 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4610                                   gdb_byte *info_ptr,
4611                                   struct die_info *comp_unit_die,
4612                                   int has_children,
4613                                   void *data)
4614 {
4615   struct dwarf2_cu *cu = reader->cu;
4616   struct objfile *objfile = cu->objfile;
4617   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4618   struct attribute *attr;
4619   CORE_ADDR baseaddr;
4620   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4621   struct partial_symtab *pst;
4622   int has_pc_info;
4623   const char *filename;
4624   int *want_partial_unit_ptr = data;
4625
4626   if (comp_unit_die->tag == DW_TAG_partial_unit
4627       && (want_partial_unit_ptr == NULL
4628           || !*want_partial_unit_ptr))
4629     return;
4630
4631   gdb_assert (! per_cu->is_debug_types);
4632
4633   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4634
4635   cu->list_in_scope = &file_symbols;
4636
4637   /* Allocate a new partial symbol table structure.  */
4638   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4639   if (attr == NULL || !DW_STRING (attr))
4640     filename = "";
4641   else
4642     filename = DW_STRING (attr);
4643
4644   pst = create_partial_symtab (per_cu, filename);
4645
4646   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4647   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4648   if (attr != NULL)
4649     pst->dirname = DW_STRING (attr);
4650
4651   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4652
4653   dwarf2_find_base_address (comp_unit_die, cu);
4654
4655   /* Possibly set the default values of LOWPC and HIGHPC from
4656      `DW_AT_ranges'.  */
4657   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4658                                       &best_highpc, cu, pst);
4659   if (has_pc_info == 1 && best_lowpc < best_highpc)
4660     /* Store the contiguous range if it is not empty; it can be empty for
4661        CUs with no code.  */
4662     addrmap_set_empty (objfile->psymtabs_addrmap,
4663                        best_lowpc + baseaddr,
4664                        best_highpc + baseaddr - 1, pst);
4665
4666   /* Check if comp unit has_children.
4667      If so, read the rest of the partial symbols from this comp unit.
4668      If not, there's no more debug_info for this comp unit.  */
4669   if (has_children)
4670     {
4671       struct partial_die_info *first_die;
4672       CORE_ADDR lowpc, highpc;
4673
4674       lowpc = ((CORE_ADDR) -1);
4675       highpc = ((CORE_ADDR) 0);
4676
4677       first_die = load_partial_dies (reader, info_ptr, 1);
4678
4679       scan_partial_symbols (first_die, &lowpc, &highpc,
4680                             ! has_pc_info, cu);
4681
4682       /* If we didn't find a lowpc, set it to highpc to avoid
4683          complaints from `maint check'.  */
4684       if (lowpc == ((CORE_ADDR) -1))
4685         lowpc = highpc;
4686
4687       /* If the compilation unit didn't have an explicit address range,
4688          then use the information extracted from its child dies.  */
4689       if (! has_pc_info)
4690         {
4691           best_lowpc = lowpc;
4692           best_highpc = highpc;
4693         }
4694     }
4695   pst->textlow = best_lowpc + baseaddr;
4696   pst->texthigh = best_highpc + baseaddr;
4697
4698   pst->n_global_syms = objfile->global_psymbols.next -
4699     (objfile->global_psymbols.list + pst->globals_offset);
4700   pst->n_static_syms = objfile->static_psymbols.next -
4701     (objfile->static_psymbols.list + pst->statics_offset);
4702   sort_pst_symbols (pst);
4703
4704   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs))
4705     {
4706       int i;
4707       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs);
4708       struct dwarf2_per_cu_data *iter;
4709
4710       /* Fill in 'dependencies' here; we fill in 'users' in a
4711          post-pass.  */
4712       pst->number_of_dependencies = len;
4713       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4714                                          len * sizeof (struct symtab *));
4715       for (i = 0;
4716            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs,
4717                         i, iter);
4718            ++i)
4719         pst->dependencies[i] = iter->v.psymtab;
4720
4721       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs);
4722     }
4723
4724   /* Get the list of files included in the current compilation unit,
4725      and build a psymtab for each of them.  */
4726   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4727
4728   if (dwarf2_read_debug)
4729     {
4730       struct gdbarch *gdbarch = get_objfile_arch (objfile);
4731
4732       fprintf_unfiltered (gdb_stdlog,
4733                           "Psymtab for %s unit @0x%x: 0x%s - 0x%s"
4734                           ", %d global, %d static syms\n",
4735                           per_cu->is_debug_types ? "type" : "comp",
4736                           per_cu->offset.sect_off,
4737                           paddress (gdbarch, pst->textlow),
4738                           paddress (gdbarch, pst->texthigh),
4739                           pst->n_global_syms, pst->n_static_syms);
4740     }
4741 }
4742
4743 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4744    Process compilation unit THIS_CU for a psymtab.  */
4745
4746 static void
4747 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
4748                            int want_partial_unit)
4749 {
4750   /* If this compilation unit was already read in, free the
4751      cached copy in order to read it in again.  This is
4752      necessary because we skipped some symbols when we first
4753      read in the compilation unit (see load_partial_dies).
4754      This problem could be avoided, but the benefit is unclear.  */
4755   if (this_cu->cu != NULL)
4756     free_one_cached_comp_unit (this_cu);
4757
4758   gdb_assert (! this_cu->is_debug_types);
4759   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
4760                            process_psymtab_comp_unit_reader,
4761                            &want_partial_unit);
4762
4763   /* Age out any secondary CUs.  */
4764   age_cached_comp_units ();
4765 }
4766
4767 static hashval_t
4768 hash_type_unit_group (const void *item)
4769 {
4770   const struct type_unit_group *tu_group = item;
4771
4772   return hash_stmt_list_entry (&tu_group->hash);
4773 }
4774
4775 static int
4776 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
4777 {
4778   const struct type_unit_group *lhs = item_lhs;
4779   const struct type_unit_group *rhs = item_rhs;
4780
4781   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
4782 }
4783
4784 /* Allocate a hash table for type unit groups.  */
4785
4786 static htab_t
4787 allocate_type_unit_groups_table (void)
4788 {
4789   return htab_create_alloc_ex (3,
4790                                hash_type_unit_group,
4791                                eq_type_unit_group,
4792                                NULL,
4793                                &dwarf2_per_objfile->objfile->objfile_obstack,
4794                                hashtab_obstack_allocate,
4795                                dummy_obstack_deallocate);
4796 }
4797
4798 /* Type units that don't have DW_AT_stmt_list are grouped into their own
4799    partial symtabs.  We combine several TUs per psymtab to not let the size
4800    of any one psymtab grow too big.  */
4801 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
4802 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
4803
4804 /* Helper routine for get_type_unit_group.
4805    Create the type_unit_group object used to hold one or more TUs.  */
4806
4807 static struct type_unit_group *
4808 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
4809 {
4810   struct objfile *objfile = dwarf2_per_objfile->objfile;
4811   struct dwarf2_per_cu_data *per_cu;
4812   struct type_unit_group *tu_group;
4813
4814   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4815                              struct type_unit_group);
4816   per_cu = &tu_group->per_cu;
4817   per_cu->objfile = objfile;
4818   per_cu->is_debug_types = 1;
4819   per_cu->s.type_unit_group = tu_group;
4820
4821   if (dwarf2_per_objfile->using_index)
4822     {
4823       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4824                                         struct dwarf2_per_cu_quick_data);
4825       tu_group->t.first_tu = cu->per_cu;
4826     }
4827   else
4828     {
4829       unsigned int line_offset = line_offset_struct.sect_off;
4830       struct partial_symtab *pst;
4831       char *name;
4832
4833       /* Give the symtab a useful name for debug purposes.  */
4834       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
4835         name = xstrprintf ("<type_units_%d>",
4836                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
4837       else
4838         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
4839
4840       pst = create_partial_symtab (per_cu, name);
4841       pst->anonymous = 1;
4842
4843       xfree (name);
4844     }
4845
4846   tu_group->hash.dwo_unit = cu->dwo_unit;
4847   tu_group->hash.line_offset = line_offset_struct;
4848
4849   return tu_group;
4850 }
4851
4852 /* Look up the type_unit_group for type unit CU, and create it if necessary.
4853    STMT_LIST is a DW_AT_stmt_list attribute.  */
4854
4855 static struct type_unit_group *
4856 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
4857 {
4858   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
4859   struct type_unit_group *tu_group;
4860   void **slot;
4861   unsigned int line_offset;
4862   struct type_unit_group type_unit_group_for_lookup;
4863
4864   if (dwarf2_per_objfile->type_unit_groups == NULL)
4865     {
4866       dwarf2_per_objfile->type_unit_groups =
4867         allocate_type_unit_groups_table ();
4868     }
4869
4870   /* Do we need to create a new group, or can we use an existing one?  */
4871
4872   if (stmt_list)
4873     {
4874       line_offset = DW_UNSND (stmt_list);
4875       ++tu_stats->nr_symtab_sharers;
4876     }
4877   else
4878     {
4879       /* Ugh, no stmt_list.  Rare, but we have to handle it.
4880          We can do various things here like create one group per TU or
4881          spread them over multiple groups to split up the expansion work.
4882          To avoid worst case scenarios (too many groups or too large groups)
4883          we, umm, group them in bunches.  */
4884       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
4885                      | (tu_stats->nr_stmt_less_type_units
4886                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
4887       ++tu_stats->nr_stmt_less_type_units;
4888     }
4889
4890   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
4891   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
4892   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
4893                          &type_unit_group_for_lookup, INSERT);
4894   if (*slot != NULL)
4895     {
4896       tu_group = *slot;
4897       gdb_assert (tu_group != NULL);
4898     }
4899   else
4900     {
4901       sect_offset line_offset_struct;
4902
4903       line_offset_struct.sect_off = line_offset;
4904       tu_group = create_type_unit_group (cu, line_offset_struct);
4905       *slot = tu_group;
4906       ++tu_stats->nr_symtabs;
4907     }
4908
4909   return tu_group;
4910 }
4911
4912 /* Struct used to sort TUs by their abbreviation table offset.  */
4913
4914 struct tu_abbrev_offset
4915 {
4916   struct signatured_type *sig_type;
4917   sect_offset abbrev_offset;
4918 };
4919
4920 /* Helper routine for build_type_unit_groups, passed to qsort.  */
4921
4922 static int
4923 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
4924 {
4925   const struct tu_abbrev_offset * const *a = ap;
4926   const struct tu_abbrev_offset * const *b = bp;
4927   unsigned int aoff = (*a)->abbrev_offset.sect_off;
4928   unsigned int boff = (*b)->abbrev_offset.sect_off;
4929
4930   return (aoff > boff) - (aoff < boff);
4931 }
4932
4933 /* A helper function to add a type_unit_group to a table.  */
4934
4935 static int
4936 add_type_unit_group_to_table (void **slot, void *datum)
4937 {
4938   struct type_unit_group *tu_group = *slot;
4939   struct type_unit_group ***datap = datum;
4940
4941   **datap = tu_group;
4942   ++*datap;
4943
4944   return 1;
4945 }
4946
4947 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
4948    each one passing FUNC,DATA.
4949
4950    The efficiency is because we sort TUs by the abbrev table they use and
4951    only read each abbrev table once.  In one program there are 200K TUs
4952    sharing 8K abbrev tables.
4953
4954    The main purpose of this function is to support building the
4955    dwarf2_per_objfile->type_unit_groups table.
4956    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
4957    can collapse the search space by grouping them by stmt_list.
4958    The savings can be significant, in the same program from above the 200K TUs
4959    share 8K stmt_list tables.
4960
4961    FUNC is expected to call get_type_unit_group, which will create the
4962    struct type_unit_group if necessary and add it to
4963    dwarf2_per_objfile->type_unit_groups.  */
4964
4965 static void
4966 build_type_unit_groups (die_reader_func_ftype *func, void *data)
4967 {
4968   struct objfile *objfile = dwarf2_per_objfile->objfile;
4969   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
4970   struct cleanup *cleanups;
4971   struct abbrev_table *abbrev_table;
4972   sect_offset abbrev_offset;
4973   struct tu_abbrev_offset *sorted_by_abbrev;
4974   struct type_unit_group **iter;
4975   int i;
4976
4977   /* It's up to the caller to not call us multiple times.  */
4978   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
4979
4980   if (dwarf2_per_objfile->n_type_units == 0)
4981     return;
4982
4983   /* TUs typically share abbrev tables, and there can be way more TUs than
4984      abbrev tables.  Sort by abbrev table to reduce the number of times we
4985      read each abbrev table in.
4986      Alternatives are to punt or to maintain a cache of abbrev tables.
4987      This is simpler and efficient enough for now.
4988
4989      Later we group TUs by their DW_AT_stmt_list value (as this defines the
4990      symtab to use).  Typically TUs with the same abbrev offset have the same
4991      stmt_list value too so in practice this should work well.
4992
4993      The basic algorithm here is:
4994
4995       sort TUs by abbrev table
4996       for each TU with same abbrev table:
4997         read abbrev table if first user
4998         read TU top level DIE
4999           [IWBN if DWO skeletons had DW_AT_stmt_list]
5000         call FUNC  */
5001
5002   if (dwarf2_read_debug)
5003     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5004
5005   /* Sort in a separate table to maintain the order of all_type_units
5006      for .gdb_index: TU indices directly index all_type_units.  */
5007   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5008                               dwarf2_per_objfile->n_type_units);
5009   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5010     {
5011       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5012
5013       sorted_by_abbrev[i].sig_type = sig_type;
5014       sorted_by_abbrev[i].abbrev_offset =
5015         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
5016                             sig_type->per_cu.offset);
5017     }
5018   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5019   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5020          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5021
5022   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5023      called any number of times, so we don't reset tu_stats here.  */
5024
5025   abbrev_offset.sect_off = ~(unsigned) 0;
5026   abbrev_table = NULL;
5027   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5028
5029   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5030     {
5031       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5032
5033       /* Switch to the next abbrev table if necessary.  */
5034       if (abbrev_table == NULL
5035           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5036         {
5037           if (abbrev_table != NULL)
5038             {
5039               abbrev_table_free (abbrev_table);
5040               /* Reset to NULL in case abbrev_table_read_table throws
5041                  an error: abbrev_table_free_cleanup will get called.  */
5042               abbrev_table = NULL;
5043             }
5044           abbrev_offset = tu->abbrev_offset;
5045           abbrev_table =
5046             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5047                                      abbrev_offset);
5048           ++tu_stats->nr_uniq_abbrev_tables;
5049         }
5050
5051       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5052                                func, data);
5053     }
5054
5055   /* Create a vector of pointers to primary type units to make it easy to
5056      iterate over them and CUs.  See dw2_get_primary_cu.  */
5057   dwarf2_per_objfile->n_type_unit_groups =
5058     htab_elements (dwarf2_per_objfile->type_unit_groups);
5059   dwarf2_per_objfile->all_type_unit_groups =
5060     obstack_alloc (&objfile->objfile_obstack,
5061                    dwarf2_per_objfile->n_type_unit_groups
5062                    * sizeof (struct type_unit_group *));
5063   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5064   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5065                           add_type_unit_group_to_table, &iter);
5066   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5067               == dwarf2_per_objfile->n_type_unit_groups);
5068
5069   do_cleanups (cleanups);
5070
5071   if (dwarf2_read_debug)
5072     {
5073       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5074       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5075                           dwarf2_per_objfile->n_type_units);
5076       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5077                           tu_stats->nr_uniq_abbrev_tables);
5078       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5079                           tu_stats->nr_symtabs);
5080       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5081                           tu_stats->nr_symtab_sharers);
5082       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5083                           tu_stats->nr_stmt_less_type_units);
5084     }
5085 }
5086
5087 /* Reader function for build_type_psymtabs.  */
5088
5089 static void
5090 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5091                             gdb_byte *info_ptr,
5092                             struct die_info *type_unit_die,
5093                             int has_children,
5094                             void *data)
5095 {
5096   struct objfile *objfile = dwarf2_per_objfile->objfile;
5097   struct dwarf2_cu *cu = reader->cu;
5098   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5099   struct type_unit_group *tu_group;
5100   struct attribute *attr;
5101   struct partial_die_info *first_die;
5102   CORE_ADDR lowpc, highpc;
5103   struct partial_symtab *pst;
5104
5105   gdb_assert (data == NULL);
5106
5107   if (! has_children)
5108     return;
5109
5110   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5111   tu_group = get_type_unit_group (cu, attr);
5112
5113   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5114
5115   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5116   cu->list_in_scope = &file_symbols;
5117   pst = create_partial_symtab (per_cu, "");
5118   pst->anonymous = 1;
5119
5120   first_die = load_partial_dies (reader, info_ptr, 1);
5121
5122   lowpc = (CORE_ADDR) -1;
5123   highpc = (CORE_ADDR) 0;
5124   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5125
5126   pst->n_global_syms = objfile->global_psymbols.next -
5127     (objfile->global_psymbols.list + pst->globals_offset);
5128   pst->n_static_syms = objfile->static_psymbols.next -
5129     (objfile->static_psymbols.list + pst->statics_offset);
5130   sort_pst_symbols (pst);
5131 }
5132
5133 /* Traversal function for build_type_psymtabs.  */
5134
5135 static int
5136 build_type_psymtab_dependencies (void **slot, void *info)
5137 {
5138   struct objfile *objfile = dwarf2_per_objfile->objfile;
5139   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5140   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5141   struct partial_symtab *pst = per_cu->v.psymtab;
5142   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5143   struct dwarf2_per_cu_data *iter;
5144   int i;
5145
5146   gdb_assert (len > 0);
5147
5148   pst->number_of_dependencies = len;
5149   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5150                                      len * sizeof (struct psymtab *));
5151   for (i = 0;
5152        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5153        ++i)
5154     {
5155       pst->dependencies[i] = iter->v.psymtab;
5156       iter->s.type_unit_group = tu_group;
5157     }
5158
5159   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5160
5161   return 1;
5162 }
5163
5164 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5165    Build partial symbol tables for the .debug_types comp-units.  */
5166
5167 static void
5168 build_type_psymtabs (struct objfile *objfile)
5169 {
5170   if (! create_all_type_units (objfile))
5171     return;
5172
5173   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5174
5175   /* Now that all TUs have been processed we can fill in the dependencies.  */
5176   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5177                           build_type_psymtab_dependencies, NULL);
5178 }
5179
5180 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5181
5182 static void
5183 psymtabs_addrmap_cleanup (void *o)
5184 {
5185   struct objfile *objfile = o;
5186
5187   objfile->psymtabs_addrmap = NULL;
5188 }
5189
5190 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5191
5192 static void
5193 set_partial_user (struct objfile *objfile)
5194 {
5195   int i;
5196
5197   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5198     {
5199       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5200       struct partial_symtab *pst = per_cu->v.psymtab;
5201       int j;
5202
5203       for (j = 0; j < pst->number_of_dependencies; ++j)
5204         {
5205           /* Set the 'user' field only if it is not already set.  */
5206           if (pst->dependencies[j]->user == NULL)
5207             pst->dependencies[j]->user = pst;
5208         }
5209     }
5210 }
5211
5212 /* Build the partial symbol table by doing a quick pass through the
5213    .debug_info and .debug_abbrev sections.  */
5214
5215 static void
5216 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5217 {
5218   struct cleanup *back_to, *addrmap_cleanup;
5219   struct obstack temp_obstack;
5220   int i;
5221
5222   if (dwarf2_read_debug)
5223     {
5224       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5225                           objfile->name);
5226     }
5227
5228   dwarf2_per_objfile->reading_partial_symbols = 1;
5229
5230   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5231
5232   /* Any cached compilation units will be linked by the per-objfile
5233      read_in_chain.  Make sure to free them when we're done.  */
5234   back_to = make_cleanup (free_cached_comp_units, NULL);
5235
5236   build_type_psymtabs (objfile);
5237
5238   create_all_comp_units (objfile);
5239
5240   /* Create a temporary address map on a temporary obstack.  We later
5241      copy this to the final obstack.  */
5242   obstack_init (&temp_obstack);
5243   make_cleanup_obstack_free (&temp_obstack);
5244   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5245   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5246
5247   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5248     {
5249       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5250
5251       process_psymtab_comp_unit (per_cu, 0);
5252     }
5253
5254   set_partial_user (objfile);
5255
5256   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5257                                                     &objfile->objfile_obstack);
5258   discard_cleanups (addrmap_cleanup);
5259
5260   do_cleanups (back_to);
5261
5262   if (dwarf2_read_debug)
5263     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5264                         objfile->name);
5265 }
5266
5267 /* die_reader_func for load_partial_comp_unit.  */
5268
5269 static void
5270 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5271                                gdb_byte *info_ptr,
5272                                struct die_info *comp_unit_die,
5273                                int has_children,
5274                                void *data)
5275 {
5276   struct dwarf2_cu *cu = reader->cu;
5277
5278   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5279
5280   /* Check if comp unit has_children.
5281      If so, read the rest of the partial symbols from this comp unit.
5282      If not, there's no more debug_info for this comp unit.  */
5283   if (has_children)
5284     load_partial_dies (reader, info_ptr, 0);
5285 }
5286
5287 /* Load the partial DIEs for a secondary CU into memory.
5288    This is also used when rereading a primary CU with load_all_dies.  */
5289
5290 static void
5291 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5292 {
5293   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5294                            load_partial_comp_unit_reader, NULL);
5295 }
5296
5297 /* Create a list of all compilation units in OBJFILE.
5298    This is only done for -readnow and building partial symtabs.  */
5299
5300 static void
5301 create_all_comp_units (struct objfile *objfile)
5302 {
5303   int n_allocated;
5304   int n_comp_units;
5305   struct dwarf2_per_cu_data **all_comp_units;
5306   gdb_byte *info_ptr;
5307
5308   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5309   info_ptr = dwarf2_per_objfile->info.buffer;
5310
5311   n_comp_units = 0;
5312   n_allocated = 10;
5313   all_comp_units = xmalloc (n_allocated
5314                             * sizeof (struct dwarf2_per_cu_data *));
5315
5316   while (info_ptr < dwarf2_per_objfile->info.buffer
5317          + dwarf2_per_objfile->info.size)
5318     {
5319       unsigned int length, initial_length_size;
5320       struct dwarf2_per_cu_data *this_cu;
5321       sect_offset offset;
5322
5323       offset.sect_off = info_ptr - dwarf2_per_objfile->info.buffer;
5324
5325       /* Read just enough information to find out where the next
5326          compilation unit is.  */
5327       length = read_initial_length (objfile->obfd, info_ptr,
5328                                     &initial_length_size);
5329
5330       /* Save the compilation unit for later lookup.  */
5331       this_cu = obstack_alloc (&objfile->objfile_obstack,
5332                                sizeof (struct dwarf2_per_cu_data));
5333       memset (this_cu, 0, sizeof (*this_cu));
5334       this_cu->offset = offset;
5335       this_cu->length = length + initial_length_size;
5336       this_cu->objfile = objfile;
5337       this_cu->info_or_types_section = &dwarf2_per_objfile->info;
5338
5339       if (n_comp_units == n_allocated)
5340         {
5341           n_allocated *= 2;
5342           all_comp_units = xrealloc (all_comp_units,
5343                                      n_allocated
5344                                      * sizeof (struct dwarf2_per_cu_data *));
5345         }
5346       all_comp_units[n_comp_units++] = this_cu;
5347
5348       info_ptr = info_ptr + this_cu->length;
5349     }
5350
5351   dwarf2_per_objfile->all_comp_units
5352     = obstack_alloc (&objfile->objfile_obstack,
5353                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5354   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5355           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5356   xfree (all_comp_units);
5357   dwarf2_per_objfile->n_comp_units = n_comp_units;
5358 }
5359
5360 /* Process all loaded DIEs for compilation unit CU, starting at
5361    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5362    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5363    DW_AT_ranges).  If NEED_PC is set, then this function will set
5364    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5365    and record the covered ranges in the addrmap.  */
5366
5367 static void
5368 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5369                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5370 {
5371   struct partial_die_info *pdi;
5372
5373   /* Now, march along the PDI's, descending into ones which have
5374      interesting children but skipping the children of the other ones,
5375      until we reach the end of the compilation unit.  */
5376
5377   pdi = first_die;
5378
5379   while (pdi != NULL)
5380     {
5381       fixup_partial_die (pdi, cu);
5382
5383       /* Anonymous namespaces or modules have no name but have interesting
5384          children, so we need to look at them.  Ditto for anonymous
5385          enums.  */
5386
5387       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5388           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5389           || pdi->tag == DW_TAG_imported_unit)
5390         {
5391           switch (pdi->tag)
5392             {
5393             case DW_TAG_subprogram:
5394               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5395               break;
5396             case DW_TAG_constant:
5397             case DW_TAG_variable:
5398             case DW_TAG_typedef:
5399             case DW_TAG_union_type:
5400               if (!pdi->is_declaration)
5401                 {
5402                   add_partial_symbol (pdi, cu);
5403                 }
5404               break;
5405             case DW_TAG_class_type:
5406             case DW_TAG_interface_type:
5407             case DW_TAG_structure_type:
5408               if (!pdi->is_declaration)
5409                 {
5410                   add_partial_symbol (pdi, cu);
5411                 }
5412               break;
5413             case DW_TAG_enumeration_type:
5414               if (!pdi->is_declaration)
5415                 add_partial_enumeration (pdi, cu);
5416               break;
5417             case DW_TAG_base_type:
5418             case DW_TAG_subrange_type:
5419               /* File scope base type definitions are added to the partial
5420                  symbol table.  */
5421               add_partial_symbol (pdi, cu);
5422               break;
5423             case DW_TAG_namespace:
5424               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5425               break;
5426             case DW_TAG_module:
5427               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5428               break;
5429             case DW_TAG_imported_unit:
5430               {
5431                 struct dwarf2_per_cu_data *per_cu;
5432
5433                 /* For now we don't handle imported units in type units.  */
5434                 if (cu->per_cu->is_debug_types)
5435                   {
5436                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5437                              " supported in type units [in module %s]"),
5438                            cu->objfile->name);
5439                   }
5440
5441                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5442                                                            cu->objfile);
5443
5444                 /* Go read the partial unit, if needed.  */
5445                 if (per_cu->v.psymtab == NULL)
5446                   process_psymtab_comp_unit (per_cu, 1);
5447
5448                 VEC_safe_push (dwarf2_per_cu_ptr,
5449                                cu->per_cu->s.imported_symtabs, per_cu);
5450               }
5451               break;
5452             default:
5453               break;
5454             }
5455         }
5456
5457       /* If the die has a sibling, skip to the sibling.  */
5458
5459       pdi = pdi->die_sibling;
5460     }
5461 }
5462
5463 /* Functions used to compute the fully scoped name of a partial DIE.
5464
5465    Normally, this is simple.  For C++, the parent DIE's fully scoped
5466    name is concatenated with "::" and the partial DIE's name.  For
5467    Java, the same thing occurs except that "." is used instead of "::".
5468    Enumerators are an exception; they use the scope of their parent
5469    enumeration type, i.e. the name of the enumeration type is not
5470    prepended to the enumerator.
5471
5472    There are two complexities.  One is DW_AT_specification; in this
5473    case "parent" means the parent of the target of the specification,
5474    instead of the direct parent of the DIE.  The other is compilers
5475    which do not emit DW_TAG_namespace; in this case we try to guess
5476    the fully qualified name of structure types from their members'
5477    linkage names.  This must be done using the DIE's children rather
5478    than the children of any DW_AT_specification target.  We only need
5479    to do this for structures at the top level, i.e. if the target of
5480    any DW_AT_specification (if any; otherwise the DIE itself) does not
5481    have a parent.  */
5482
5483 /* Compute the scope prefix associated with PDI's parent, in
5484    compilation unit CU.  The result will be allocated on CU's
5485    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5486    field.  NULL is returned if no prefix is necessary.  */
5487 static char *
5488 partial_die_parent_scope (struct partial_die_info *pdi,
5489                           struct dwarf2_cu *cu)
5490 {
5491   char *grandparent_scope;
5492   struct partial_die_info *parent, *real_pdi;
5493
5494   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5495      then this means the parent of the specification DIE.  */
5496
5497   real_pdi = pdi;
5498   while (real_pdi->has_specification)
5499     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
5500
5501   parent = real_pdi->die_parent;
5502   if (parent == NULL)
5503     return NULL;
5504
5505   if (parent->scope_set)
5506     return parent->scope;
5507
5508   fixup_partial_die (parent, cu);
5509
5510   grandparent_scope = partial_die_parent_scope (parent, cu);
5511
5512   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5513      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5514      Work around this problem here.  */
5515   if (cu->language == language_cplus
5516       && parent->tag == DW_TAG_namespace
5517       && strcmp (parent->name, "::") == 0
5518       && grandparent_scope == NULL)
5519     {
5520       parent->scope = NULL;
5521       parent->scope_set = 1;
5522       return NULL;
5523     }
5524
5525   if (pdi->tag == DW_TAG_enumerator)
5526     /* Enumerators should not get the name of the enumeration as a prefix.  */
5527     parent->scope = grandparent_scope;
5528   else if (parent->tag == DW_TAG_namespace
5529       || parent->tag == DW_TAG_module
5530       || parent->tag == DW_TAG_structure_type
5531       || parent->tag == DW_TAG_class_type
5532       || parent->tag == DW_TAG_interface_type
5533       || parent->tag == DW_TAG_union_type
5534       || parent->tag == DW_TAG_enumeration_type)
5535     {
5536       if (grandparent_scope == NULL)
5537         parent->scope = parent->name;
5538       else
5539         parent->scope = typename_concat (&cu->comp_unit_obstack,
5540                                          grandparent_scope,
5541                                          parent->name, 0, cu);
5542     }
5543   else
5544     {
5545       /* FIXME drow/2004-04-01: What should we be doing with
5546          function-local names?  For partial symbols, we should probably be
5547          ignoring them.  */
5548       complaint (&symfile_complaints,
5549                  _("unhandled containing DIE tag %d for DIE at %d"),
5550                  parent->tag, pdi->offset.sect_off);
5551       parent->scope = grandparent_scope;
5552     }
5553
5554   parent->scope_set = 1;
5555   return parent->scope;
5556 }
5557
5558 /* Return the fully scoped name associated with PDI, from compilation unit
5559    CU.  The result will be allocated with malloc.  */
5560
5561 static char *
5562 partial_die_full_name (struct partial_die_info *pdi,
5563                        struct dwarf2_cu *cu)
5564 {
5565   char *parent_scope;
5566
5567   /* If this is a template instantiation, we can not work out the
5568      template arguments from partial DIEs.  So, unfortunately, we have
5569      to go through the full DIEs.  At least any work we do building
5570      types here will be reused if full symbols are loaded later.  */
5571   if (pdi->has_template_arguments)
5572     {
5573       fixup_partial_die (pdi, cu);
5574
5575       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5576         {
5577           struct die_info *die;
5578           struct attribute attr;
5579           struct dwarf2_cu *ref_cu = cu;
5580
5581           /* DW_FORM_ref_addr is using section offset.  */
5582           attr.name = 0;
5583           attr.form = DW_FORM_ref_addr;
5584           attr.u.unsnd = pdi->offset.sect_off;
5585           die = follow_die_ref (NULL, &attr, &ref_cu);
5586
5587           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5588         }
5589     }
5590
5591   parent_scope = partial_die_parent_scope (pdi, cu);
5592   if (parent_scope == NULL)
5593     return NULL;
5594   else
5595     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5596 }
5597
5598 static void
5599 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5600 {
5601   struct objfile *objfile = cu->objfile;
5602   CORE_ADDR addr = 0;
5603   char *actual_name = NULL;
5604   CORE_ADDR baseaddr;
5605   int built_actual_name = 0;
5606
5607   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5608
5609   actual_name = partial_die_full_name (pdi, cu);
5610   if (actual_name)
5611     built_actual_name = 1;
5612
5613   if (actual_name == NULL)
5614     actual_name = pdi->name;
5615
5616   switch (pdi->tag)
5617     {
5618     case DW_TAG_subprogram:
5619       if (pdi->is_external || cu->language == language_ada)
5620         {
5621           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5622              of the global scope.  But in Ada, we want to be able to access
5623              nested procedures globally.  So all Ada subprograms are stored
5624              in the global scope.  */
5625           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5626              mst_text, objfile); */
5627           add_psymbol_to_list (actual_name, strlen (actual_name),
5628                                built_actual_name,
5629                                VAR_DOMAIN, LOC_BLOCK,
5630                                &objfile->global_psymbols,
5631                                0, pdi->lowpc + baseaddr,
5632                                cu->language, objfile);
5633         }
5634       else
5635         {
5636           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5637              mst_file_text, objfile); */
5638           add_psymbol_to_list (actual_name, strlen (actual_name),
5639                                built_actual_name,
5640                                VAR_DOMAIN, LOC_BLOCK,
5641                                &objfile->static_psymbols,
5642                                0, pdi->lowpc + baseaddr,
5643                                cu->language, objfile);
5644         }
5645       break;
5646     case DW_TAG_constant:
5647       {
5648         struct psymbol_allocation_list *list;
5649
5650         if (pdi->is_external)
5651           list = &objfile->global_psymbols;
5652         else
5653           list = &objfile->static_psymbols;
5654         add_psymbol_to_list (actual_name, strlen (actual_name),
5655                              built_actual_name, VAR_DOMAIN, LOC_STATIC,
5656                              list, 0, 0, cu->language, objfile);
5657       }
5658       break;
5659     case DW_TAG_variable:
5660       if (pdi->d.locdesc)
5661         addr = decode_locdesc (pdi->d.locdesc, cu);
5662
5663       if (pdi->d.locdesc
5664           && addr == 0
5665           && !dwarf2_per_objfile->has_section_at_zero)
5666         {
5667           /* A global or static variable may also have been stripped
5668              out by the linker if unused, in which case its address
5669              will be nullified; do not add such variables into partial
5670              symbol table then.  */
5671         }
5672       else if (pdi->is_external)
5673         {
5674           /* Global Variable.
5675              Don't enter into the minimal symbol tables as there is
5676              a minimal symbol table entry from the ELF symbols already.
5677              Enter into partial symbol table if it has a location
5678              descriptor or a type.
5679              If the location descriptor is missing, new_symbol will create
5680              a LOC_UNRESOLVED symbol, the address of the variable will then
5681              be determined from the minimal symbol table whenever the variable
5682              is referenced.
5683              The address for the partial symbol table entry is not
5684              used by GDB, but it comes in handy for debugging partial symbol
5685              table building.  */
5686
5687           if (pdi->d.locdesc || pdi->has_type)
5688             add_psymbol_to_list (actual_name, strlen (actual_name),
5689                                  built_actual_name,
5690                                  VAR_DOMAIN, LOC_STATIC,
5691                                  &objfile->global_psymbols,
5692                                  0, addr + baseaddr,
5693                                  cu->language, objfile);
5694         }
5695       else
5696         {
5697           /* Static Variable.  Skip symbols without location descriptors.  */
5698           if (pdi->d.locdesc == NULL)
5699             {
5700               if (built_actual_name)
5701                 xfree (actual_name);
5702               return;
5703             }
5704           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
5705              mst_file_data, objfile); */
5706           add_psymbol_to_list (actual_name, strlen (actual_name),
5707                                built_actual_name,
5708                                VAR_DOMAIN, LOC_STATIC,
5709                                &objfile->static_psymbols,
5710                                0, addr + baseaddr,
5711                                cu->language, objfile);
5712         }
5713       break;
5714     case DW_TAG_typedef:
5715     case DW_TAG_base_type:
5716     case DW_TAG_subrange_type:
5717       add_psymbol_to_list (actual_name, strlen (actual_name),
5718                            built_actual_name,
5719                            VAR_DOMAIN, LOC_TYPEDEF,
5720                            &objfile->static_psymbols,
5721                            0, (CORE_ADDR) 0, cu->language, objfile);
5722       break;
5723     case DW_TAG_namespace:
5724       add_psymbol_to_list (actual_name, strlen (actual_name),
5725                            built_actual_name,
5726                            VAR_DOMAIN, LOC_TYPEDEF,
5727                            &objfile->global_psymbols,
5728                            0, (CORE_ADDR) 0, cu->language, objfile);
5729       break;
5730     case DW_TAG_class_type:
5731     case DW_TAG_interface_type:
5732     case DW_TAG_structure_type:
5733     case DW_TAG_union_type:
5734     case DW_TAG_enumeration_type:
5735       /* Skip external references.  The DWARF standard says in the section
5736          about "Structure, Union, and Class Type Entries": "An incomplete
5737          structure, union or class type is represented by a structure,
5738          union or class entry that does not have a byte size attribute
5739          and that has a DW_AT_declaration attribute."  */
5740       if (!pdi->has_byte_size && pdi->is_declaration)
5741         {
5742           if (built_actual_name)
5743             xfree (actual_name);
5744           return;
5745         }
5746
5747       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
5748          static vs. global.  */
5749       add_psymbol_to_list (actual_name, strlen (actual_name),
5750                            built_actual_name,
5751                            STRUCT_DOMAIN, LOC_TYPEDEF,
5752                            (cu->language == language_cplus
5753                             || cu->language == language_java)
5754                            ? &objfile->global_psymbols
5755                            : &objfile->static_psymbols,
5756                            0, (CORE_ADDR) 0, cu->language, objfile);
5757
5758       break;
5759     case DW_TAG_enumerator:
5760       add_psymbol_to_list (actual_name, strlen (actual_name),
5761                            built_actual_name,
5762                            VAR_DOMAIN, LOC_CONST,
5763                            (cu->language == language_cplus
5764                             || cu->language == language_java)
5765                            ? &objfile->global_psymbols
5766                            : &objfile->static_psymbols,
5767                            0, (CORE_ADDR) 0, cu->language, objfile);
5768       break;
5769     default:
5770       break;
5771     }
5772
5773   if (built_actual_name)
5774     xfree (actual_name);
5775 }
5776
5777 /* Read a partial die corresponding to a namespace; also, add a symbol
5778    corresponding to that namespace to the symbol table.  NAMESPACE is
5779    the name of the enclosing namespace.  */
5780
5781 static void
5782 add_partial_namespace (struct partial_die_info *pdi,
5783                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
5784                        int need_pc, struct dwarf2_cu *cu)
5785 {
5786   /* Add a symbol for the namespace.  */
5787
5788   add_partial_symbol (pdi, cu);
5789
5790   /* Now scan partial symbols in that namespace.  */
5791
5792   if (pdi->has_children)
5793     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
5794 }
5795
5796 /* Read a partial die corresponding to a Fortran module.  */
5797
5798 static void
5799 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
5800                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5801 {
5802   /* Now scan partial symbols in that module.  */
5803
5804   if (pdi->has_children)
5805     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
5806 }
5807
5808 /* Read a partial die corresponding to a subprogram and create a partial
5809    symbol for that subprogram.  When the CU language allows it, this
5810    routine also defines a partial symbol for each nested subprogram
5811    that this subprogram contains.
5812
5813    DIE my also be a lexical block, in which case we simply search
5814    recursively for suprograms defined inside that lexical block.
5815    Again, this is only performed when the CU language allows this
5816    type of definitions.  */
5817
5818 static void
5819 add_partial_subprogram (struct partial_die_info *pdi,
5820                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
5821                         int need_pc, struct dwarf2_cu *cu)
5822 {
5823   if (pdi->tag == DW_TAG_subprogram)
5824     {
5825       if (pdi->has_pc_info)
5826         {
5827           if (pdi->lowpc < *lowpc)
5828             *lowpc = pdi->lowpc;
5829           if (pdi->highpc > *highpc)
5830             *highpc = pdi->highpc;
5831           if (need_pc)
5832             {
5833               CORE_ADDR baseaddr;
5834               struct objfile *objfile = cu->objfile;
5835
5836               baseaddr = ANOFFSET (objfile->section_offsets,
5837                                    SECT_OFF_TEXT (objfile));
5838               addrmap_set_empty (objfile->psymtabs_addrmap,
5839                                  pdi->lowpc + baseaddr,
5840                                  pdi->highpc - 1 + baseaddr,
5841                                  cu->per_cu->v.psymtab);
5842             }
5843         }
5844
5845       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
5846         {
5847           if (!pdi->is_declaration)
5848             /* Ignore subprogram DIEs that do not have a name, they are
5849                illegal.  Do not emit a complaint at this point, we will
5850                do so when we convert this psymtab into a symtab.  */
5851             if (pdi->name)
5852               add_partial_symbol (pdi, cu);
5853         }
5854     }
5855
5856   if (! pdi->has_children)
5857     return;
5858
5859   if (cu->language == language_ada)
5860     {
5861       pdi = pdi->die_child;
5862       while (pdi != NULL)
5863         {
5864           fixup_partial_die (pdi, cu);
5865           if (pdi->tag == DW_TAG_subprogram
5866               || pdi->tag == DW_TAG_lexical_block)
5867             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5868           pdi = pdi->die_sibling;
5869         }
5870     }
5871 }
5872
5873 /* Read a partial die corresponding to an enumeration type.  */
5874
5875 static void
5876 add_partial_enumeration (struct partial_die_info *enum_pdi,
5877                          struct dwarf2_cu *cu)
5878 {
5879   struct partial_die_info *pdi;
5880
5881   if (enum_pdi->name != NULL)
5882     add_partial_symbol (enum_pdi, cu);
5883
5884   pdi = enum_pdi->die_child;
5885   while (pdi)
5886     {
5887       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
5888         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
5889       else
5890         add_partial_symbol (pdi, cu);
5891       pdi = pdi->die_sibling;
5892     }
5893 }
5894
5895 /* Return the initial uleb128 in the die at INFO_PTR.  */
5896
5897 static unsigned int
5898 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
5899 {
5900   unsigned int bytes_read;
5901
5902   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5903 }
5904
5905 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
5906    Return the corresponding abbrev, or NULL if the number is zero (indicating
5907    an empty DIE).  In either case *BYTES_READ will be set to the length of
5908    the initial number.  */
5909
5910 static struct abbrev_info *
5911 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
5912                  struct dwarf2_cu *cu)
5913 {
5914   bfd *abfd = cu->objfile->obfd;
5915   unsigned int abbrev_number;
5916   struct abbrev_info *abbrev;
5917
5918   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
5919
5920   if (abbrev_number == 0)
5921     return NULL;
5922
5923   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
5924   if (!abbrev)
5925     {
5926       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
5927              abbrev_number, bfd_get_filename (abfd));
5928     }
5929
5930   return abbrev;
5931 }
5932
5933 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5934    Returns a pointer to the end of a series of DIEs, terminated by an empty
5935    DIE.  Any children of the skipped DIEs will also be skipped.  */
5936
5937 static gdb_byte *
5938 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
5939 {
5940   struct dwarf2_cu *cu = reader->cu;
5941   struct abbrev_info *abbrev;
5942   unsigned int bytes_read;
5943
5944   while (1)
5945     {
5946       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
5947       if (abbrev == NULL)
5948         return info_ptr + bytes_read;
5949       else
5950         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
5951     }
5952 }
5953
5954 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5955    INFO_PTR should point just after the initial uleb128 of a DIE, and the
5956    abbrev corresponding to that skipped uleb128 should be passed in
5957    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
5958    children.  */
5959
5960 static gdb_byte *
5961 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
5962               struct abbrev_info *abbrev)
5963 {
5964   unsigned int bytes_read;
5965   struct attribute attr;
5966   bfd *abfd = reader->abfd;
5967   struct dwarf2_cu *cu = reader->cu;
5968   gdb_byte *buffer = reader->buffer;
5969   const gdb_byte *buffer_end = reader->buffer_end;
5970   gdb_byte *start_info_ptr = info_ptr;
5971   unsigned int form, i;
5972
5973   for (i = 0; i < abbrev->num_attrs; i++)
5974     {
5975       /* The only abbrev we care about is DW_AT_sibling.  */
5976       if (abbrev->attrs[i].name == DW_AT_sibling)
5977         {
5978           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
5979           if (attr.form == DW_FORM_ref_addr)
5980             complaint (&symfile_complaints,
5981                        _("ignoring absolute DW_AT_sibling"));
5982           else
5983             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
5984         }
5985
5986       /* If it isn't DW_AT_sibling, skip this attribute.  */
5987       form = abbrev->attrs[i].form;
5988     skip_attribute:
5989       switch (form)
5990         {
5991         case DW_FORM_ref_addr:
5992           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
5993              and later it is offset sized.  */
5994           if (cu->header.version == 2)
5995             info_ptr += cu->header.addr_size;
5996           else
5997             info_ptr += cu->header.offset_size;
5998           break;
5999         case DW_FORM_addr:
6000           info_ptr += cu->header.addr_size;
6001           break;
6002         case DW_FORM_data1:
6003         case DW_FORM_ref1:
6004         case DW_FORM_flag:
6005           info_ptr += 1;
6006           break;
6007         case DW_FORM_flag_present:
6008           break;
6009         case DW_FORM_data2:
6010         case DW_FORM_ref2:
6011           info_ptr += 2;
6012           break;
6013         case DW_FORM_data4:
6014         case DW_FORM_ref4:
6015           info_ptr += 4;
6016           break;
6017         case DW_FORM_data8:
6018         case DW_FORM_ref8:
6019         case DW_FORM_ref_sig8:
6020           info_ptr += 8;
6021           break;
6022         case DW_FORM_string:
6023           read_direct_string (abfd, info_ptr, &bytes_read);
6024           info_ptr += bytes_read;
6025           break;
6026         case DW_FORM_sec_offset:
6027         case DW_FORM_strp:
6028           info_ptr += cu->header.offset_size;
6029           break;
6030         case DW_FORM_exprloc:
6031         case DW_FORM_block:
6032           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6033           info_ptr += bytes_read;
6034           break;
6035         case DW_FORM_block1:
6036           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6037           break;
6038         case DW_FORM_block2:
6039           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6040           break;
6041         case DW_FORM_block4:
6042           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6043           break;
6044         case DW_FORM_sdata:
6045         case DW_FORM_udata:
6046         case DW_FORM_ref_udata:
6047         case DW_FORM_GNU_addr_index:
6048         case DW_FORM_GNU_str_index:
6049           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6050           break;
6051         case DW_FORM_indirect:
6052           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6053           info_ptr += bytes_read;
6054           /* We need to continue parsing from here, so just go back to
6055              the top.  */
6056           goto skip_attribute;
6057
6058         default:
6059           error (_("Dwarf Error: Cannot handle %s "
6060                    "in DWARF reader [in module %s]"),
6061                  dwarf_form_name (form),
6062                  bfd_get_filename (abfd));
6063         }
6064     }
6065
6066   if (abbrev->has_children)
6067     return skip_children (reader, info_ptr);
6068   else
6069     return info_ptr;
6070 }
6071
6072 /* Locate ORIG_PDI's sibling.
6073    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6074
6075 static gdb_byte *
6076 locate_pdi_sibling (const struct die_reader_specs *reader,
6077                     struct partial_die_info *orig_pdi,
6078                     gdb_byte *info_ptr)
6079 {
6080   /* Do we know the sibling already?  */
6081
6082   if (orig_pdi->sibling)
6083     return orig_pdi->sibling;
6084
6085   /* Are there any children to deal with?  */
6086
6087   if (!orig_pdi->has_children)
6088     return info_ptr;
6089
6090   /* Skip the children the long way.  */
6091
6092   return skip_children (reader, info_ptr);
6093 }
6094
6095 /* Expand this partial symbol table into a full symbol table.  */
6096
6097 static void
6098 dwarf2_psymtab_to_symtab (struct partial_symtab *pst)
6099 {
6100   if (pst != NULL)
6101     {
6102       if (pst->readin)
6103         {
6104           warning (_("bug: psymtab for %s is already read in."),
6105                    pst->filename);
6106         }
6107       else
6108         {
6109           if (info_verbose)
6110             {
6111               printf_filtered (_("Reading in symbols for %s..."),
6112                                pst->filename);
6113               gdb_flush (gdb_stdout);
6114             }
6115
6116           /* Restore our global data.  */
6117           dwarf2_per_objfile = objfile_data (pst->objfile,
6118                                              dwarf2_objfile_data_key);
6119
6120           /* If this psymtab is constructed from a debug-only objfile, the
6121              has_section_at_zero flag will not necessarily be correct.  We
6122              can get the correct value for this flag by looking at the data
6123              associated with the (presumably stripped) associated objfile.  */
6124           if (pst->objfile->separate_debug_objfile_backlink)
6125             {
6126               struct dwarf2_per_objfile *dpo_backlink
6127                 = objfile_data (pst->objfile->separate_debug_objfile_backlink,
6128                                 dwarf2_objfile_data_key);
6129
6130               dwarf2_per_objfile->has_section_at_zero
6131                 = dpo_backlink->has_section_at_zero;
6132             }
6133
6134           dwarf2_per_objfile->reading_partial_symbols = 0;
6135
6136           psymtab_to_symtab_1 (pst);
6137
6138           /* Finish up the debug error message.  */
6139           if (info_verbose)
6140             printf_filtered (_("done.\n"));
6141         }
6142     }
6143
6144   process_cu_includes ();
6145 }
6146 \f
6147 /* Reading in full CUs.  */
6148
6149 /* Add PER_CU to the queue.  */
6150
6151 static void
6152 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6153                  enum language pretend_language)
6154 {
6155   struct dwarf2_queue_item *item;
6156
6157   per_cu->queued = 1;
6158   item = xmalloc (sizeof (*item));
6159   item->per_cu = per_cu;
6160   item->pretend_language = pretend_language;
6161   item->next = NULL;
6162
6163   if (dwarf2_queue == NULL)
6164     dwarf2_queue = item;
6165   else
6166     dwarf2_queue_tail->next = item;
6167
6168   dwarf2_queue_tail = item;
6169 }
6170
6171 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6172    unit and add it to our queue.
6173    The result is non-zero if PER_CU was queued, otherwise the result is zero
6174    meaning either PER_CU is already queued or it is already loaded.  */
6175
6176 static int
6177 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6178                        struct dwarf2_per_cu_data *per_cu,
6179                        enum language pretend_language)
6180 {
6181   /* We may arrive here during partial symbol reading, if we need full
6182      DIEs to process an unusual case (e.g. template arguments).  Do
6183      not queue PER_CU, just tell our caller to load its DIEs.  */
6184   if (dwarf2_per_objfile->reading_partial_symbols)
6185     {
6186       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6187         return 1;
6188       return 0;
6189     }
6190
6191   /* Mark the dependence relation so that we don't flush PER_CU
6192      too early.  */
6193   dwarf2_add_dependence (this_cu, per_cu);
6194
6195   /* If it's already on the queue, we have nothing to do.  */
6196   if (per_cu->queued)
6197     return 0;
6198
6199   /* If the compilation unit is already loaded, just mark it as
6200      used.  */
6201   if (per_cu->cu != NULL)
6202     {
6203       per_cu->cu->last_used = 0;
6204       return 0;
6205     }
6206
6207   /* Add it to the queue.  */
6208   queue_comp_unit (per_cu, pretend_language);
6209
6210   return 1;
6211 }
6212
6213 /* Process the queue.  */
6214
6215 static void
6216 process_queue (void)
6217 {
6218   struct dwarf2_queue_item *item, *next_item;
6219
6220   if (dwarf2_read_debug)
6221     {
6222       fprintf_unfiltered (gdb_stdlog,
6223                           "Expanding one or more symtabs of objfile %s ...\n",
6224                           dwarf2_per_objfile->objfile->name);
6225     }
6226
6227   /* The queue starts out with one item, but following a DIE reference
6228      may load a new CU, adding it to the end of the queue.  */
6229   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6230     {
6231       if (dwarf2_per_objfile->using_index
6232           ? !item->per_cu->v.quick->symtab
6233           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6234         {
6235           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6236
6237           if (dwarf2_read_debug)
6238             {
6239               fprintf_unfiltered (gdb_stdlog,
6240                                   "Expanding symtab of %s at offset 0x%x\n",
6241                                   per_cu->is_debug_types ? "TU" : "CU",
6242                                   per_cu->offset.sect_off);
6243             }
6244
6245           if (per_cu->is_debug_types)
6246             process_full_type_unit (per_cu, item->pretend_language);
6247           else
6248             process_full_comp_unit (per_cu, item->pretend_language);
6249
6250           if (dwarf2_read_debug)
6251             {
6252               fprintf_unfiltered (gdb_stdlog,
6253                                   "Done expanding %s at offset 0x%x\n",
6254                                   per_cu->is_debug_types ? "TU" : "CU",
6255                                   per_cu->offset.sect_off);
6256             }
6257         }
6258
6259       item->per_cu->queued = 0;
6260       next_item = item->next;
6261       xfree (item);
6262     }
6263
6264   dwarf2_queue_tail = NULL;
6265
6266   if (dwarf2_read_debug)
6267     {
6268       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6269                           dwarf2_per_objfile->objfile->name);
6270     }
6271 }
6272
6273 /* Free all allocated queue entries.  This function only releases anything if
6274    an error was thrown; if the queue was processed then it would have been
6275    freed as we went along.  */
6276
6277 static void
6278 dwarf2_release_queue (void *dummy)
6279 {
6280   struct dwarf2_queue_item *item, *last;
6281
6282   item = dwarf2_queue;
6283   while (item)
6284     {
6285       /* Anything still marked queued is likely to be in an
6286          inconsistent state, so discard it.  */
6287       if (item->per_cu->queued)
6288         {
6289           if (item->per_cu->cu != NULL)
6290             free_one_cached_comp_unit (item->per_cu);
6291           item->per_cu->queued = 0;
6292         }
6293
6294       last = item;
6295       item = item->next;
6296       xfree (last);
6297     }
6298
6299   dwarf2_queue = dwarf2_queue_tail = NULL;
6300 }
6301
6302 /* Read in full symbols for PST, and anything it depends on.  */
6303
6304 static void
6305 psymtab_to_symtab_1 (struct partial_symtab *pst)
6306 {
6307   struct dwarf2_per_cu_data *per_cu;
6308   int i;
6309
6310   if (pst->readin)
6311     return;
6312
6313   for (i = 0; i < pst->number_of_dependencies; i++)
6314     if (!pst->dependencies[i]->readin
6315         && pst->dependencies[i]->user == NULL)
6316       {
6317         /* Inform about additional files that need to be read in.  */
6318         if (info_verbose)
6319           {
6320             /* FIXME: i18n: Need to make this a single string.  */
6321             fputs_filtered (" ", gdb_stdout);
6322             wrap_here ("");
6323             fputs_filtered ("and ", gdb_stdout);
6324             wrap_here ("");
6325             printf_filtered ("%s...", pst->dependencies[i]->filename);
6326             wrap_here ("");     /* Flush output.  */
6327             gdb_flush (gdb_stdout);
6328           }
6329         psymtab_to_symtab_1 (pst->dependencies[i]);
6330       }
6331
6332   per_cu = pst->read_symtab_private;
6333
6334   if (per_cu == NULL)
6335     {
6336       /* It's an include file, no symbols to read for it.
6337          Everything is in the parent symtab.  */
6338       pst->readin = 1;
6339       return;
6340     }
6341
6342   dw2_do_instantiate_symtab (per_cu);
6343 }
6344
6345 /* Trivial hash function for die_info: the hash value of a DIE
6346    is its offset in .debug_info for this objfile.  */
6347
6348 static hashval_t
6349 die_hash (const void *item)
6350 {
6351   const struct die_info *die = item;
6352
6353   return die->offset.sect_off;
6354 }
6355
6356 /* Trivial comparison function for die_info structures: two DIEs
6357    are equal if they have the same offset.  */
6358
6359 static int
6360 die_eq (const void *item_lhs, const void *item_rhs)
6361 {
6362   const struct die_info *die_lhs = item_lhs;
6363   const struct die_info *die_rhs = item_rhs;
6364
6365   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6366 }
6367
6368 /* die_reader_func for load_full_comp_unit.
6369    This is identical to read_signatured_type_reader,
6370    but is kept separate for now.  */
6371
6372 static void
6373 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6374                             gdb_byte *info_ptr,
6375                             struct die_info *comp_unit_die,
6376                             int has_children,
6377                             void *data)
6378 {
6379   struct dwarf2_cu *cu = reader->cu;
6380   enum language *language_ptr = data;
6381
6382   gdb_assert (cu->die_hash == NULL);
6383   cu->die_hash =
6384     htab_create_alloc_ex (cu->header.length / 12,
6385                           die_hash,
6386                           die_eq,
6387                           NULL,
6388                           &cu->comp_unit_obstack,
6389                           hashtab_obstack_allocate,
6390                           dummy_obstack_deallocate);
6391
6392   if (has_children)
6393     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6394                                                   &info_ptr, comp_unit_die);
6395   cu->dies = comp_unit_die;
6396   /* comp_unit_die is not stored in die_hash, no need.  */
6397
6398   /* We try not to read any attributes in this function, because not
6399      all CUs needed for references have been loaded yet, and symbol
6400      table processing isn't initialized.  But we have to set the CU language,
6401      or we won't be able to build types correctly.
6402      Similarly, if we do not read the producer, we can not apply
6403      producer-specific interpretation.  */
6404   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6405 }
6406
6407 /* Load the DIEs associated with PER_CU into memory.  */
6408
6409 static void
6410 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6411                      enum language pretend_language)
6412 {
6413   gdb_assert (! this_cu->is_debug_types);
6414
6415   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6416                            load_full_comp_unit_reader, &pretend_language);
6417 }
6418
6419 /* Add a DIE to the delayed physname list.  */
6420
6421 static void
6422 add_to_method_list (struct type *type, int fnfield_index, int index,
6423                     const char *name, struct die_info *die,
6424                     struct dwarf2_cu *cu)
6425 {
6426   struct delayed_method_info mi;
6427   mi.type = type;
6428   mi.fnfield_index = fnfield_index;
6429   mi.index = index;
6430   mi.name = name;
6431   mi.die = die;
6432   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6433 }
6434
6435 /* A cleanup for freeing the delayed method list.  */
6436
6437 static void
6438 free_delayed_list (void *ptr)
6439 {
6440   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6441   if (cu->method_list != NULL)
6442     {
6443       VEC_free (delayed_method_info, cu->method_list);
6444       cu->method_list = NULL;
6445     }
6446 }
6447
6448 /* Compute the physnames of any methods on the CU's method list.
6449
6450    The computation of method physnames is delayed in order to avoid the
6451    (bad) condition that one of the method's formal parameters is of an as yet
6452    incomplete type.  */
6453
6454 static void
6455 compute_delayed_physnames (struct dwarf2_cu *cu)
6456 {
6457   int i;
6458   struct delayed_method_info *mi;
6459   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6460     {
6461       const char *physname;
6462       struct fn_fieldlist *fn_flp
6463         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6464       physname = dwarf2_physname ((char *) mi->name, mi->die, cu);
6465       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6466     }
6467 }
6468
6469 /* Go objects should be embedded in a DW_TAG_module DIE,
6470    and it's not clear if/how imported objects will appear.
6471    To keep Go support simple until that's worked out,
6472    go back through what we've read and create something usable.
6473    We could do this while processing each DIE, and feels kinda cleaner,
6474    but that way is more invasive.
6475    This is to, for example, allow the user to type "p var" or "b main"
6476    without having to specify the package name, and allow lookups
6477    of module.object to work in contexts that use the expression
6478    parser.  */
6479
6480 static void
6481 fixup_go_packaging (struct dwarf2_cu *cu)
6482 {
6483   char *package_name = NULL;
6484   struct pending *list;
6485   int i;
6486
6487   for (list = global_symbols; list != NULL; list = list->next)
6488     {
6489       for (i = 0; i < list->nsyms; ++i)
6490         {
6491           struct symbol *sym = list->symbol[i];
6492
6493           if (SYMBOL_LANGUAGE (sym) == language_go
6494               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6495             {
6496               char *this_package_name = go_symbol_package_name (sym);
6497
6498               if (this_package_name == NULL)
6499                 continue;
6500               if (package_name == NULL)
6501                 package_name = this_package_name;
6502               else
6503                 {
6504                   if (strcmp (package_name, this_package_name) != 0)
6505                     complaint (&symfile_complaints,
6506                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6507                                (sym->symtab && sym->symtab->filename
6508                                 ? sym->symtab->filename
6509                                 : cu->objfile->name),
6510                                this_package_name, package_name);
6511                   xfree (this_package_name);
6512                 }
6513             }
6514         }
6515     }
6516
6517   if (package_name != NULL)
6518     {
6519       struct objfile *objfile = cu->objfile;
6520       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6521                                      package_name, objfile);
6522       struct symbol *sym;
6523
6524       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6525
6526       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6527       SYMBOL_SET_LANGUAGE (sym, language_go);
6528       SYMBOL_SET_NAMES (sym, package_name, strlen (package_name), 1, objfile);
6529       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6530          e.g., "main" finds the "main" module and not C's main().  */
6531       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6532       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
6533       SYMBOL_TYPE (sym) = type;
6534
6535       add_symbol_to_list (sym, &global_symbols);
6536
6537       xfree (package_name);
6538     }
6539 }
6540
6541 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
6542
6543 /* Return the symtab for PER_CU.  This works properly regardless of
6544    whether we're using the index or psymtabs.  */
6545
6546 static struct symtab *
6547 get_symtab (struct dwarf2_per_cu_data *per_cu)
6548 {
6549   return (dwarf2_per_objfile->using_index
6550           ? per_cu->v.quick->symtab
6551           : per_cu->v.psymtab->symtab);
6552 }
6553
6554 /* A helper function for computing the list of all symbol tables
6555    included by PER_CU.  */
6556
6557 static void
6558 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6559                                 htab_t all_children,
6560                                 struct dwarf2_per_cu_data *per_cu)
6561 {
6562   void **slot;
6563   int ix;
6564   struct dwarf2_per_cu_data *iter;
6565
6566   slot = htab_find_slot (all_children, per_cu, INSERT);
6567   if (*slot != NULL)
6568     {
6569       /* This inclusion and its children have been processed.  */
6570       return;
6571     }
6572
6573   *slot = per_cu;
6574   /* Only add a CU if it has a symbol table.  */
6575   if (get_symtab (per_cu) != NULL)
6576     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6577
6578   for (ix = 0;
6579        VEC_iterate (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs, ix, iter);
6580        ++ix)
6581     recursively_compute_inclusions (result, all_children, iter);
6582 }
6583
6584 /* Compute the symtab 'includes' fields for the symtab related to
6585    PER_CU.  */
6586
6587 static void
6588 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6589 {
6590   gdb_assert (! per_cu->is_debug_types);
6591
6592   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs))
6593     {
6594       int ix, len;
6595       struct dwarf2_per_cu_data *iter;
6596       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6597       htab_t all_children;
6598       struct symtab *symtab = get_symtab (per_cu);
6599
6600       /* If we don't have a symtab, we can just skip this case.  */
6601       if (symtab == NULL)
6602         return;
6603
6604       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6605                                         NULL, xcalloc, xfree);
6606
6607       for (ix = 0;
6608            VEC_iterate (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs,
6609                         ix, iter);
6610            ++ix)
6611         recursively_compute_inclusions (&result_children, all_children, iter);
6612
6613       /* Now we have a transitive closure of all the included CUs, so
6614          we can convert it to a list of symtabs.  */
6615       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6616       symtab->includes
6617         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6618                          (len + 1) * sizeof (struct symtab *));
6619       for (ix = 0;
6620            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6621            ++ix)
6622         symtab->includes[ix] = get_symtab (iter);
6623       symtab->includes[len] = NULL;
6624
6625       VEC_free (dwarf2_per_cu_ptr, result_children);
6626       htab_delete (all_children);
6627     }
6628 }
6629
6630 /* Compute the 'includes' field for the symtabs of all the CUs we just
6631    read.  */
6632
6633 static void
6634 process_cu_includes (void)
6635 {
6636   int ix;
6637   struct dwarf2_per_cu_data *iter;
6638
6639   for (ix = 0;
6640        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6641                     ix, iter);
6642        ++ix)
6643     {
6644       if (! iter->is_debug_types)
6645         compute_symtab_includes (iter);
6646     }
6647
6648   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6649 }
6650
6651 /* Generate full symbol information for PER_CU, whose DIEs have
6652    already been loaded into memory.  */
6653
6654 static void
6655 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6656                         enum language pretend_language)
6657 {
6658   struct dwarf2_cu *cu = per_cu->cu;
6659   struct objfile *objfile = per_cu->objfile;
6660   CORE_ADDR lowpc, highpc;
6661   struct symtab *symtab;
6662   struct cleanup *back_to, *delayed_list_cleanup;
6663   CORE_ADDR baseaddr;
6664   struct block *static_block;
6665
6666   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6667
6668   buildsym_init ();
6669   back_to = make_cleanup (really_free_pendings, NULL);
6670   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6671
6672   cu->list_in_scope = &file_symbols;
6673
6674   cu->language = pretend_language;
6675   cu->language_defn = language_def (cu->language);
6676
6677   /* Do line number decoding in read_file_scope () */
6678   process_die (cu->dies, cu);
6679
6680   /* For now fudge the Go package.  */
6681   if (cu->language == language_go)
6682     fixup_go_packaging (cu);
6683
6684   /* Now that we have processed all the DIEs in the CU, all the types 
6685      should be complete, and it should now be safe to compute all of the
6686      physnames.  */
6687   compute_delayed_physnames (cu);
6688   do_cleanups (delayed_list_cleanup);
6689
6690   /* Some compilers don't define a DW_AT_high_pc attribute for the
6691      compilation unit.  If the DW_AT_high_pc is missing, synthesize
6692      it, by scanning the DIE's below the compilation unit.  */
6693   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
6694
6695   static_block = end_symtab_get_static_block (highpc + baseaddr, objfile, 0);
6696
6697   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
6698      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
6699      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
6700      addrmap to help ensure it has an accurate map of pc values belonging to
6701      this comp unit.  */
6702   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
6703
6704   symtab = end_symtab_from_static_block (static_block, objfile,
6705                                          SECT_OFF_TEXT (objfile), 0);
6706
6707   if (symtab != NULL)
6708     {
6709       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
6710
6711       /* Set symtab language to language from DW_AT_language.  If the
6712          compilation is from a C file generated by language preprocessors, do
6713          not set the language if it was already deduced by start_subfile.  */
6714       if (!(cu->language == language_c && symtab->language != language_c))
6715         symtab->language = cu->language;
6716
6717       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
6718          produce DW_AT_location with location lists but it can be possibly
6719          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
6720          there were bugs in prologue debug info, fixed later in GCC-4.5
6721          by "unwind info for epilogues" patch (which is not directly related).
6722
6723          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
6724          needed, it would be wrong due to missing DW_AT_producer there.
6725
6726          Still one can confuse GDB by using non-standard GCC compilation
6727          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
6728          */ 
6729       if (cu->has_loclist && gcc_4_minor >= 5)
6730         symtab->locations_valid = 1;
6731
6732       if (gcc_4_minor >= 5)
6733         symtab->epilogue_unwind_valid = 1;
6734
6735       symtab->call_site_htab = cu->call_site_htab;
6736     }
6737
6738   if (dwarf2_per_objfile->using_index)
6739     per_cu->v.quick->symtab = symtab;
6740   else
6741     {
6742       struct partial_symtab *pst = per_cu->v.psymtab;
6743       pst->symtab = symtab;
6744       pst->readin = 1;
6745     }
6746
6747   /* Push it for inclusion processing later.  */
6748   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
6749
6750   do_cleanups (back_to);
6751 }
6752
6753 /* Generate full symbol information for type unit PER_CU, whose DIEs have
6754    already been loaded into memory.  */
6755
6756 static void
6757 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
6758                         enum language pretend_language)
6759 {
6760   struct dwarf2_cu *cu = per_cu->cu;
6761   struct objfile *objfile = per_cu->objfile;
6762   struct symtab *symtab;
6763   struct cleanup *back_to, *delayed_list_cleanup;
6764
6765   buildsym_init ();
6766   back_to = make_cleanup (really_free_pendings, NULL);
6767   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6768
6769   cu->list_in_scope = &file_symbols;
6770
6771   cu->language = pretend_language;
6772   cu->language_defn = language_def (cu->language);
6773
6774   /* The symbol tables are set up in read_type_unit_scope.  */
6775   process_die (cu->dies, cu);
6776
6777   /* For now fudge the Go package.  */
6778   if (cu->language == language_go)
6779     fixup_go_packaging (cu);
6780
6781   /* Now that we have processed all the DIEs in the CU, all the types 
6782      should be complete, and it should now be safe to compute all of the
6783      physnames.  */
6784   compute_delayed_physnames (cu);
6785   do_cleanups (delayed_list_cleanup);
6786
6787   /* TUs share symbol tables.
6788      If this is the first TU to use this symtab, complete the construction
6789      of it with end_expandable_symtab.  Otherwise, complete the addition of
6790      this TU's symbols to the existing symtab.  */
6791   if (per_cu->s.type_unit_group->primary_symtab == NULL)
6792     {
6793       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
6794       per_cu->s.type_unit_group->primary_symtab = symtab;
6795
6796       if (symtab != NULL)
6797         {
6798           /* Set symtab language to language from DW_AT_language.  If the
6799              compilation is from a C file generated by language preprocessors,
6800              do not set the language if it was already deduced by
6801              start_subfile.  */
6802           if (!(cu->language == language_c && symtab->language != language_c))
6803             symtab->language = cu->language;
6804         }
6805     }
6806   else
6807     {
6808       augment_type_symtab (objfile,
6809                            per_cu->s.type_unit_group->primary_symtab);
6810       symtab = per_cu->s.type_unit_group->primary_symtab;
6811     }
6812
6813   if (dwarf2_per_objfile->using_index)
6814     per_cu->v.quick->symtab = symtab;
6815   else
6816     {
6817       struct partial_symtab *pst = per_cu->v.psymtab;
6818       pst->symtab = symtab;
6819       pst->readin = 1;
6820     }
6821
6822   do_cleanups (back_to);
6823 }
6824
6825 /* Process an imported unit DIE.  */
6826
6827 static void
6828 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
6829 {
6830   struct attribute *attr;
6831
6832   /* For now we don't handle imported units in type units.  */
6833   if (cu->per_cu->is_debug_types)
6834     {
6835       error (_("Dwarf Error: DW_TAG_imported_unit is not"
6836                " supported in type units [in module %s]"),
6837              cu->objfile->name);
6838     }
6839
6840   attr = dwarf2_attr (die, DW_AT_import, cu);
6841   if (attr != NULL)
6842     {
6843       struct dwarf2_per_cu_data *per_cu;
6844       struct symtab *imported_symtab;
6845       sect_offset offset;
6846
6847       offset = dwarf2_get_ref_die_offset (attr);
6848       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
6849
6850       /* Queue the unit, if needed.  */
6851       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
6852         load_full_comp_unit (per_cu, cu->language);
6853
6854       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs,
6855                      per_cu);
6856     }
6857 }
6858
6859 /* Process a die and its children.  */
6860
6861 static void
6862 process_die (struct die_info *die, struct dwarf2_cu *cu)
6863 {
6864   switch (die->tag)
6865     {
6866     case DW_TAG_padding:
6867       break;
6868     case DW_TAG_compile_unit:
6869     case DW_TAG_partial_unit:
6870       read_file_scope (die, cu);
6871       break;
6872     case DW_TAG_type_unit:
6873       read_type_unit_scope (die, cu);
6874       break;
6875     case DW_TAG_subprogram:
6876     case DW_TAG_inlined_subroutine:
6877       read_func_scope (die, cu);
6878       break;
6879     case DW_TAG_lexical_block:
6880     case DW_TAG_try_block:
6881     case DW_TAG_catch_block:
6882       read_lexical_block_scope (die, cu);
6883       break;
6884     case DW_TAG_GNU_call_site:
6885       read_call_site_scope (die, cu);
6886       break;
6887     case DW_TAG_class_type:
6888     case DW_TAG_interface_type:
6889     case DW_TAG_structure_type:
6890     case DW_TAG_union_type:
6891       process_structure_scope (die, cu);
6892       break;
6893     case DW_TAG_enumeration_type:
6894       process_enumeration_scope (die, cu);
6895       break;
6896
6897     /* These dies have a type, but processing them does not create
6898        a symbol or recurse to process the children.  Therefore we can
6899        read them on-demand through read_type_die.  */
6900     case DW_TAG_subroutine_type:
6901     case DW_TAG_set_type:
6902     case DW_TAG_array_type:
6903     case DW_TAG_pointer_type:
6904     case DW_TAG_ptr_to_member_type:
6905     case DW_TAG_reference_type:
6906     case DW_TAG_string_type:
6907       break;
6908
6909     case DW_TAG_base_type:
6910     case DW_TAG_subrange_type:
6911     case DW_TAG_typedef:
6912       /* Add a typedef symbol for the type definition, if it has a
6913          DW_AT_name.  */
6914       new_symbol (die, read_type_die (die, cu), cu);
6915       break;
6916     case DW_TAG_common_block:
6917       read_common_block (die, cu);
6918       break;
6919     case DW_TAG_common_inclusion:
6920       break;
6921     case DW_TAG_namespace:
6922       processing_has_namespace_info = 1;
6923       read_namespace (die, cu);
6924       break;
6925     case DW_TAG_module:
6926       processing_has_namespace_info = 1;
6927       read_module (die, cu);
6928       break;
6929     case DW_TAG_imported_declaration:
6930     case DW_TAG_imported_module:
6931       processing_has_namespace_info = 1;
6932       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
6933                                  || cu->language != language_fortran))
6934         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
6935                    dwarf_tag_name (die->tag));
6936       read_import_statement (die, cu);
6937       break;
6938
6939     case DW_TAG_imported_unit:
6940       process_imported_unit_die (die, cu);
6941       break;
6942
6943     default:
6944       new_symbol (die, NULL, cu);
6945       break;
6946     }
6947 }
6948
6949 /* A helper function for dwarf2_compute_name which determines whether DIE
6950    needs to have the name of the scope prepended to the name listed in the
6951    die.  */
6952
6953 static int
6954 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
6955 {
6956   struct attribute *attr;
6957
6958   switch (die->tag)
6959     {
6960     case DW_TAG_namespace:
6961     case DW_TAG_typedef:
6962     case DW_TAG_class_type:
6963     case DW_TAG_interface_type:
6964     case DW_TAG_structure_type:
6965     case DW_TAG_union_type:
6966     case DW_TAG_enumeration_type:
6967     case DW_TAG_enumerator:
6968     case DW_TAG_subprogram:
6969     case DW_TAG_member:
6970       return 1;
6971
6972     case DW_TAG_variable:
6973     case DW_TAG_constant:
6974       /* We only need to prefix "globally" visible variables.  These include
6975          any variable marked with DW_AT_external or any variable that
6976          lives in a namespace.  [Variables in anonymous namespaces
6977          require prefixing, but they are not DW_AT_external.]  */
6978
6979       if (dwarf2_attr (die, DW_AT_specification, cu))
6980         {
6981           struct dwarf2_cu *spec_cu = cu;
6982
6983           return die_needs_namespace (die_specification (die, &spec_cu),
6984                                       spec_cu);
6985         }
6986
6987       attr = dwarf2_attr (die, DW_AT_external, cu);
6988       if (attr == NULL && die->parent->tag != DW_TAG_namespace
6989           && die->parent->tag != DW_TAG_module)
6990         return 0;
6991       /* A variable in a lexical block of some kind does not need a
6992          namespace, even though in C++ such variables may be external
6993          and have a mangled name.  */
6994       if (die->parent->tag ==  DW_TAG_lexical_block
6995           || die->parent->tag ==  DW_TAG_try_block
6996           || die->parent->tag ==  DW_TAG_catch_block
6997           || die->parent->tag == DW_TAG_subprogram)
6998         return 0;
6999       return 1;
7000
7001     default:
7002       return 0;
7003     }
7004 }
7005
7006 /* Retrieve the last character from a mem_file.  */
7007
7008 static void
7009 do_ui_file_peek_last (void *object, const char *buffer, long length)
7010 {
7011   char *last_char_p = (char *) object;
7012
7013   if (length > 0)
7014     *last_char_p = buffer[length - 1];
7015 }
7016
7017 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7018    compute the physname for the object, which include a method's:
7019    - formal parameters (C++/Java),
7020    - receiver type (Go),
7021    - return type (Java).
7022
7023    The term "physname" is a bit confusing.
7024    For C++, for example, it is the demangled name.
7025    For Go, for example, it's the mangled name.
7026
7027    For Ada, return the DIE's linkage name rather than the fully qualified
7028    name.  PHYSNAME is ignored..
7029
7030    The result is allocated on the objfile_obstack and canonicalized.  */
7031
7032 static const char *
7033 dwarf2_compute_name (char *name, struct die_info *die, struct dwarf2_cu *cu,
7034                      int physname)
7035 {
7036   struct objfile *objfile = cu->objfile;
7037
7038   if (name == NULL)
7039     name = dwarf2_name (die, cu);
7040
7041   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7042      compute it by typename_concat inside GDB.  */
7043   if (cu->language == language_ada
7044       || (cu->language == language_fortran && physname))
7045     {
7046       /* For Ada unit, we prefer the linkage name over the name, as
7047          the former contains the exported name, which the user expects
7048          to be able to reference.  Ideally, we want the user to be able
7049          to reference this entity using either natural or linkage name,
7050          but we haven't started looking at this enhancement yet.  */
7051       struct attribute *attr;
7052
7053       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7054       if (attr == NULL)
7055         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7056       if (attr && DW_STRING (attr))
7057         return DW_STRING (attr);
7058     }
7059
7060   /* These are the only languages we know how to qualify names in.  */
7061   if (name != NULL
7062       && (cu->language == language_cplus || cu->language == language_java
7063           || cu->language == language_fortran))
7064     {
7065       if (die_needs_namespace (die, cu))
7066         {
7067           long length;
7068           const char *prefix;
7069           struct ui_file *buf;
7070
7071           prefix = determine_prefix (die, cu);
7072           buf = mem_fileopen ();
7073           if (*prefix != '\0')
7074             {
7075               char *prefixed_name = typename_concat (NULL, prefix, name,
7076                                                      physname, cu);
7077
7078               fputs_unfiltered (prefixed_name, buf);
7079               xfree (prefixed_name);
7080             }
7081           else
7082             fputs_unfiltered (name, buf);
7083
7084           /* Template parameters may be specified in the DIE's DW_AT_name, or
7085              as children with DW_TAG_template_type_param or
7086              DW_TAG_value_type_param.  If the latter, add them to the name
7087              here.  If the name already has template parameters, then
7088              skip this step; some versions of GCC emit both, and
7089              it is more efficient to use the pre-computed name.
7090
7091              Something to keep in mind about this process: it is very
7092              unlikely, or in some cases downright impossible, to produce
7093              something that will match the mangled name of a function.
7094              If the definition of the function has the same debug info,
7095              we should be able to match up with it anyway.  But fallbacks
7096              using the minimal symbol, for instance to find a method
7097              implemented in a stripped copy of libstdc++, will not work.
7098              If we do not have debug info for the definition, we will have to
7099              match them up some other way.
7100
7101              When we do name matching there is a related problem with function
7102              templates; two instantiated function templates are allowed to
7103              differ only by their return types, which we do not add here.  */
7104
7105           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7106             {
7107               struct attribute *attr;
7108               struct die_info *child;
7109               int first = 1;
7110
7111               die->building_fullname = 1;
7112
7113               for (child = die->child; child != NULL; child = child->sibling)
7114                 {
7115                   struct type *type;
7116                   LONGEST value;
7117                   gdb_byte *bytes;
7118                   struct dwarf2_locexpr_baton *baton;
7119                   struct value *v;
7120
7121                   if (child->tag != DW_TAG_template_type_param
7122                       && child->tag != DW_TAG_template_value_param)
7123                     continue;
7124
7125                   if (first)
7126                     {
7127                       fputs_unfiltered ("<", buf);
7128                       first = 0;
7129                     }
7130                   else
7131                     fputs_unfiltered (", ", buf);
7132
7133                   attr = dwarf2_attr (child, DW_AT_type, cu);
7134                   if (attr == NULL)
7135                     {
7136                       complaint (&symfile_complaints,
7137                                  _("template parameter missing DW_AT_type"));
7138                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7139                       continue;
7140                     }
7141                   type = die_type (child, cu);
7142
7143                   if (child->tag == DW_TAG_template_type_param)
7144                     {
7145                       c_print_type (type, "", buf, -1, 0);
7146                       continue;
7147                     }
7148
7149                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7150                   if (attr == NULL)
7151                     {
7152                       complaint (&symfile_complaints,
7153                                  _("template parameter missing "
7154                                    "DW_AT_const_value"));
7155                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7156                       continue;
7157                     }
7158
7159                   dwarf2_const_value_attr (attr, type, name,
7160                                            &cu->comp_unit_obstack, cu,
7161                                            &value, &bytes, &baton);
7162
7163                   if (TYPE_NOSIGN (type))
7164                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7165                        changed, this can use value_print instead.  */
7166                     c_printchar (value, type, buf);
7167                   else
7168                     {
7169                       struct value_print_options opts;
7170
7171                       if (baton != NULL)
7172                         v = dwarf2_evaluate_loc_desc (type, NULL,
7173                                                       baton->data,
7174                                                       baton->size,
7175                                                       baton->per_cu);
7176                       else if (bytes != NULL)
7177                         {
7178                           v = allocate_value (type);
7179                           memcpy (value_contents_writeable (v), bytes,
7180                                   TYPE_LENGTH (type));
7181                         }
7182                       else
7183                         v = value_from_longest (type, value);
7184
7185                       /* Specify decimal so that we do not depend on
7186                          the radix.  */
7187                       get_formatted_print_options (&opts, 'd');
7188                       opts.raw = 1;
7189                       value_print (v, buf, &opts);
7190                       release_value (v);
7191                       value_free (v);
7192                     }
7193                 }
7194
7195               die->building_fullname = 0;
7196
7197               if (!first)
7198                 {
7199                   /* Close the argument list, with a space if necessary
7200                      (nested templates).  */
7201                   char last_char = '\0';
7202                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7203                   if (last_char == '>')
7204                     fputs_unfiltered (" >", buf);
7205                   else
7206                     fputs_unfiltered (">", buf);
7207                 }
7208             }
7209
7210           /* For Java and C++ methods, append formal parameter type
7211              information, if PHYSNAME.  */
7212
7213           if (physname && die->tag == DW_TAG_subprogram
7214               && (cu->language == language_cplus
7215                   || cu->language == language_java))
7216             {
7217               struct type *type = read_type_die (die, cu);
7218
7219               c_type_print_args (type, buf, 1, cu->language);
7220
7221               if (cu->language == language_java)
7222                 {
7223                   /* For java, we must append the return type to method
7224                      names.  */
7225                   if (die->tag == DW_TAG_subprogram)
7226                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7227                                      0, 0);
7228                 }
7229               else if (cu->language == language_cplus)
7230                 {
7231                   /* Assume that an artificial first parameter is
7232                      "this", but do not crash if it is not.  RealView
7233                      marks unnamed (and thus unused) parameters as
7234                      artificial; there is no way to differentiate
7235                      the two cases.  */
7236                   if (TYPE_NFIELDS (type) > 0
7237                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7238                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7239                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7240                                                                         0))))
7241                     fputs_unfiltered (" const", buf);
7242                 }
7243             }
7244
7245           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7246                                        &length);
7247           ui_file_delete (buf);
7248
7249           if (cu->language == language_cplus)
7250             {
7251               char *cname
7252                 = dwarf2_canonicalize_name (name, cu,
7253                                             &objfile->objfile_obstack);
7254
7255               if (cname != NULL)
7256                 name = cname;
7257             }
7258         }
7259     }
7260
7261   return name;
7262 }
7263
7264 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7265    If scope qualifiers are appropriate they will be added.  The result
7266    will be allocated on the objfile_obstack, or NULL if the DIE does
7267    not have a name.  NAME may either be from a previous call to
7268    dwarf2_name or NULL.
7269
7270    The output string will be canonicalized (if C++/Java).  */
7271
7272 static const char *
7273 dwarf2_full_name (char *name, struct die_info *die, struct dwarf2_cu *cu)
7274 {
7275   return dwarf2_compute_name (name, die, cu, 0);
7276 }
7277
7278 /* Construct a physname for the given DIE in CU.  NAME may either be
7279    from a previous call to dwarf2_name or NULL.  The result will be
7280    allocated on the objfile_objstack or NULL if the DIE does not have a
7281    name.
7282
7283    The output string will be canonicalized (if C++/Java).  */
7284
7285 static const char *
7286 dwarf2_physname (char *name, struct die_info *die, struct dwarf2_cu *cu)
7287 {
7288   struct objfile *objfile = cu->objfile;
7289   struct attribute *attr;
7290   const char *retval, *mangled = NULL, *canon = NULL;
7291   struct cleanup *back_to;
7292   int need_copy = 1;
7293
7294   /* In this case dwarf2_compute_name is just a shortcut not building anything
7295      on its own.  */
7296   if (!die_needs_namespace (die, cu))
7297     return dwarf2_compute_name (name, die, cu, 1);
7298
7299   back_to = make_cleanup (null_cleanup, NULL);
7300
7301   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7302   if (!attr)
7303     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7304
7305   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7306      has computed.  */
7307   if (attr && DW_STRING (attr))
7308     {
7309       char *demangled;
7310
7311       mangled = DW_STRING (attr);
7312
7313       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7314          type.  It is easier for GDB users to search for such functions as
7315          `name(params)' than `long name(params)'.  In such case the minimal
7316          symbol names do not match the full symbol names but for template
7317          functions there is never a need to look up their definition from their
7318          declaration so the only disadvantage remains the minimal symbol
7319          variant `long name(params)' does not have the proper inferior type.
7320          */
7321
7322       if (cu->language == language_go)
7323         {
7324           /* This is a lie, but we already lie to the caller new_symbol_full.
7325              new_symbol_full assumes we return the mangled name.
7326              This just undoes that lie until things are cleaned up.  */
7327           demangled = NULL;
7328         }
7329       else
7330         {
7331           demangled = cplus_demangle (mangled,
7332                                       (DMGL_PARAMS | DMGL_ANSI
7333                                        | (cu->language == language_java
7334                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7335                                           : DMGL_RET_DROP)));
7336         }
7337       if (demangled)
7338         {
7339           make_cleanup (xfree, demangled);
7340           canon = demangled;
7341         }
7342       else
7343         {
7344           canon = mangled;
7345           need_copy = 0;
7346         }
7347     }
7348
7349   if (canon == NULL || check_physname)
7350     {
7351       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7352
7353       if (canon != NULL && strcmp (physname, canon) != 0)
7354         {
7355           /* It may not mean a bug in GDB.  The compiler could also
7356              compute DW_AT_linkage_name incorrectly.  But in such case
7357              GDB would need to be bug-to-bug compatible.  */
7358
7359           complaint (&symfile_complaints,
7360                      _("Computed physname <%s> does not match demangled <%s> "
7361                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7362                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7363
7364           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7365              is available here - over computed PHYSNAME.  It is safer
7366              against both buggy GDB and buggy compilers.  */
7367
7368           retval = canon;
7369         }
7370       else
7371         {
7372           retval = physname;
7373           need_copy = 0;
7374         }
7375     }
7376   else
7377     retval = canon;
7378
7379   if (need_copy)
7380     retval = obsavestring (retval, strlen (retval),
7381                            &objfile->objfile_obstack);
7382
7383   do_cleanups (back_to);
7384   return retval;
7385 }
7386
7387 /* Read the import statement specified by the given die and record it.  */
7388
7389 static void
7390 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7391 {
7392   struct objfile *objfile = cu->objfile;
7393   struct attribute *import_attr;
7394   struct die_info *imported_die, *child_die;
7395   struct dwarf2_cu *imported_cu;
7396   const char *imported_name;
7397   const char *imported_name_prefix;
7398   const char *canonical_name;
7399   const char *import_alias;
7400   const char *imported_declaration = NULL;
7401   const char *import_prefix;
7402   VEC (const_char_ptr) *excludes = NULL;
7403   struct cleanup *cleanups;
7404
7405   char *temp;
7406
7407   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7408   if (import_attr == NULL)
7409     {
7410       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7411                  dwarf_tag_name (die->tag));
7412       return;
7413     }
7414
7415   imported_cu = cu;
7416   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7417   imported_name = dwarf2_name (imported_die, imported_cu);
7418   if (imported_name == NULL)
7419     {
7420       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7421
7422         The import in the following code:
7423         namespace A
7424           {
7425             typedef int B;
7426           }
7427
7428         int main ()
7429           {
7430             using A::B;
7431             B b;
7432             return b;
7433           }
7434
7435         ...
7436          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7437             <52>   DW_AT_decl_file   : 1
7438             <53>   DW_AT_decl_line   : 6
7439             <54>   DW_AT_import      : <0x75>
7440          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7441             <59>   DW_AT_name        : B
7442             <5b>   DW_AT_decl_file   : 1
7443             <5c>   DW_AT_decl_line   : 2
7444             <5d>   DW_AT_type        : <0x6e>
7445         ...
7446          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7447             <76>   DW_AT_byte_size   : 4
7448             <77>   DW_AT_encoding    : 5        (signed)
7449
7450         imports the wrong die ( 0x75 instead of 0x58 ).
7451         This case will be ignored until the gcc bug is fixed.  */
7452       return;
7453     }
7454
7455   /* Figure out the local name after import.  */
7456   import_alias = dwarf2_name (die, cu);
7457
7458   /* Figure out where the statement is being imported to.  */
7459   import_prefix = determine_prefix (die, cu);
7460
7461   /* Figure out what the scope of the imported die is and prepend it
7462      to the name of the imported die.  */
7463   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7464
7465   if (imported_die->tag != DW_TAG_namespace
7466       && imported_die->tag != DW_TAG_module)
7467     {
7468       imported_declaration = imported_name;
7469       canonical_name = imported_name_prefix;
7470     }
7471   else if (strlen (imported_name_prefix) > 0)
7472     {
7473       temp = alloca (strlen (imported_name_prefix)
7474                      + 2 + strlen (imported_name) + 1);
7475       strcpy (temp, imported_name_prefix);
7476       strcat (temp, "::");
7477       strcat (temp, imported_name);
7478       canonical_name = temp;
7479     }
7480   else
7481     canonical_name = imported_name;
7482
7483   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7484
7485   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7486     for (child_die = die->child; child_die && child_die->tag;
7487          child_die = sibling_die (child_die))
7488       {
7489         /* DWARF-4: A Fortran use statement with a “rename list” may be
7490            represented by an imported module entry with an import attribute
7491            referring to the module and owned entries corresponding to those
7492            entities that are renamed as part of being imported.  */
7493
7494         if (child_die->tag != DW_TAG_imported_declaration)
7495           {
7496             complaint (&symfile_complaints,
7497                        _("child DW_TAG_imported_declaration expected "
7498                          "- DIE at 0x%x [in module %s]"),
7499                        child_die->offset.sect_off, objfile->name);
7500             continue;
7501           }
7502
7503         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7504         if (import_attr == NULL)
7505           {
7506             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7507                        dwarf_tag_name (child_die->tag));
7508             continue;
7509           }
7510
7511         imported_cu = cu;
7512         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7513                                               &imported_cu);
7514         imported_name = dwarf2_name (imported_die, imported_cu);
7515         if (imported_name == NULL)
7516           {
7517             complaint (&symfile_complaints,
7518                        _("child DW_TAG_imported_declaration has unknown "
7519                          "imported name - DIE at 0x%x [in module %s]"),
7520                        child_die->offset.sect_off, objfile->name);
7521             continue;
7522           }
7523
7524         VEC_safe_push (const_char_ptr, excludes, imported_name);
7525
7526         process_die (child_die, cu);
7527       }
7528
7529   cp_add_using_directive (import_prefix,
7530                           canonical_name,
7531                           import_alias,
7532                           imported_declaration,
7533                           excludes,
7534                           &objfile->objfile_obstack);
7535
7536   do_cleanups (cleanups);
7537 }
7538
7539 /* Cleanup function for handle_DW_AT_stmt_list.  */
7540
7541 static void
7542 free_cu_line_header (void *arg)
7543 {
7544   struct dwarf2_cu *cu = arg;
7545
7546   free_line_header (cu->line_header);
7547   cu->line_header = NULL;
7548 }
7549
7550 static void
7551 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7552                          char **name, char **comp_dir)
7553 {
7554   struct attribute *attr;
7555
7556   *name = NULL;
7557   *comp_dir = NULL;
7558
7559   /* Find the filename.  Do not use dwarf2_name here, since the filename
7560      is not a source language identifier.  */
7561   attr = dwarf2_attr (die, DW_AT_name, cu);
7562   if (attr)
7563     {
7564       *name = DW_STRING (attr);
7565     }
7566
7567   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7568   if (attr)
7569     *comp_dir = DW_STRING (attr);
7570   else if (*name != NULL && IS_ABSOLUTE_PATH (*name))
7571     {
7572       *comp_dir = ldirname (*name);
7573       if (*comp_dir != NULL)
7574         make_cleanup (xfree, *comp_dir);
7575     }
7576   if (*comp_dir != NULL)
7577     {
7578       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7579          directory, get rid of it.  */
7580       char *cp = strchr (*comp_dir, ':');
7581
7582       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7583         *comp_dir = cp + 1;
7584     }
7585
7586   if (*name == NULL)
7587     *name = "<unknown>";
7588 }
7589
7590 /* Handle DW_AT_stmt_list for a compilation unit.
7591    DIE is the DW_TAG_compile_unit die for CU.
7592    COMP_DIR is the compilation directory.
7593    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7594
7595 static void
7596 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7597                         const char *comp_dir)
7598 {
7599   struct attribute *attr;
7600
7601   gdb_assert (! cu->per_cu->is_debug_types);
7602
7603   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7604   if (attr)
7605     {
7606       unsigned int line_offset = DW_UNSND (attr);
7607       struct line_header *line_header
7608         = dwarf_decode_line_header (line_offset, cu);
7609
7610       if (line_header)
7611         {
7612           cu->line_header = line_header;
7613           make_cleanup (free_cu_line_header, cu);
7614           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7615         }
7616     }
7617 }
7618
7619 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7620
7621 static void
7622 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7623 {
7624   struct objfile *objfile = dwarf2_per_objfile->objfile;
7625   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7626   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7627   CORE_ADDR highpc = ((CORE_ADDR) 0);
7628   struct attribute *attr;
7629   char *name = NULL;
7630   char *comp_dir = NULL;
7631   struct die_info *child_die;
7632   bfd *abfd = objfile->obfd;
7633   CORE_ADDR baseaddr;
7634
7635   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7636
7637   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7638
7639   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7640      from finish_block.  */
7641   if (lowpc == ((CORE_ADDR) -1))
7642     lowpc = highpc;
7643   lowpc += baseaddr;
7644   highpc += baseaddr;
7645
7646   find_file_and_directory (die, cu, &name, &comp_dir);
7647
7648   prepare_one_comp_unit (cu, die, cu->language);
7649
7650   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7651      standardised yet.  As a workaround for the language detection we fall
7652      back to the DW_AT_producer string.  */
7653   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7654     cu->language = language_opencl;
7655
7656   /* Similar hack for Go.  */
7657   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
7658     set_cu_language (DW_LANG_Go, cu);
7659
7660   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
7661
7662   /* Decode line number information if present.  We do this before
7663      processing child DIEs, so that the line header table is available
7664      for DW_AT_decl_file.  */
7665   handle_DW_AT_stmt_list (die, cu, comp_dir);
7666
7667   /* Process all dies in compilation unit.  */
7668   if (die->child != NULL)
7669     {
7670       child_die = die->child;
7671       while (child_die && child_die->tag)
7672         {
7673           process_die (child_die, cu);
7674           child_die = sibling_die (child_die);
7675         }
7676     }
7677
7678   /* Decode macro information, if present.  Dwarf 2 macro information
7679      refers to information in the line number info statement program
7680      header, so we can only read it if we've read the header
7681      successfully.  */
7682   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
7683   if (attr && cu->line_header)
7684     {
7685       if (dwarf2_attr (die, DW_AT_macro_info, cu))
7686         complaint (&symfile_complaints,
7687                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
7688
7689       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
7690     }
7691   else
7692     {
7693       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
7694       if (attr && cu->line_header)
7695         {
7696           unsigned int macro_offset = DW_UNSND (attr);
7697
7698           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
7699         }
7700     }
7701
7702   do_cleanups (back_to);
7703 }
7704
7705 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
7706    Create the set of symtabs used by this TU, or if this TU is sharing
7707    symtabs with another TU and the symtabs have already been created
7708    then restore those symtabs in the line header.
7709    We don't need the pc/line-number mapping for type units.  */
7710
7711 static void
7712 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
7713 {
7714   struct objfile *objfile = dwarf2_per_objfile->objfile;
7715   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7716   struct type_unit_group *tu_group;
7717   int first_time;
7718   struct line_header *lh;
7719   struct attribute *attr;
7720   unsigned int i, line_offset;
7721
7722   gdb_assert (per_cu->is_debug_types);
7723
7724   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7725
7726   /* If we're using .gdb_index (includes -readnow) then
7727      per_cu->s.type_unit_group may not have been set up yet.  */
7728   if (per_cu->s.type_unit_group == NULL)
7729     per_cu->s.type_unit_group = get_type_unit_group (cu, attr);
7730   tu_group = per_cu->s.type_unit_group;
7731
7732   /* If we've already processed this stmt_list there's no real need to
7733      do it again, we could fake it and just recreate the part we need
7734      (file name,index -> symtab mapping).  If data shows this optimization
7735      is useful we can do it then.  */
7736   first_time = tu_group->primary_symtab == NULL;
7737
7738   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
7739      debug info.  */
7740   lh = NULL;
7741   if (attr != NULL)
7742     {
7743       line_offset = DW_UNSND (attr);
7744       lh = dwarf_decode_line_header (line_offset, cu);
7745     }
7746   if (lh == NULL)
7747     {
7748       if (first_time)
7749         dwarf2_start_symtab (cu, "", NULL, 0);
7750       else
7751         {
7752           gdb_assert (tu_group->symtabs == NULL);
7753           restart_symtab (0);
7754         }
7755       /* Note: The primary symtab will get allocated at the end.  */
7756       return;
7757     }
7758
7759   cu->line_header = lh;
7760   make_cleanup (free_cu_line_header, cu);
7761
7762   if (first_time)
7763     {
7764       dwarf2_start_symtab (cu, "", NULL, 0);
7765
7766       tu_group->num_symtabs = lh->num_file_names;
7767       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
7768
7769       for (i = 0; i < lh->num_file_names; ++i)
7770         {
7771           char *dir = NULL;
7772           struct file_entry *fe = &lh->file_names[i];
7773
7774           if (fe->dir_index)
7775             dir = lh->include_dirs[fe->dir_index - 1];
7776           dwarf2_start_subfile (fe->name, dir, NULL);
7777
7778           /* Note: We don't have to watch for the main subfile here, type units
7779              don't have DW_AT_name.  */
7780
7781           if (current_subfile->symtab == NULL)
7782             {
7783               /* NOTE: start_subfile will recognize when it's been passed
7784                  a file it has already seen.  So we can't assume there's a
7785                  simple mapping from lh->file_names to subfiles,
7786                  lh->file_names may contain dups.  */
7787               current_subfile->symtab = allocate_symtab (current_subfile->name,
7788                                                          objfile);
7789             }
7790
7791           fe->symtab = current_subfile->symtab;
7792           tu_group->symtabs[i] = fe->symtab;
7793         }
7794     }
7795   else
7796     {
7797       restart_symtab (0);
7798
7799       for (i = 0; i < lh->num_file_names; ++i)
7800         {
7801           struct file_entry *fe = &lh->file_names[i];
7802
7803           fe->symtab = tu_group->symtabs[i];
7804         }
7805     }
7806
7807   /* The main symtab is allocated last.  Type units don't have DW_AT_name
7808      so they don't have a "real" (so to speak) symtab anyway.
7809      There is later code that will assign the main symtab to all symbols
7810      that don't have one.  We need to handle the case of a symbol with a
7811      missing symtab (DW_AT_decl_file) anyway.  */
7812 }
7813
7814 /* Process DW_TAG_type_unit.
7815    For TUs we want to skip the first top level sibling if it's not the
7816    actual type being defined by this TU.  In this case the first top
7817    level sibling is there to provide context only.  */
7818
7819 static void
7820 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
7821 {
7822   struct die_info *child_die;
7823
7824   prepare_one_comp_unit (cu, die, language_minimal);
7825
7826   /* Initialize (or reinitialize) the machinery for building symtabs.
7827      We do this before processing child DIEs, so that the line header table
7828      is available for DW_AT_decl_file.  */
7829   setup_type_unit_groups (die, cu);
7830
7831   if (die->child != NULL)
7832     {
7833       child_die = die->child;
7834       while (child_die && child_die->tag)
7835         {
7836           process_die (child_die, cu);
7837           child_die = sibling_die (child_die);
7838         }
7839     }
7840 }
7841 \f
7842 /* DWO files.  */
7843
7844 static hashval_t
7845 hash_dwo_file (const void *item)
7846 {
7847   const struct dwo_file *dwo_file = item;
7848
7849   return htab_hash_string (dwo_file->dwo_name);
7850 }
7851
7852 static int
7853 eq_dwo_file (const void *item_lhs, const void *item_rhs)
7854 {
7855   const struct dwo_file *lhs = item_lhs;
7856   const struct dwo_file *rhs = item_rhs;
7857
7858   return strcmp (lhs->dwo_name, rhs->dwo_name) == 0;
7859 }
7860
7861 /* Allocate a hash table for DWO files.  */
7862
7863 static htab_t
7864 allocate_dwo_file_hash_table (void)
7865 {
7866   struct objfile *objfile = dwarf2_per_objfile->objfile;
7867
7868   return htab_create_alloc_ex (41,
7869                                hash_dwo_file,
7870                                eq_dwo_file,
7871                                NULL,
7872                                &objfile->objfile_obstack,
7873                                hashtab_obstack_allocate,
7874                                dummy_obstack_deallocate);
7875 }
7876
7877 static hashval_t
7878 hash_dwo_unit (const void *item)
7879 {
7880   const struct dwo_unit *dwo_unit = item;
7881
7882   /* This drops the top 32 bits of the id, but is ok for a hash.  */
7883   return dwo_unit->signature;
7884 }
7885
7886 static int
7887 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
7888 {
7889   const struct dwo_unit *lhs = item_lhs;
7890   const struct dwo_unit *rhs = item_rhs;
7891
7892   /* The signature is assumed to be unique within the DWO file.
7893      So while object file CU dwo_id's always have the value zero,
7894      that's OK, assuming each object file DWO file has only one CU,
7895      and that's the rule for now.  */
7896   return lhs->signature == rhs->signature;
7897 }
7898
7899 /* Allocate a hash table for DWO CUs,TUs.
7900    There is one of these tables for each of CUs,TUs for each DWO file.  */
7901
7902 static htab_t
7903 allocate_dwo_unit_table (struct objfile *objfile)
7904 {
7905   /* Start out with a pretty small number.
7906      Generally DWO files contain only one CU and maybe some TUs.  */
7907   return htab_create_alloc_ex (3,
7908                                hash_dwo_unit,
7909                                eq_dwo_unit,
7910                                NULL,
7911                                &objfile->objfile_obstack,
7912                                hashtab_obstack_allocate,
7913                                dummy_obstack_deallocate);
7914 }
7915
7916 /* This function is mapped across the sections and remembers the offset and
7917    size of each of the DWO debugging sections we are interested in.  */
7918
7919 static void
7920 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_file_ptr)
7921 {
7922   struct dwo_file *dwo_file = dwo_file_ptr;
7923   const struct dwo_section_names *names = &dwo_section_names;
7924
7925   if (section_is_p (sectp->name, &names->abbrev_dwo))
7926     {
7927       dwo_file->sections.abbrev.asection = sectp;
7928       dwo_file->sections.abbrev.size = bfd_get_section_size (sectp);
7929     }
7930   else if (section_is_p (sectp->name, &names->info_dwo))
7931     {
7932       dwo_file->sections.info.asection = sectp;
7933       dwo_file->sections.info.size = bfd_get_section_size (sectp);
7934     }
7935   else if (section_is_p (sectp->name, &names->line_dwo))
7936     {
7937       dwo_file->sections.line.asection = sectp;
7938       dwo_file->sections.line.size = bfd_get_section_size (sectp);
7939     }
7940   else if (section_is_p (sectp->name, &names->loc_dwo))
7941     {
7942       dwo_file->sections.loc.asection = sectp;
7943       dwo_file->sections.loc.size = bfd_get_section_size (sectp);
7944     }
7945   else if (section_is_p (sectp->name, &names->macinfo_dwo))
7946     {
7947       dwo_file->sections.macinfo.asection = sectp;
7948       dwo_file->sections.macinfo.size = bfd_get_section_size (sectp);
7949     }
7950   else if (section_is_p (sectp->name, &names->macro_dwo))
7951     {
7952       dwo_file->sections.macro.asection = sectp;
7953       dwo_file->sections.macro.size = bfd_get_section_size (sectp);
7954     }
7955   else if (section_is_p (sectp->name, &names->str_dwo))
7956     {
7957       dwo_file->sections.str.asection = sectp;
7958       dwo_file->sections.str.size = bfd_get_section_size (sectp);
7959     }
7960   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
7961     {
7962       dwo_file->sections.str_offsets.asection = sectp;
7963       dwo_file->sections.str_offsets.size = bfd_get_section_size (sectp);
7964     }
7965   else if (section_is_p (sectp->name, &names->types_dwo))
7966     {
7967       struct dwarf2_section_info type_section;
7968
7969       memset (&type_section, 0, sizeof (type_section));
7970       type_section.asection = sectp;
7971       type_section.size = bfd_get_section_size (sectp);
7972       VEC_safe_push (dwarf2_section_info_def, dwo_file->sections.types,
7973                      &type_section);
7974     }
7975 }
7976
7977 /* Structure used to pass data to create_debug_info_hash_table_reader.  */
7978
7979 struct create_dwo_info_table_data
7980 {
7981   struct dwo_file *dwo_file;
7982   htab_t cu_htab;
7983 };
7984
7985 /* die_reader_func for create_debug_info_hash_table.  */
7986
7987 static void
7988 create_debug_info_hash_table_reader (const struct die_reader_specs *reader,
7989                                      gdb_byte *info_ptr,
7990                                      struct die_info *comp_unit_die,
7991                                      int has_children,
7992                                      void *datap)
7993 {
7994   struct dwarf2_cu *cu = reader->cu;
7995   struct objfile *objfile = dwarf2_per_objfile->objfile;
7996   sect_offset offset = cu->per_cu->offset;
7997   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
7998   struct create_dwo_info_table_data *data = datap;
7999   struct dwo_file *dwo_file = data->dwo_file;
8000   htab_t cu_htab = data->cu_htab;
8001   void **slot;
8002   struct attribute *attr;
8003   struct dwo_unit *dwo_unit;
8004
8005   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8006   if (attr == NULL)
8007     {
8008       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8009                " its dwo_id [in module %s]"),
8010              offset.sect_off, dwo_file->dwo_name);
8011       return;
8012     }
8013
8014   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8015   dwo_unit->dwo_file = dwo_file;
8016   dwo_unit->signature = DW_UNSND (attr);
8017   dwo_unit->info_or_types_section = section;
8018   dwo_unit->offset = offset;
8019   dwo_unit->length = cu->per_cu->length;
8020
8021   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8022   gdb_assert (slot != NULL);
8023   if (*slot != NULL)
8024     {
8025       const struct dwo_unit *dup_dwo_unit = *slot;
8026
8027       complaint (&symfile_complaints,
8028                  _("debug entry at offset 0x%x is duplicate to the entry at"
8029                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8030                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8031                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8032                  dwo_file->dwo_name);
8033     }
8034   else
8035     *slot = dwo_unit;
8036
8037   if (dwarf2_read_debug)
8038     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8039                         offset.sect_off,
8040                         phex (dwo_unit->signature,
8041                               sizeof (dwo_unit->signature)));
8042 }
8043
8044 /* Create a hash table to map DWO IDs to their CU entry in .debug_info.dwo.  */
8045
8046 static htab_t
8047 create_debug_info_hash_table (struct dwo_file *dwo_file)
8048 {
8049   struct objfile *objfile = dwarf2_per_objfile->objfile;
8050   struct dwarf2_section_info *section = &dwo_file->sections.info;
8051   bfd *abfd;
8052   htab_t cu_htab;
8053   gdb_byte *info_ptr, *end_ptr;
8054   struct create_dwo_info_table_data create_dwo_info_table_data;
8055
8056   dwarf2_read_section (objfile, section);
8057   info_ptr = section->buffer;
8058
8059   if (info_ptr == NULL)
8060     return NULL;
8061
8062   /* We can't set abfd until now because the section may be empty or
8063      not present, in which case section->asection will be NULL.  */
8064   abfd = section->asection->owner;
8065
8066   if (dwarf2_read_debug)
8067     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8068                         bfd_get_filename (abfd));
8069
8070   cu_htab = allocate_dwo_unit_table (objfile);
8071
8072   create_dwo_info_table_data.dwo_file = dwo_file;
8073   create_dwo_info_table_data.cu_htab = cu_htab;
8074
8075   end_ptr = info_ptr + section->size;
8076   while (info_ptr < end_ptr)
8077     {
8078       struct dwarf2_per_cu_data per_cu;
8079
8080       memset (&per_cu, 0, sizeof (per_cu));
8081       per_cu.objfile = objfile;
8082       per_cu.is_debug_types = 0;
8083       per_cu.offset.sect_off = info_ptr - section->buffer;
8084       per_cu.info_or_types_section = section;
8085
8086       init_cutu_and_read_dies_no_follow (&per_cu,
8087                                          &dwo_file->sections.abbrev,
8088                                          dwo_file,
8089                                          create_debug_info_hash_table_reader,
8090                                          &create_dwo_info_table_data);
8091
8092       info_ptr += per_cu.length;
8093     }
8094
8095   return cu_htab;
8096 }
8097
8098 /* Subroutine of open_dwo_file to simplify it.
8099    Open the file specified by FILE_NAME and hand it off to BFD for
8100    preliminary analysis.  Return a newly initialized bfd *, which
8101    includes a canonicalized copy of FILE_NAME.
8102    In case of trouble, return NULL.
8103    NOTE: This function is derived from symfile_bfd_open.  */
8104
8105 static bfd *
8106 try_open_dwo_file (const char *file_name)
8107 {
8108   bfd *sym_bfd;
8109   int desc;
8110   char *absolute_name;
8111
8112   desc = openp (debug_file_directory, OPF_TRY_CWD_FIRST, file_name,
8113                 O_RDONLY | O_BINARY, &absolute_name);
8114   if (desc < 0)
8115     return NULL;
8116
8117   sym_bfd = bfd_fopen (absolute_name, gnutarget, FOPEN_RB, desc);
8118   if (!sym_bfd)
8119     {
8120       xfree (absolute_name);
8121       return NULL;
8122     }
8123   bfd_set_cacheable (sym_bfd, 1);
8124
8125   if (!bfd_check_format (sym_bfd, bfd_object))
8126     {
8127       bfd_close (sym_bfd); /* This also closes desc.  */
8128       xfree (absolute_name);
8129       return NULL;
8130     }
8131
8132   /* bfd_usrdata exists for applications and libbfd must not touch it.  */
8133   gdb_assert (bfd_usrdata (sym_bfd) == NULL);
8134
8135   return sym_bfd;
8136 }
8137
8138 /* Try to open DWO file DWO_NAME.
8139    COMP_DIR is the DW_AT_comp_dir attribute.
8140    The result is the bfd handle of the file.
8141    If there is a problem finding or opening the file, return NULL.
8142    Upon success, the canonicalized path of the file is stored in the bfd,
8143    same as symfile_bfd_open.  */
8144
8145 static bfd *
8146 open_dwo_file (const char *dwo_name, const char *comp_dir)
8147 {
8148   bfd *abfd;
8149
8150   if (IS_ABSOLUTE_PATH (dwo_name))
8151     return try_open_dwo_file (dwo_name);
8152
8153   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8154
8155   if (comp_dir != NULL)
8156     {
8157       char *path_to_try = concat (comp_dir, SLASH_STRING, dwo_name, NULL);
8158
8159       /* NOTE: If comp_dir is a relative path, this will also try the
8160          search path, which seems useful.  */
8161       abfd = try_open_dwo_file (path_to_try);
8162       xfree (path_to_try);
8163       if (abfd != NULL)
8164         return abfd;
8165     }
8166
8167   /* That didn't work, try debug-file-directory, which, despite its name,
8168      is a list of paths.  */
8169
8170   if (*debug_file_directory == '\0')
8171     return NULL;
8172
8173   return try_open_dwo_file (dwo_name);
8174 }
8175
8176 /* Initialize the use of the DWO file specified by DWO_NAME.  */
8177
8178 static struct dwo_file *
8179 init_dwo_file (const char *dwo_name, const char *comp_dir)
8180 {
8181   struct objfile *objfile = dwarf2_per_objfile->objfile;
8182   struct dwo_file *dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8183                                               struct dwo_file);
8184   bfd *abfd;
8185   struct cleanup *cleanups;
8186
8187   if (dwarf2_read_debug)
8188     fprintf_unfiltered (gdb_stdlog, "Reading DWO file %s:\n", dwo_name);
8189
8190   abfd = open_dwo_file (dwo_name, comp_dir);
8191   if (abfd == NULL)
8192     return NULL;
8193   dwo_file->dwo_name = dwo_name;
8194   dwo_file->dwo_bfd = abfd;
8195
8196   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8197
8198   bfd_map_over_sections (abfd, dwarf2_locate_dwo_sections, dwo_file);
8199
8200   dwo_file->cus = create_debug_info_hash_table (dwo_file);
8201
8202   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8203                                                  dwo_file->sections.types);
8204
8205   discard_cleanups (cleanups);
8206
8207   return dwo_file;
8208 }
8209
8210 /* Lookup DWO file DWO_NAME.  */
8211
8212 static struct dwo_file *
8213 lookup_dwo_file (char *dwo_name, const char *comp_dir)
8214 {
8215   struct dwo_file *dwo_file;
8216   struct dwo_file find_entry;
8217   void **slot;
8218
8219   if (dwarf2_per_objfile->dwo_files == NULL)
8220     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8221
8222   /* Have we already seen this DWO file?  */
8223   find_entry.dwo_name = dwo_name;
8224   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8225
8226   /* If not, read it in and build a table of the DWOs it contains.  */
8227   if (*slot == NULL)
8228     *slot = init_dwo_file (dwo_name, comp_dir);
8229
8230   /* NOTE: This will be NULL if unable to open the file.  */
8231   dwo_file = *slot;
8232
8233   return dwo_file;
8234 }
8235
8236 /* Lookup the DWO CU referenced from THIS_CU in DWO file DWO_NAME.
8237    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
8238    SIGNATURE is the "dwo_id" of the CU (for consistency we use the same
8239    nomenclature as TUs).
8240    The result is a pointer to the dwo_unit object or NULL if we didn't find it
8241    (dwo_id mismatch or couldn't find the DWO file).  */
8242
8243 static struct dwo_unit *
8244 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
8245                       char *dwo_name, const char *comp_dir,
8246                       ULONGEST signature)
8247 {
8248   struct objfile *objfile = dwarf2_per_objfile->objfile;
8249   struct dwo_file *dwo_file;
8250
8251   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
8252   if (dwo_file == NULL)
8253     return NULL;
8254
8255   /* Look up the DWO using its signature(dwo_id).  */
8256
8257   if (dwo_file->cus != NULL)
8258     {
8259       struct dwo_unit find_dwo_cu, *dwo_cu;
8260
8261       find_dwo_cu.signature = signature;
8262       dwo_cu = htab_find (dwo_file->cus, &find_dwo_cu);
8263
8264       if (dwo_cu != NULL)
8265         return dwo_cu;
8266     }
8267
8268   /* We didn't find it.  This must mean a dwo_id mismatch.  */
8269
8270   complaint (&symfile_complaints,
8271              _("Could not find DWO CU referenced by CU at offset 0x%x"
8272                " [in module %s]"),
8273              this_cu->offset.sect_off, objfile->name);
8274   return NULL;
8275 }
8276
8277 /* Lookup the DWO TU referenced from THIS_TU in DWO file DWO_NAME.
8278    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
8279    The result is a pointer to the dwo_unit object or NULL if we didn't find it
8280    (dwo_id mismatch or couldn't find the DWO file).  */
8281
8282 static struct dwo_unit *
8283 lookup_dwo_type_unit (struct signatured_type *this_tu,
8284                       char *dwo_name, const char *comp_dir)
8285 {
8286   struct objfile *objfile = dwarf2_per_objfile->objfile;
8287   struct dwo_file *dwo_file;
8288
8289   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
8290   if (dwo_file == NULL)
8291     return NULL;
8292
8293   /* Look up the DWO using its signature(dwo_id).  */
8294
8295   if (dwo_file->tus != NULL)
8296     {
8297       struct dwo_unit find_dwo_tu, *dwo_tu;
8298
8299       find_dwo_tu.signature = this_tu->signature;
8300       dwo_tu = htab_find (dwo_file->tus, &find_dwo_tu);
8301
8302       if (dwo_tu != NULL)
8303         return dwo_tu;
8304     }
8305
8306   /* We didn't find it.  This must mean a dwo_id mismatch.  */
8307
8308   complaint (&symfile_complaints,
8309              _("Could not find DWO TU referenced by TU at offset 0x%x"
8310                " [in module %s]"),
8311              this_tu->per_cu.offset.sect_off, objfile->name);
8312   return NULL;
8313 }
8314
8315 /* Free all resources associated with DWO_FILE.
8316    Close the DWO file and munmap the sections.
8317    All memory should be on the objfile obstack.  */
8318
8319 static void
8320 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
8321 {
8322   int ix;
8323   struct dwarf2_section_info *section;
8324
8325   gdb_assert (dwo_file->dwo_bfd != objfile->obfd);
8326   bfd_close (dwo_file->dwo_bfd);
8327
8328   munmap_section_buffer (&dwo_file->sections.abbrev);
8329   munmap_section_buffer (&dwo_file->sections.info);
8330   munmap_section_buffer (&dwo_file->sections.line);
8331   munmap_section_buffer (&dwo_file->sections.loc);
8332   munmap_section_buffer (&dwo_file->sections.str);
8333   munmap_section_buffer (&dwo_file->sections.str_offsets);
8334
8335   for (ix = 0;
8336        VEC_iterate (dwarf2_section_info_def, dwo_file->sections.types,
8337                     ix, section);
8338        ++ix)
8339     munmap_section_buffer (section);
8340
8341   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
8342 }
8343
8344 /* Wrapper for free_dwo_file for use in cleanups.  */
8345
8346 static void
8347 free_dwo_file_cleanup (void *arg)
8348 {
8349   struct dwo_file *dwo_file = (struct dwo_file *) arg;
8350   struct objfile *objfile = dwarf2_per_objfile->objfile;
8351
8352   free_dwo_file (dwo_file, objfile);
8353 }
8354
8355 /* Traversal function for free_dwo_files.  */
8356
8357 static int
8358 free_dwo_file_from_slot (void **slot, void *info)
8359 {
8360   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8361   struct objfile *objfile = (struct objfile *) info;
8362
8363   free_dwo_file (dwo_file, objfile);
8364
8365   return 1;
8366 }
8367
8368 /* Free all resources associated with DWO_FILES.  */
8369
8370 static void
8371 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
8372 {
8373   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
8374 }
8375 \f
8376 /* Read in various DIEs.  */
8377
8378 /* qsort helper for inherit_abstract_dies.  */
8379
8380 static int
8381 unsigned_int_compar (const void *ap, const void *bp)
8382 {
8383   unsigned int a = *(unsigned int *) ap;
8384   unsigned int b = *(unsigned int *) bp;
8385
8386   return (a > b) - (b > a);
8387 }
8388
8389 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
8390    Inherit only the children of the DW_AT_abstract_origin DIE not being
8391    already referenced by DW_AT_abstract_origin from the children of the
8392    current DIE.  */
8393
8394 static void
8395 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
8396 {
8397   struct die_info *child_die;
8398   unsigned die_children_count;
8399   /* CU offsets which were referenced by children of the current DIE.  */
8400   sect_offset *offsets;
8401   sect_offset *offsets_end, *offsetp;
8402   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
8403   struct die_info *origin_die;
8404   /* Iterator of the ORIGIN_DIE children.  */
8405   struct die_info *origin_child_die;
8406   struct cleanup *cleanups;
8407   struct attribute *attr;
8408   struct dwarf2_cu *origin_cu;
8409   struct pending **origin_previous_list_in_scope;
8410
8411   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
8412   if (!attr)
8413     return;
8414
8415   /* Note that following die references may follow to a die in a
8416      different cu.  */
8417
8418   origin_cu = cu;
8419   origin_die = follow_die_ref (die, attr, &origin_cu);
8420
8421   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
8422      symbols in.  */
8423   origin_previous_list_in_scope = origin_cu->list_in_scope;
8424   origin_cu->list_in_scope = cu->list_in_scope;
8425
8426   if (die->tag != origin_die->tag
8427       && !(die->tag == DW_TAG_inlined_subroutine
8428            && origin_die->tag == DW_TAG_subprogram))
8429     complaint (&symfile_complaints,
8430                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
8431                die->offset.sect_off, origin_die->offset.sect_off);
8432
8433   child_die = die->child;
8434   die_children_count = 0;
8435   while (child_die && child_die->tag)
8436     {
8437       child_die = sibling_die (child_die);
8438       die_children_count++;
8439     }
8440   offsets = xmalloc (sizeof (*offsets) * die_children_count);
8441   cleanups = make_cleanup (xfree, offsets);
8442
8443   offsets_end = offsets;
8444   child_die = die->child;
8445   while (child_die && child_die->tag)
8446     {
8447       /* For each CHILD_DIE, find the corresponding child of
8448          ORIGIN_DIE.  If there is more than one layer of
8449          DW_AT_abstract_origin, follow them all; there shouldn't be,
8450          but GCC versions at least through 4.4 generate this (GCC PR
8451          40573).  */
8452       struct die_info *child_origin_die = child_die;
8453       struct dwarf2_cu *child_origin_cu = cu;
8454
8455       while (1)
8456         {
8457           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
8458                               child_origin_cu);
8459           if (attr == NULL)
8460             break;
8461           child_origin_die = follow_die_ref (child_origin_die, attr,
8462                                              &child_origin_cu);
8463         }
8464
8465       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
8466          counterpart may exist.  */
8467       if (child_origin_die != child_die)
8468         {
8469           if (child_die->tag != child_origin_die->tag
8470               && !(child_die->tag == DW_TAG_inlined_subroutine
8471                    && child_origin_die->tag == DW_TAG_subprogram))
8472             complaint (&symfile_complaints,
8473                        _("Child DIE 0x%x and its abstract origin 0x%x have "
8474                          "different tags"), child_die->offset.sect_off,
8475                        child_origin_die->offset.sect_off);
8476           if (child_origin_die->parent != origin_die)
8477             complaint (&symfile_complaints,
8478                        _("Child DIE 0x%x and its abstract origin 0x%x have "
8479                          "different parents"), child_die->offset.sect_off,
8480                        child_origin_die->offset.sect_off);
8481           else
8482             *offsets_end++ = child_origin_die->offset;
8483         }
8484       child_die = sibling_die (child_die);
8485     }
8486   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
8487          unsigned_int_compar);
8488   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
8489     if (offsetp[-1].sect_off == offsetp->sect_off)
8490       complaint (&symfile_complaints,
8491                  _("Multiple children of DIE 0x%x refer "
8492                    "to DIE 0x%x as their abstract origin"),
8493                  die->offset.sect_off, offsetp->sect_off);
8494
8495   offsetp = offsets;
8496   origin_child_die = origin_die->child;
8497   while (origin_child_die && origin_child_die->tag)
8498     {
8499       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
8500       while (offsetp < offsets_end
8501              && offsetp->sect_off < origin_child_die->offset.sect_off)
8502         offsetp++;
8503       if (offsetp >= offsets_end
8504           || offsetp->sect_off > origin_child_die->offset.sect_off)
8505         {
8506           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
8507           process_die (origin_child_die, origin_cu);
8508         }
8509       origin_child_die = sibling_die (origin_child_die);
8510     }
8511   origin_cu->list_in_scope = origin_previous_list_in_scope;
8512
8513   do_cleanups (cleanups);
8514 }
8515
8516 static void
8517 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
8518 {
8519   struct objfile *objfile = cu->objfile;
8520   struct context_stack *new;
8521   CORE_ADDR lowpc;
8522   CORE_ADDR highpc;
8523   struct die_info *child_die;
8524   struct attribute *attr, *call_line, *call_file;
8525   char *name;
8526   CORE_ADDR baseaddr;
8527   struct block *block;
8528   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
8529   VEC (symbolp) *template_args = NULL;
8530   struct template_symbol *templ_func = NULL;
8531
8532   if (inlined_func)
8533     {
8534       /* If we do not have call site information, we can't show the
8535          caller of this inlined function.  That's too confusing, so
8536          only use the scope for local variables.  */
8537       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
8538       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
8539       if (call_line == NULL || call_file == NULL)
8540         {
8541           read_lexical_block_scope (die, cu);
8542           return;
8543         }
8544     }
8545
8546   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8547
8548   name = dwarf2_name (die, cu);
8549
8550   /* Ignore functions with missing or empty names.  These are actually
8551      illegal according to the DWARF standard.  */
8552   if (name == NULL)
8553     {
8554       complaint (&symfile_complaints,
8555                  _("missing name for subprogram DIE at %d"),
8556                  die->offset.sect_off);
8557       return;
8558     }
8559
8560   /* Ignore functions with missing or invalid low and high pc attributes.  */
8561   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
8562     {
8563       attr = dwarf2_attr (die, DW_AT_external, cu);
8564       if (!attr || !DW_UNSND (attr))
8565         complaint (&symfile_complaints,
8566                    _("cannot get low and high bounds "
8567                      "for subprogram DIE at %d"),
8568                    die->offset.sect_off);
8569       return;
8570     }
8571
8572   lowpc += baseaddr;
8573   highpc += baseaddr;
8574
8575   /* If we have any template arguments, then we must allocate a
8576      different sort of symbol.  */
8577   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
8578     {
8579       if (child_die->tag == DW_TAG_template_type_param
8580           || child_die->tag == DW_TAG_template_value_param)
8581         {
8582           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8583                                        struct template_symbol);
8584           templ_func->base.is_cplus_template_function = 1;
8585           break;
8586         }
8587     }
8588
8589   new = push_context (0, lowpc);
8590   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
8591                                (struct symbol *) templ_func);
8592
8593   /* If there is a location expression for DW_AT_frame_base, record
8594      it.  */
8595   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
8596   if (attr)
8597     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
8598        expression is being recorded directly in the function's symbol
8599        and not in a separate frame-base object.  I guess this hack is
8600        to avoid adding some sort of frame-base adjunct/annex to the
8601        function's symbol :-(.  The problem with doing this is that it
8602        results in a function symbol with a location expression that
8603        has nothing to do with the location of the function, ouch!  The
8604        relationship should be: a function's symbol has-a frame base; a
8605        frame-base has-a location expression.  */
8606     dwarf2_symbol_mark_computed (attr, new->name, cu);
8607
8608   cu->list_in_scope = &local_symbols;
8609
8610   if (die->child != NULL)
8611     {
8612       child_die = die->child;
8613       while (child_die && child_die->tag)
8614         {
8615           if (child_die->tag == DW_TAG_template_type_param
8616               || child_die->tag == DW_TAG_template_value_param)
8617             {
8618               struct symbol *arg = new_symbol (child_die, NULL, cu);
8619
8620               if (arg != NULL)
8621                 VEC_safe_push (symbolp, template_args, arg);
8622             }
8623           else
8624             process_die (child_die, cu);
8625           child_die = sibling_die (child_die);
8626         }
8627     }
8628
8629   inherit_abstract_dies (die, cu);
8630
8631   /* If we have a DW_AT_specification, we might need to import using
8632      directives from the context of the specification DIE.  See the
8633      comment in determine_prefix.  */
8634   if (cu->language == language_cplus
8635       && dwarf2_attr (die, DW_AT_specification, cu))
8636     {
8637       struct dwarf2_cu *spec_cu = cu;
8638       struct die_info *spec_die = die_specification (die, &spec_cu);
8639
8640       while (spec_die)
8641         {
8642           child_die = spec_die->child;
8643           while (child_die && child_die->tag)
8644             {
8645               if (child_die->tag == DW_TAG_imported_module)
8646                 process_die (child_die, spec_cu);
8647               child_die = sibling_die (child_die);
8648             }
8649
8650           /* In some cases, GCC generates specification DIEs that
8651              themselves contain DW_AT_specification attributes.  */
8652           spec_die = die_specification (spec_die, &spec_cu);
8653         }
8654     }
8655
8656   new = pop_context ();
8657   /* Make a block for the local symbols within.  */
8658   block = finish_block (new->name, &local_symbols, new->old_blocks,
8659                         lowpc, highpc, objfile);
8660
8661   /* For C++, set the block's scope.  */
8662   if (cu->language == language_cplus || cu->language == language_fortran)
8663     cp_set_block_scope (new->name, block, &objfile->objfile_obstack,
8664                         determine_prefix (die, cu),
8665                         processing_has_namespace_info);
8666
8667   /* If we have address ranges, record them.  */
8668   dwarf2_record_block_ranges (die, block, baseaddr, cu);
8669
8670   /* Attach template arguments to function.  */
8671   if (! VEC_empty (symbolp, template_args))
8672     {
8673       gdb_assert (templ_func != NULL);
8674
8675       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
8676       templ_func->template_arguments
8677         = obstack_alloc (&objfile->objfile_obstack,
8678                          (templ_func->n_template_arguments
8679                           * sizeof (struct symbol *)));
8680       memcpy (templ_func->template_arguments,
8681               VEC_address (symbolp, template_args),
8682               (templ_func->n_template_arguments * sizeof (struct symbol *)));
8683       VEC_free (symbolp, template_args);
8684     }
8685
8686   /* In C++, we can have functions nested inside functions (e.g., when
8687      a function declares a class that has methods).  This means that
8688      when we finish processing a function scope, we may need to go
8689      back to building a containing block's symbol lists.  */
8690   local_symbols = new->locals;
8691   param_symbols = new->params;
8692   using_directives = new->using_directives;
8693
8694   /* If we've finished processing a top-level function, subsequent
8695      symbols go in the file symbol list.  */
8696   if (outermost_context_p ())
8697     cu->list_in_scope = &file_symbols;
8698 }
8699
8700 /* Process all the DIES contained within a lexical block scope.  Start
8701    a new scope, process the dies, and then close the scope.  */
8702
8703 static void
8704 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
8705 {
8706   struct objfile *objfile = cu->objfile;
8707   struct context_stack *new;
8708   CORE_ADDR lowpc, highpc;
8709   struct die_info *child_die;
8710   CORE_ADDR baseaddr;
8711
8712   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8713
8714   /* Ignore blocks with missing or invalid low and high pc attributes.  */
8715   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
8716      as multiple lexical blocks?  Handling children in a sane way would
8717      be nasty.  Might be easier to properly extend generic blocks to
8718      describe ranges.  */
8719   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
8720     return;
8721   lowpc += baseaddr;
8722   highpc += baseaddr;
8723
8724   push_context (0, lowpc);
8725   if (die->child != NULL)
8726     {
8727       child_die = die->child;
8728       while (child_die && child_die->tag)
8729         {
8730           process_die (child_die, cu);
8731           child_die = sibling_die (child_die);
8732         }
8733     }
8734   new = pop_context ();
8735
8736   if (local_symbols != NULL || using_directives != NULL)
8737     {
8738       struct block *block
8739         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
8740                         highpc, objfile);
8741
8742       /* Note that recording ranges after traversing children, as we
8743          do here, means that recording a parent's ranges entails
8744          walking across all its children's ranges as they appear in
8745          the address map, which is quadratic behavior.
8746
8747          It would be nicer to record the parent's ranges before
8748          traversing its children, simply overriding whatever you find
8749          there.  But since we don't even decide whether to create a
8750          block until after we've traversed its children, that's hard
8751          to do.  */
8752       dwarf2_record_block_ranges (die, block, baseaddr, cu);
8753     }
8754   local_symbols = new->locals;
8755   using_directives = new->using_directives;
8756 }
8757
8758 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
8759
8760 static void
8761 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
8762 {
8763   struct objfile *objfile = cu->objfile;
8764   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8765   CORE_ADDR pc, baseaddr;
8766   struct attribute *attr;
8767   struct call_site *call_site, call_site_local;
8768   void **slot;
8769   int nparams;
8770   struct die_info *child_die;
8771
8772   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8773
8774   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
8775   if (!attr)
8776     {
8777       complaint (&symfile_complaints,
8778                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
8779                    "DIE 0x%x [in module %s]"),
8780                  die->offset.sect_off, objfile->name);
8781       return;
8782     }
8783   pc = DW_ADDR (attr) + baseaddr;
8784
8785   if (cu->call_site_htab == NULL)
8786     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
8787                                                NULL, &objfile->objfile_obstack,
8788                                                hashtab_obstack_allocate, NULL);
8789   call_site_local.pc = pc;
8790   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
8791   if (*slot != NULL)
8792     {
8793       complaint (&symfile_complaints,
8794                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
8795                    "DIE 0x%x [in module %s]"),
8796                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
8797       return;
8798     }
8799
8800   /* Count parameters at the caller.  */
8801
8802   nparams = 0;
8803   for (child_die = die->child; child_die && child_die->tag;
8804        child_die = sibling_die (child_die))
8805     {
8806       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
8807         {
8808           complaint (&symfile_complaints,
8809                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
8810                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
8811                      child_die->tag, child_die->offset.sect_off, objfile->name);
8812           continue;
8813         }
8814
8815       nparams++;
8816     }
8817
8818   call_site = obstack_alloc (&objfile->objfile_obstack,
8819                              (sizeof (*call_site)
8820                               + (sizeof (*call_site->parameter)
8821                                  * (nparams - 1))));
8822   *slot = call_site;
8823   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
8824   call_site->pc = pc;
8825
8826   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
8827     {
8828       struct die_info *func_die;
8829
8830       /* Skip also over DW_TAG_inlined_subroutine.  */
8831       for (func_die = die->parent;
8832            func_die && func_die->tag != DW_TAG_subprogram
8833            && func_die->tag != DW_TAG_subroutine_type;
8834            func_die = func_die->parent);
8835
8836       /* DW_AT_GNU_all_call_sites is a superset
8837          of DW_AT_GNU_all_tail_call_sites.  */
8838       if (func_die
8839           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
8840           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
8841         {
8842           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
8843              not complete.  But keep CALL_SITE for look ups via call_site_htab,
8844              both the initial caller containing the real return address PC and
8845              the final callee containing the current PC of a chain of tail
8846              calls do not need to have the tail call list complete.  But any
8847              function candidate for a virtual tail call frame searched via
8848              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
8849              determined unambiguously.  */
8850         }
8851       else
8852         {
8853           struct type *func_type = NULL;
8854
8855           if (func_die)
8856             func_type = get_die_type (func_die, cu);
8857           if (func_type != NULL)
8858             {
8859               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
8860
8861               /* Enlist this call site to the function.  */
8862               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
8863               TYPE_TAIL_CALL_LIST (func_type) = call_site;
8864             }
8865           else
8866             complaint (&symfile_complaints,
8867                        _("Cannot find function owning DW_TAG_GNU_call_site "
8868                          "DIE 0x%x [in module %s]"),
8869                        die->offset.sect_off, objfile->name);
8870         }
8871     }
8872
8873   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
8874   if (attr == NULL)
8875     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
8876   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
8877   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
8878     /* Keep NULL DWARF_BLOCK.  */;
8879   else if (attr_form_is_block (attr))
8880     {
8881       struct dwarf2_locexpr_baton *dlbaton;
8882
8883       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
8884       dlbaton->data = DW_BLOCK (attr)->data;
8885       dlbaton->size = DW_BLOCK (attr)->size;
8886       dlbaton->per_cu = cu->per_cu;
8887
8888       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
8889     }
8890   else if (is_ref_attr (attr))
8891     {
8892       struct dwarf2_cu *target_cu = cu;
8893       struct die_info *target_die;
8894
8895       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
8896       gdb_assert (target_cu->objfile == objfile);
8897       if (die_is_declaration (target_die, target_cu))
8898         {
8899           const char *target_physname;
8900
8901           target_physname = dwarf2_physname (NULL, target_die, target_cu);
8902           if (target_physname == NULL)
8903             complaint (&symfile_complaints,
8904                        _("DW_AT_GNU_call_site_target target DIE has invalid "
8905                          "physname, for referencing DIE 0x%x [in module %s]"),
8906                        die->offset.sect_off, objfile->name);
8907           else
8908             SET_FIELD_PHYSNAME (call_site->target, (char *) target_physname);
8909         }
8910       else
8911         {
8912           CORE_ADDR lowpc;
8913
8914           /* DW_AT_entry_pc should be preferred.  */
8915           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
8916             complaint (&symfile_complaints,
8917                        _("DW_AT_GNU_call_site_target target DIE has invalid "
8918                          "low pc, for referencing DIE 0x%x [in module %s]"),
8919                        die->offset.sect_off, objfile->name);
8920           else
8921             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
8922         }
8923     }
8924   else
8925     complaint (&symfile_complaints,
8926                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
8927                  "block nor reference, for DIE 0x%x [in module %s]"),
8928                die->offset.sect_off, objfile->name);
8929
8930   call_site->per_cu = cu->per_cu;
8931
8932   for (child_die = die->child;
8933        child_die && child_die->tag;
8934        child_die = sibling_die (child_die))
8935     {
8936       struct call_site_parameter *parameter;
8937       struct attribute *loc, *origin;
8938
8939       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
8940         {
8941           /* Already printed the complaint above.  */
8942           continue;
8943         }
8944
8945       gdb_assert (call_site->parameter_count < nparams);
8946       parameter = &call_site->parameter[call_site->parameter_count];
8947
8948       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
8949          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
8950          register is contained in DW_AT_GNU_call_site_value.  */
8951
8952       loc = dwarf2_attr (child_die, DW_AT_location, cu);
8953       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
8954       if (loc == NULL && origin != NULL && is_ref_attr (origin))
8955         {
8956           sect_offset offset;
8957
8958           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
8959           offset = dwarf2_get_ref_die_offset (origin);
8960           if (!offset_in_cu_p (&cu->header, offset))
8961             {
8962               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
8963                  binding can be done only inside one CU.  Such referenced DIE
8964                  therefore cannot be even moved to DW_TAG_partial_unit.  */
8965               complaint (&symfile_complaints,
8966                          _("DW_AT_abstract_origin offset is not in CU for "
8967                            "DW_TAG_GNU_call_site child DIE 0x%x "
8968                            "[in module %s]"),
8969                          child_die->offset.sect_off, objfile->name);
8970               continue;
8971             }
8972           parameter->u.param_offset.cu_off = (offset.sect_off
8973                                               - cu->header.offset.sect_off);
8974         }
8975       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
8976         {
8977           complaint (&symfile_complaints,
8978                      _("No DW_FORM_block* DW_AT_location for "
8979                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
8980                      child_die->offset.sect_off, objfile->name);
8981           continue;
8982         }
8983       else
8984         {
8985           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
8986             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
8987           if (parameter->u.dwarf_reg != -1)
8988             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
8989           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
8990                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
8991                                              &parameter->u.fb_offset))
8992             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
8993           else
8994             {
8995               complaint (&symfile_complaints,
8996                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
8997                            "for DW_FORM_block* DW_AT_location is supported for "
8998                            "DW_TAG_GNU_call_site child DIE 0x%x "
8999                            "[in module %s]"),
9000                          child_die->offset.sect_off, objfile->name);
9001               continue;
9002             }
9003         }
9004
9005       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
9006       if (!attr_form_is_block (attr))
9007         {
9008           complaint (&symfile_complaints,
9009                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
9010                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9011                      child_die->offset.sect_off, objfile->name);
9012           continue;
9013         }
9014       parameter->value = DW_BLOCK (attr)->data;
9015       parameter->value_size = DW_BLOCK (attr)->size;
9016
9017       /* Parameters are not pre-cleared by memset above.  */
9018       parameter->data_value = NULL;
9019       parameter->data_value_size = 0;
9020       call_site->parameter_count++;
9021
9022       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
9023       if (attr)
9024         {
9025           if (!attr_form_is_block (attr))
9026             complaint (&symfile_complaints,
9027                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
9028                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9029                        child_die->offset.sect_off, objfile->name);
9030           else
9031             {
9032               parameter->data_value = DW_BLOCK (attr)->data;
9033               parameter->data_value_size = DW_BLOCK (attr)->size;
9034             }
9035         }
9036     }
9037 }
9038
9039 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
9040    Return 1 if the attributes are present and valid, otherwise, return 0.
9041    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
9042
9043 static int
9044 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
9045                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
9046                     struct partial_symtab *ranges_pst)
9047 {
9048   struct objfile *objfile = cu->objfile;
9049   struct comp_unit_head *cu_header = &cu->header;
9050   bfd *obfd = objfile->obfd;
9051   unsigned int addr_size = cu_header->addr_size;
9052   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9053   /* Base address selection entry.  */
9054   CORE_ADDR base;
9055   int found_base;
9056   unsigned int dummy;
9057   gdb_byte *buffer;
9058   CORE_ADDR marker;
9059   int low_set;
9060   CORE_ADDR low = 0;
9061   CORE_ADDR high = 0;
9062   CORE_ADDR baseaddr;
9063
9064   found_base = cu->base_known;
9065   base = cu->base_address;
9066
9067   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
9068   if (offset >= dwarf2_per_objfile->ranges.size)
9069     {
9070       complaint (&symfile_complaints,
9071                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
9072                  offset);
9073       return 0;
9074     }
9075   buffer = dwarf2_per_objfile->ranges.buffer + offset;
9076
9077   /* Read in the largest possible address.  */
9078   marker = read_address (obfd, buffer, cu, &dummy);
9079   if ((marker & mask) == mask)
9080     {
9081       /* If we found the largest possible address, then
9082          read the base address.  */
9083       base = read_address (obfd, buffer + addr_size, cu, &dummy);
9084       buffer += 2 * addr_size;
9085       offset += 2 * addr_size;
9086       found_base = 1;
9087     }
9088
9089   low_set = 0;
9090
9091   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9092
9093   while (1)
9094     {
9095       CORE_ADDR range_beginning, range_end;
9096
9097       range_beginning = read_address (obfd, buffer, cu, &dummy);
9098       buffer += addr_size;
9099       range_end = read_address (obfd, buffer, cu, &dummy);
9100       buffer += addr_size;
9101       offset += 2 * addr_size;
9102
9103       /* An end of list marker is a pair of zero addresses.  */
9104       if (range_beginning == 0 && range_end == 0)
9105         /* Found the end of list entry.  */
9106         break;
9107
9108       /* Each base address selection entry is a pair of 2 values.
9109          The first is the largest possible address, the second is
9110          the base address.  Check for a base address here.  */
9111       if ((range_beginning & mask) == mask)
9112         {
9113           /* If we found the largest possible address, then
9114              read the base address.  */
9115           base = read_address (obfd, buffer + addr_size, cu, &dummy);
9116           found_base = 1;
9117           continue;
9118         }
9119
9120       if (!found_base)
9121         {
9122           /* We have no valid base address for the ranges
9123              data.  */
9124           complaint (&symfile_complaints,
9125                      _("Invalid .debug_ranges data (no base address)"));
9126           return 0;
9127         }
9128
9129       if (range_beginning > range_end)
9130         {
9131           /* Inverted range entries are invalid.  */
9132           complaint (&symfile_complaints,
9133                      _("Invalid .debug_ranges data (inverted range)"));
9134           return 0;
9135         }
9136
9137       /* Empty range entries have no effect.  */
9138       if (range_beginning == range_end)
9139         continue;
9140
9141       range_beginning += base;
9142       range_end += base;
9143
9144       if (ranges_pst != NULL)
9145         addrmap_set_empty (objfile->psymtabs_addrmap,
9146                            range_beginning + baseaddr,
9147                            range_end - 1 + baseaddr,
9148                            ranges_pst);
9149
9150       /* FIXME: This is recording everything as a low-high
9151          segment of consecutive addresses.  We should have a
9152          data structure for discontiguous block ranges
9153          instead.  */
9154       if (! low_set)
9155         {
9156           low = range_beginning;
9157           high = range_end;
9158           low_set = 1;
9159         }
9160       else
9161         {
9162           if (range_beginning < low)
9163             low = range_beginning;
9164           if (range_end > high)
9165             high = range_end;
9166         }
9167     }
9168
9169   if (! low_set)
9170     /* If the first entry is an end-of-list marker, the range
9171        describes an empty scope, i.e. no instructions.  */
9172     return 0;
9173
9174   if (low_return)
9175     *low_return = low;
9176   if (high_return)
9177     *high_return = high;
9178   return 1;
9179 }
9180
9181 /* Get low and high pc attributes from a die.  Return 1 if the attributes
9182    are present and valid, otherwise, return 0.  Return -1 if the range is
9183    discontinuous, i.e. derived from DW_AT_ranges information.  */
9184
9185 static int
9186 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
9187                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
9188                       struct partial_symtab *pst)
9189 {
9190   struct attribute *attr;
9191   struct attribute *attr_high;
9192   CORE_ADDR low = 0;
9193   CORE_ADDR high = 0;
9194   int ret = 0;
9195
9196   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
9197   if (attr_high)
9198     {
9199       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9200       if (attr)
9201         {
9202           low = DW_ADDR (attr);
9203           if (attr_high->form == DW_FORM_addr
9204               || attr_high->form == DW_FORM_GNU_addr_index)
9205             high = DW_ADDR (attr_high);
9206           else
9207             high = low + DW_UNSND (attr_high);
9208         }
9209       else
9210         /* Found high w/o low attribute.  */
9211         return 0;
9212
9213       /* Found consecutive range of addresses.  */
9214       ret = 1;
9215     }
9216   else
9217     {
9218       attr = dwarf2_attr (die, DW_AT_ranges, cu);
9219       if (attr != NULL)
9220         {
9221           unsigned int ranges_offset = DW_UNSND (attr) + cu->ranges_base;
9222
9223           /* Value of the DW_AT_ranges attribute is the offset in the
9224              .debug_ranges section.  */
9225           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
9226             return 0;
9227           /* Found discontinuous range of addresses.  */
9228           ret = -1;
9229         }
9230     }
9231
9232   /* read_partial_die has also the strict LOW < HIGH requirement.  */
9233   if (high <= low)
9234     return 0;
9235
9236   /* When using the GNU linker, .gnu.linkonce. sections are used to
9237      eliminate duplicate copies of functions and vtables and such.
9238      The linker will arbitrarily choose one and discard the others.
9239      The AT_*_pc values for such functions refer to local labels in
9240      these sections.  If the section from that file was discarded, the
9241      labels are not in the output, so the relocs get a value of 0.
9242      If this is a discarded function, mark the pc bounds as invalid,
9243      so that GDB will ignore it.  */
9244   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
9245     return 0;
9246
9247   *lowpc = low;
9248   if (highpc)
9249     *highpc = high;
9250   return ret;
9251 }
9252
9253 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
9254    its low and high PC addresses.  Do nothing if these addresses could not
9255    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
9256    and HIGHPC to the high address if greater than HIGHPC.  */
9257
9258 static void
9259 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
9260                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
9261                                  struct dwarf2_cu *cu)
9262 {
9263   CORE_ADDR low, high;
9264   struct die_info *child = die->child;
9265
9266   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
9267     {
9268       *lowpc = min (*lowpc, low);
9269       *highpc = max (*highpc, high);
9270     }
9271
9272   /* If the language does not allow nested subprograms (either inside
9273      subprograms or lexical blocks), we're done.  */
9274   if (cu->language != language_ada)
9275     return;
9276
9277   /* Check all the children of the given DIE.  If it contains nested
9278      subprograms, then check their pc bounds.  Likewise, we need to
9279      check lexical blocks as well, as they may also contain subprogram
9280      definitions.  */
9281   while (child && child->tag)
9282     {
9283       if (child->tag == DW_TAG_subprogram
9284           || child->tag == DW_TAG_lexical_block)
9285         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
9286       child = sibling_die (child);
9287     }
9288 }
9289
9290 /* Get the low and high pc's represented by the scope DIE, and store
9291    them in *LOWPC and *HIGHPC.  If the correct values can't be
9292    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
9293
9294 static void
9295 get_scope_pc_bounds (struct die_info *die,
9296                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
9297                      struct dwarf2_cu *cu)
9298 {
9299   CORE_ADDR best_low = (CORE_ADDR) -1;
9300   CORE_ADDR best_high = (CORE_ADDR) 0;
9301   CORE_ADDR current_low, current_high;
9302
9303   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
9304     {
9305       best_low = current_low;
9306       best_high = current_high;
9307     }
9308   else
9309     {
9310       struct die_info *child = die->child;
9311
9312       while (child && child->tag)
9313         {
9314           switch (child->tag) {
9315           case DW_TAG_subprogram:
9316             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
9317             break;
9318           case DW_TAG_namespace:
9319           case DW_TAG_module:
9320             /* FIXME: carlton/2004-01-16: Should we do this for
9321                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
9322                that current GCC's always emit the DIEs corresponding
9323                to definitions of methods of classes as children of a
9324                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
9325                the DIEs giving the declarations, which could be
9326                anywhere).  But I don't see any reason why the
9327                standards says that they have to be there.  */
9328             get_scope_pc_bounds (child, &current_low, &current_high, cu);
9329
9330             if (current_low != ((CORE_ADDR) -1))
9331               {
9332                 best_low = min (best_low, current_low);
9333                 best_high = max (best_high, current_high);
9334               }
9335             break;
9336           default:
9337             /* Ignore.  */
9338             break;
9339           }
9340
9341           child = sibling_die (child);
9342         }
9343     }
9344
9345   *lowpc = best_low;
9346   *highpc = best_high;
9347 }
9348
9349 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
9350    in DIE.  */
9351
9352 static void
9353 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
9354                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
9355 {
9356   struct objfile *objfile = cu->objfile;
9357   struct attribute *attr;
9358   struct attribute *attr_high;
9359
9360   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
9361   if (attr_high)
9362     {
9363       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9364       if (attr)
9365         {
9366           CORE_ADDR low = DW_ADDR (attr);
9367           CORE_ADDR high;
9368           if (attr_high->form == DW_FORM_addr
9369               || attr_high->form == DW_FORM_GNU_addr_index)
9370             high = DW_ADDR (attr_high);
9371           else
9372             high = low + DW_UNSND (attr_high);
9373
9374           record_block_range (block, baseaddr + low, baseaddr + high - 1);
9375         }
9376     }
9377
9378   attr = dwarf2_attr (die, DW_AT_ranges, cu);
9379   if (attr)
9380     {
9381       bfd *obfd = objfile->obfd;
9382
9383       /* The value of the DW_AT_ranges attribute is the offset of the
9384          address range list in the .debug_ranges section.  */
9385       unsigned long offset = DW_UNSND (attr) + cu->ranges_base;
9386       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
9387
9388       /* For some target architectures, but not others, the
9389          read_address function sign-extends the addresses it returns.
9390          To recognize base address selection entries, we need a
9391          mask.  */
9392       unsigned int addr_size = cu->header.addr_size;
9393       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9394
9395       /* The base address, to which the next pair is relative.  Note
9396          that this 'base' is a DWARF concept: most entries in a range
9397          list are relative, to reduce the number of relocs against the
9398          debugging information.  This is separate from this function's
9399          'baseaddr' argument, which GDB uses to relocate debugging
9400          information from a shared library based on the address at
9401          which the library was loaded.  */
9402       CORE_ADDR base = cu->base_address;
9403       int base_known = cu->base_known;
9404
9405       gdb_assert (dwarf2_per_objfile->ranges.readin);
9406       if (offset >= dwarf2_per_objfile->ranges.size)
9407         {
9408           complaint (&symfile_complaints,
9409                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
9410                      offset);
9411           return;
9412         }
9413
9414       for (;;)
9415         {
9416           unsigned int bytes_read;
9417           CORE_ADDR start, end;
9418
9419           start = read_address (obfd, buffer, cu, &bytes_read);
9420           buffer += bytes_read;
9421           end = read_address (obfd, buffer, cu, &bytes_read);
9422           buffer += bytes_read;
9423
9424           /* Did we find the end of the range list?  */
9425           if (start == 0 && end == 0)
9426             break;
9427
9428           /* Did we find a base address selection entry?  */
9429           else if ((start & base_select_mask) == base_select_mask)
9430             {
9431               base = end;
9432               base_known = 1;
9433             }
9434
9435           /* We found an ordinary address range.  */
9436           else
9437             {
9438               if (!base_known)
9439                 {
9440                   complaint (&symfile_complaints,
9441                              _("Invalid .debug_ranges data "
9442                                "(no base address)"));
9443                   return;
9444                 }
9445
9446               if (start > end)
9447                 {
9448                   /* Inverted range entries are invalid.  */
9449                   complaint (&symfile_complaints,
9450                              _("Invalid .debug_ranges data "
9451                                "(inverted range)"));
9452                   return;
9453                 }
9454
9455               /* Empty range entries have no effect.  */
9456               if (start == end)
9457                 continue;
9458
9459               record_block_range (block,
9460                                   baseaddr + base + start,
9461                                   baseaddr + base + end - 1);
9462             }
9463         }
9464     }
9465 }
9466
9467 /* Check whether the producer field indicates either of GCC < 4.6, or the
9468    Intel C/C++ compiler, and cache the result in CU.  */
9469
9470 static void
9471 check_producer (struct dwarf2_cu *cu)
9472 {
9473   const char *cs;
9474   int major, minor, release;
9475
9476   if (cu->producer == NULL)
9477     {
9478       /* For unknown compilers expect their behavior is DWARF version
9479          compliant.
9480
9481          GCC started to support .debug_types sections by -gdwarf-4 since
9482          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
9483          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
9484          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
9485          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
9486     }
9487   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
9488     {
9489       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
9490
9491       cs = &cu->producer[strlen ("GNU ")];
9492       while (*cs && !isdigit (*cs))
9493         cs++;
9494       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
9495         {
9496           /* Not recognized as GCC.  */
9497         }
9498       else
9499         cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
9500     }
9501   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
9502     cu->producer_is_icc = 1;
9503   else
9504     {
9505       /* For other non-GCC compilers, expect their behavior is DWARF version
9506          compliant.  */
9507     }
9508
9509   cu->checked_producer = 1;
9510 }
9511
9512 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
9513    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
9514    during 4.6.0 experimental.  */
9515
9516 static int
9517 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
9518 {
9519   if (!cu->checked_producer)
9520     check_producer (cu);
9521
9522   return cu->producer_is_gxx_lt_4_6;
9523 }
9524
9525 /* Return the default accessibility type if it is not overriden by
9526    DW_AT_accessibility.  */
9527
9528 static enum dwarf_access_attribute
9529 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
9530 {
9531   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
9532     {
9533       /* The default DWARF 2 accessibility for members is public, the default
9534          accessibility for inheritance is private.  */
9535
9536       if (die->tag != DW_TAG_inheritance)
9537         return DW_ACCESS_public;
9538       else
9539         return DW_ACCESS_private;
9540     }
9541   else
9542     {
9543       /* DWARF 3+ defines the default accessibility a different way.  The same
9544          rules apply now for DW_TAG_inheritance as for the members and it only
9545          depends on the container kind.  */
9546
9547       if (die->parent->tag == DW_TAG_class_type)
9548         return DW_ACCESS_private;
9549       else
9550         return DW_ACCESS_public;
9551     }
9552 }
9553
9554 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
9555    offset.  If the attribute was not found return 0, otherwise return
9556    1.  If it was found but could not properly be handled, set *OFFSET
9557    to 0.  */
9558
9559 static int
9560 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
9561                              LONGEST *offset)
9562 {
9563   struct attribute *attr;
9564
9565   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
9566   if (attr != NULL)
9567     {
9568       *offset = 0;
9569
9570       /* Note that we do not check for a section offset first here.
9571          This is because DW_AT_data_member_location is new in DWARF 4,
9572          so if we see it, we can assume that a constant form is really
9573          a constant and not a section offset.  */
9574       if (attr_form_is_constant (attr))
9575         *offset = dwarf2_get_attr_constant_value (attr, 0);
9576       else if (attr_form_is_section_offset (attr))
9577         dwarf2_complex_location_expr_complaint ();
9578       else if (attr_form_is_block (attr))
9579         *offset = decode_locdesc (DW_BLOCK (attr), cu);
9580       else
9581         dwarf2_complex_location_expr_complaint ();
9582
9583       return 1;
9584     }
9585
9586   return 0;
9587 }
9588
9589 /* Add an aggregate field to the field list.  */
9590
9591 static void
9592 dwarf2_add_field (struct field_info *fip, struct die_info *die,
9593                   struct dwarf2_cu *cu)
9594 {
9595   struct objfile *objfile = cu->objfile;
9596   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9597   struct nextfield *new_field;
9598   struct attribute *attr;
9599   struct field *fp;
9600   char *fieldname = "";
9601
9602   /* Allocate a new field list entry and link it in.  */
9603   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
9604   make_cleanup (xfree, new_field);
9605   memset (new_field, 0, sizeof (struct nextfield));
9606
9607   if (die->tag == DW_TAG_inheritance)
9608     {
9609       new_field->next = fip->baseclasses;
9610       fip->baseclasses = new_field;
9611     }
9612   else
9613     {
9614       new_field->next = fip->fields;
9615       fip->fields = new_field;
9616     }
9617   fip->nfields++;
9618
9619   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
9620   if (attr)
9621     new_field->accessibility = DW_UNSND (attr);
9622   else
9623     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
9624   if (new_field->accessibility != DW_ACCESS_public)
9625     fip->non_public_fields = 1;
9626
9627   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
9628   if (attr)
9629     new_field->virtuality = DW_UNSND (attr);
9630   else
9631     new_field->virtuality = DW_VIRTUALITY_none;
9632
9633   fp = &new_field->field;
9634
9635   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
9636     {
9637       LONGEST offset;
9638
9639       /* Data member other than a C++ static data member.  */
9640
9641       /* Get type of field.  */
9642       fp->type = die_type (die, cu);
9643
9644       SET_FIELD_BITPOS (*fp, 0);
9645
9646       /* Get bit size of field (zero if none).  */
9647       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
9648       if (attr)
9649         {
9650           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
9651         }
9652       else
9653         {
9654           FIELD_BITSIZE (*fp) = 0;
9655         }
9656
9657       /* Get bit offset of field.  */
9658       if (handle_data_member_location (die, cu, &offset))
9659         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
9660       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
9661       if (attr)
9662         {
9663           if (gdbarch_bits_big_endian (gdbarch))
9664             {
9665               /* For big endian bits, the DW_AT_bit_offset gives the
9666                  additional bit offset from the MSB of the containing
9667                  anonymous object to the MSB of the field.  We don't
9668                  have to do anything special since we don't need to
9669                  know the size of the anonymous object.  */
9670               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
9671             }
9672           else
9673             {
9674               /* For little endian bits, compute the bit offset to the
9675                  MSB of the anonymous object, subtract off the number of
9676                  bits from the MSB of the field to the MSB of the
9677                  object, and then subtract off the number of bits of
9678                  the field itself.  The result is the bit offset of
9679                  the LSB of the field.  */
9680               int anonymous_size;
9681               int bit_offset = DW_UNSND (attr);
9682
9683               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9684               if (attr)
9685                 {
9686                   /* The size of the anonymous object containing
9687                      the bit field is explicit, so use the
9688                      indicated size (in bytes).  */
9689                   anonymous_size = DW_UNSND (attr);
9690                 }
9691               else
9692                 {
9693                   /* The size of the anonymous object containing
9694                      the bit field must be inferred from the type
9695                      attribute of the data member containing the
9696                      bit field.  */
9697                   anonymous_size = TYPE_LENGTH (fp->type);
9698                 }
9699               SET_FIELD_BITPOS (*fp,
9700                                 (FIELD_BITPOS (*fp)
9701                                  + anonymous_size * bits_per_byte
9702                                  - bit_offset - FIELD_BITSIZE (*fp)));
9703             }
9704         }
9705
9706       /* Get name of field.  */
9707       fieldname = dwarf2_name (die, cu);
9708       if (fieldname == NULL)
9709         fieldname = "";
9710
9711       /* The name is already allocated along with this objfile, so we don't
9712          need to duplicate it for the type.  */
9713       fp->name = fieldname;
9714
9715       /* Change accessibility for artificial fields (e.g. virtual table
9716          pointer or virtual base class pointer) to private.  */
9717       if (dwarf2_attr (die, DW_AT_artificial, cu))
9718         {
9719           FIELD_ARTIFICIAL (*fp) = 1;
9720           new_field->accessibility = DW_ACCESS_private;
9721           fip->non_public_fields = 1;
9722         }
9723     }
9724   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
9725     {
9726       /* C++ static member.  */
9727
9728       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
9729          is a declaration, but all versions of G++ as of this writing
9730          (so through at least 3.2.1) incorrectly generate
9731          DW_TAG_variable tags.  */
9732
9733       const char *physname;
9734
9735       /* Get name of field.  */
9736       fieldname = dwarf2_name (die, cu);
9737       if (fieldname == NULL)
9738         return;
9739
9740       attr = dwarf2_attr (die, DW_AT_const_value, cu);
9741       if (attr
9742           /* Only create a symbol if this is an external value.
9743              new_symbol checks this and puts the value in the global symbol
9744              table, which we want.  If it is not external, new_symbol
9745              will try to put the value in cu->list_in_scope which is wrong.  */
9746           && dwarf2_flag_true_p (die, DW_AT_external, cu))
9747         {
9748           /* A static const member, not much different than an enum as far as
9749              we're concerned, except that we can support more types.  */
9750           new_symbol (die, NULL, cu);
9751         }
9752
9753       /* Get physical name.  */
9754       physname = dwarf2_physname (fieldname, die, cu);
9755
9756       /* The name is already allocated along with this objfile, so we don't
9757          need to duplicate it for the type.  */
9758       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
9759       FIELD_TYPE (*fp) = die_type (die, cu);
9760       FIELD_NAME (*fp) = fieldname;
9761     }
9762   else if (die->tag == DW_TAG_inheritance)
9763     {
9764       LONGEST offset;
9765
9766       /* C++ base class field.  */
9767       if (handle_data_member_location (die, cu, &offset))
9768         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
9769       FIELD_BITSIZE (*fp) = 0;
9770       FIELD_TYPE (*fp) = die_type (die, cu);
9771       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
9772       fip->nbaseclasses++;
9773     }
9774 }
9775
9776 /* Add a typedef defined in the scope of the FIP's class.  */
9777
9778 static void
9779 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
9780                     struct dwarf2_cu *cu)
9781 {
9782   struct objfile *objfile = cu->objfile;
9783   struct typedef_field_list *new_field;
9784   struct attribute *attr;
9785   struct typedef_field *fp;
9786   char *fieldname = "";
9787
9788   /* Allocate a new field list entry and link it in.  */
9789   new_field = xzalloc (sizeof (*new_field));
9790   make_cleanup (xfree, new_field);
9791
9792   gdb_assert (die->tag == DW_TAG_typedef);
9793
9794   fp = &new_field->field;
9795
9796   /* Get name of field.  */
9797   fp->name = dwarf2_name (die, cu);
9798   if (fp->name == NULL)
9799     return;
9800
9801   fp->type = read_type_die (die, cu);
9802
9803   new_field->next = fip->typedef_field_list;
9804   fip->typedef_field_list = new_field;
9805   fip->typedef_field_list_count++;
9806 }
9807
9808 /* Create the vector of fields, and attach it to the type.  */
9809
9810 static void
9811 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
9812                               struct dwarf2_cu *cu)
9813 {
9814   int nfields = fip->nfields;
9815
9816   /* Record the field count, allocate space for the array of fields,
9817      and create blank accessibility bitfields if necessary.  */
9818   TYPE_NFIELDS (type) = nfields;
9819   TYPE_FIELDS (type) = (struct field *)
9820     TYPE_ALLOC (type, sizeof (struct field) * nfields);
9821   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
9822
9823   if (fip->non_public_fields && cu->language != language_ada)
9824     {
9825       ALLOCATE_CPLUS_STRUCT_TYPE (type);
9826
9827       TYPE_FIELD_PRIVATE_BITS (type) =
9828         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
9829       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
9830
9831       TYPE_FIELD_PROTECTED_BITS (type) =
9832         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
9833       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
9834
9835       TYPE_FIELD_IGNORE_BITS (type) =
9836         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
9837       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
9838     }
9839
9840   /* If the type has baseclasses, allocate and clear a bit vector for
9841      TYPE_FIELD_VIRTUAL_BITS.  */
9842   if (fip->nbaseclasses && cu->language != language_ada)
9843     {
9844       int num_bytes = B_BYTES (fip->nbaseclasses);
9845       unsigned char *pointer;
9846
9847       ALLOCATE_CPLUS_STRUCT_TYPE (type);
9848       pointer = TYPE_ALLOC (type, num_bytes);
9849       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
9850       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
9851       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
9852     }
9853
9854   /* Copy the saved-up fields into the field vector.  Start from the head of
9855      the list, adding to the tail of the field array, so that they end up in
9856      the same order in the array in which they were added to the list.  */
9857   while (nfields-- > 0)
9858     {
9859       struct nextfield *fieldp;
9860
9861       if (fip->fields)
9862         {
9863           fieldp = fip->fields;
9864           fip->fields = fieldp->next;
9865         }
9866       else
9867         {
9868           fieldp = fip->baseclasses;
9869           fip->baseclasses = fieldp->next;
9870         }
9871
9872       TYPE_FIELD (type, nfields) = fieldp->field;
9873       switch (fieldp->accessibility)
9874         {
9875         case DW_ACCESS_private:
9876           if (cu->language != language_ada)
9877             SET_TYPE_FIELD_PRIVATE (type, nfields);
9878           break;
9879
9880         case DW_ACCESS_protected:
9881           if (cu->language != language_ada)
9882             SET_TYPE_FIELD_PROTECTED (type, nfields);
9883           break;
9884
9885         case DW_ACCESS_public:
9886           break;
9887
9888         default:
9889           /* Unknown accessibility.  Complain and treat it as public.  */
9890           {
9891             complaint (&symfile_complaints, _("unsupported accessibility %d"),
9892                        fieldp->accessibility);
9893           }
9894           break;
9895         }
9896       if (nfields < fip->nbaseclasses)
9897         {
9898           switch (fieldp->virtuality)
9899             {
9900             case DW_VIRTUALITY_virtual:
9901             case DW_VIRTUALITY_pure_virtual:
9902               if (cu->language == language_ada)
9903                 error (_("unexpected virtuality in component of Ada type"));
9904               SET_TYPE_FIELD_VIRTUAL (type, nfields);
9905               break;
9906             }
9907         }
9908     }
9909 }
9910
9911 /* Add a member function to the proper fieldlist.  */
9912
9913 static void
9914 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
9915                       struct type *type, struct dwarf2_cu *cu)
9916 {
9917   struct objfile *objfile = cu->objfile;
9918   struct attribute *attr;
9919   struct fnfieldlist *flp;
9920   int i;
9921   struct fn_field *fnp;
9922   char *fieldname;
9923   struct nextfnfield *new_fnfield;
9924   struct type *this_type;
9925   enum dwarf_access_attribute accessibility;
9926
9927   if (cu->language == language_ada)
9928     error (_("unexpected member function in Ada type"));
9929
9930   /* Get name of member function.  */
9931   fieldname = dwarf2_name (die, cu);
9932   if (fieldname == NULL)
9933     return;
9934
9935   /* Look up member function name in fieldlist.  */
9936   for (i = 0; i < fip->nfnfields; i++)
9937     {
9938       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
9939         break;
9940     }
9941
9942   /* Create new list element if necessary.  */
9943   if (i < fip->nfnfields)
9944     flp = &fip->fnfieldlists[i];
9945   else
9946     {
9947       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
9948         {
9949           fip->fnfieldlists = (struct fnfieldlist *)
9950             xrealloc (fip->fnfieldlists,
9951                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
9952                       * sizeof (struct fnfieldlist));
9953           if (fip->nfnfields == 0)
9954             make_cleanup (free_current_contents, &fip->fnfieldlists);
9955         }
9956       flp = &fip->fnfieldlists[fip->nfnfields];
9957       flp->name = fieldname;
9958       flp->length = 0;
9959       flp->head = NULL;
9960       i = fip->nfnfields++;
9961     }
9962
9963   /* Create a new member function field and chain it to the field list
9964      entry.  */
9965   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
9966   make_cleanup (xfree, new_fnfield);
9967   memset (new_fnfield, 0, sizeof (struct nextfnfield));
9968   new_fnfield->next = flp->head;
9969   flp->head = new_fnfield;
9970   flp->length++;
9971
9972   /* Fill in the member function field info.  */
9973   fnp = &new_fnfield->fnfield;
9974
9975   /* Delay processing of the physname until later.  */
9976   if (cu->language == language_cplus || cu->language == language_java)
9977     {
9978       add_to_method_list (type, i, flp->length - 1, fieldname,
9979                           die, cu);
9980     }
9981   else
9982     {
9983       const char *physname = dwarf2_physname (fieldname, die, cu);
9984       fnp->physname = physname ? physname : "";
9985     }
9986
9987   fnp->type = alloc_type (objfile);
9988   this_type = read_type_die (die, cu);
9989   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
9990     {
9991       int nparams = TYPE_NFIELDS (this_type);
9992
9993       /* TYPE is the domain of this method, and THIS_TYPE is the type
9994            of the method itself (TYPE_CODE_METHOD).  */
9995       smash_to_method_type (fnp->type, type,
9996                             TYPE_TARGET_TYPE (this_type),
9997                             TYPE_FIELDS (this_type),
9998                             TYPE_NFIELDS (this_type),
9999                             TYPE_VARARGS (this_type));
10000
10001       /* Handle static member functions.
10002          Dwarf2 has no clean way to discern C++ static and non-static
10003          member functions.  G++ helps GDB by marking the first
10004          parameter for non-static member functions (which is the this
10005          pointer) as artificial.  We obtain this information from
10006          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
10007       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
10008         fnp->voffset = VOFFSET_STATIC;
10009     }
10010   else
10011     complaint (&symfile_complaints, _("member function type missing for '%s'"),
10012                dwarf2_full_name (fieldname, die, cu));
10013
10014   /* Get fcontext from DW_AT_containing_type if present.  */
10015   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10016     fnp->fcontext = die_containing_type (die, cu);
10017
10018   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
10019      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
10020
10021   /* Get accessibility.  */
10022   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10023   if (attr)
10024     accessibility = DW_UNSND (attr);
10025   else
10026     accessibility = dwarf2_default_access_attribute (die, cu);
10027   switch (accessibility)
10028     {
10029     case DW_ACCESS_private:
10030       fnp->is_private = 1;
10031       break;
10032     case DW_ACCESS_protected:
10033       fnp->is_protected = 1;
10034       break;
10035     }
10036
10037   /* Check for artificial methods.  */
10038   attr = dwarf2_attr (die, DW_AT_artificial, cu);
10039   if (attr && DW_UNSND (attr) != 0)
10040     fnp->is_artificial = 1;
10041
10042   /* Get index in virtual function table if it is a virtual member
10043      function.  For older versions of GCC, this is an offset in the
10044      appropriate virtual table, as specified by DW_AT_containing_type.
10045      For everyone else, it is an expression to be evaluated relative
10046      to the object address.  */
10047
10048   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
10049   if (attr)
10050     {
10051       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
10052         {
10053           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
10054             {
10055               /* Old-style GCC.  */
10056               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
10057             }
10058           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
10059                    || (DW_BLOCK (attr)->size > 1
10060                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
10061                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
10062             {
10063               struct dwarf_block blk;
10064               int offset;
10065
10066               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
10067                         ? 1 : 2);
10068               blk.size = DW_BLOCK (attr)->size - offset;
10069               blk.data = DW_BLOCK (attr)->data + offset;
10070               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
10071               if ((fnp->voffset % cu->header.addr_size) != 0)
10072                 dwarf2_complex_location_expr_complaint ();
10073               else
10074                 fnp->voffset /= cu->header.addr_size;
10075               fnp->voffset += 2;
10076             }
10077           else
10078             dwarf2_complex_location_expr_complaint ();
10079
10080           if (!fnp->fcontext)
10081             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
10082         }
10083       else if (attr_form_is_section_offset (attr))
10084         {
10085           dwarf2_complex_location_expr_complaint ();
10086         }
10087       else
10088         {
10089           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
10090                                                  fieldname);
10091         }
10092     }
10093   else
10094     {
10095       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10096       if (attr && DW_UNSND (attr))
10097         {
10098           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
10099           complaint (&symfile_complaints,
10100                      _("Member function \"%s\" (offset %d) is virtual "
10101                        "but the vtable offset is not specified"),
10102                      fieldname, die->offset.sect_off);
10103           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10104           TYPE_CPLUS_DYNAMIC (type) = 1;
10105         }
10106     }
10107 }
10108
10109 /* Create the vector of member function fields, and attach it to the type.  */
10110
10111 static void
10112 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
10113                                  struct dwarf2_cu *cu)
10114 {
10115   struct fnfieldlist *flp;
10116   int i;
10117
10118   if (cu->language == language_ada)
10119     error (_("unexpected member functions in Ada type"));
10120
10121   ALLOCATE_CPLUS_STRUCT_TYPE (type);
10122   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
10123     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
10124
10125   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
10126     {
10127       struct nextfnfield *nfp = flp->head;
10128       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
10129       int k;
10130
10131       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
10132       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
10133       fn_flp->fn_fields = (struct fn_field *)
10134         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
10135       for (k = flp->length; (k--, nfp); nfp = nfp->next)
10136         fn_flp->fn_fields[k] = nfp->fnfield;
10137     }
10138
10139   TYPE_NFN_FIELDS (type) = fip->nfnfields;
10140 }
10141
10142 /* Returns non-zero if NAME is the name of a vtable member in CU's
10143    language, zero otherwise.  */
10144 static int
10145 is_vtable_name (const char *name, struct dwarf2_cu *cu)
10146 {
10147   static const char vptr[] = "_vptr";
10148   static const char vtable[] = "vtable";
10149
10150   /* Look for the C++ and Java forms of the vtable.  */
10151   if ((cu->language == language_java
10152        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
10153        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
10154        && is_cplus_marker (name[sizeof (vptr) - 1])))
10155     return 1;
10156
10157   return 0;
10158 }
10159
10160 /* GCC outputs unnamed structures that are really pointers to member
10161    functions, with the ABI-specified layout.  If TYPE describes
10162    such a structure, smash it into a member function type.
10163
10164    GCC shouldn't do this; it should just output pointer to member DIEs.
10165    This is GCC PR debug/28767.  */
10166
10167 static void
10168 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
10169 {
10170   struct type *pfn_type, *domain_type, *new_type;
10171
10172   /* Check for a structure with no name and two children.  */
10173   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
10174     return;
10175
10176   /* Check for __pfn and __delta members.  */
10177   if (TYPE_FIELD_NAME (type, 0) == NULL
10178       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
10179       || TYPE_FIELD_NAME (type, 1) == NULL
10180       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
10181     return;
10182
10183   /* Find the type of the method.  */
10184   pfn_type = TYPE_FIELD_TYPE (type, 0);
10185   if (pfn_type == NULL
10186       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
10187       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
10188     return;
10189
10190   /* Look for the "this" argument.  */
10191   pfn_type = TYPE_TARGET_TYPE (pfn_type);
10192   if (TYPE_NFIELDS (pfn_type) == 0
10193       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
10194       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
10195     return;
10196
10197   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
10198   new_type = alloc_type (objfile);
10199   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
10200                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
10201                         TYPE_VARARGS (pfn_type));
10202   smash_to_methodptr_type (type, new_type);
10203 }
10204
10205 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
10206    (icc).  */
10207
10208 static int
10209 producer_is_icc (struct dwarf2_cu *cu)
10210 {
10211   if (!cu->checked_producer)
10212     check_producer (cu);
10213
10214   return cu->producer_is_icc;
10215 }
10216
10217 /* Called when we find the DIE that starts a structure or union scope
10218    (definition) to create a type for the structure or union.  Fill in
10219    the type's name and general properties; the members will not be
10220    processed until process_structure_type.
10221
10222    NOTE: we need to call these functions regardless of whether or not the
10223    DIE has a DW_AT_name attribute, since it might be an anonymous
10224    structure or union.  This gets the type entered into our set of
10225    user defined types.
10226
10227    However, if the structure is incomplete (an opaque struct/union)
10228    then suppress creating a symbol table entry for it since gdb only
10229    wants to find the one with the complete definition.  Note that if
10230    it is complete, we just call new_symbol, which does it's own
10231    checking about whether the struct/union is anonymous or not (and
10232    suppresses creating a symbol table entry itself).  */
10233
10234 static struct type *
10235 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
10236 {
10237   struct objfile *objfile = cu->objfile;
10238   struct type *type;
10239   struct attribute *attr;
10240   char *name;
10241
10242   /* If the definition of this type lives in .debug_types, read that type.
10243      Don't follow DW_AT_specification though, that will take us back up
10244      the chain and we want to go down.  */
10245   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
10246   if (attr)
10247     {
10248       struct dwarf2_cu *type_cu = cu;
10249       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
10250
10251       /* We could just recurse on read_structure_type, but we need to call
10252          get_die_type to ensure only one type for this DIE is created.
10253          This is important, for example, because for c++ classes we need
10254          TYPE_NAME set which is only done by new_symbol.  Blech.  */
10255       type = read_type_die (type_die, type_cu);
10256
10257       /* TYPE_CU may not be the same as CU.
10258          Ensure TYPE is recorded in CU's type_hash table.  */
10259       return set_die_type (die, type, cu);
10260     }
10261
10262   type = alloc_type (objfile);
10263   INIT_CPLUS_SPECIFIC (type);
10264
10265   name = dwarf2_name (die, cu);
10266   if (name != NULL)
10267     {
10268       if (cu->language == language_cplus
10269           || cu->language == language_java)
10270         {
10271           char *full_name = (char *) dwarf2_full_name (name, die, cu);
10272
10273           /* dwarf2_full_name might have already finished building the DIE's
10274              type.  If so, there is no need to continue.  */
10275           if (get_die_type (die, cu) != NULL)
10276             return get_die_type (die, cu);
10277
10278           TYPE_TAG_NAME (type) = full_name;
10279           if (die->tag == DW_TAG_structure_type
10280               || die->tag == DW_TAG_class_type)
10281             TYPE_NAME (type) = TYPE_TAG_NAME (type);
10282         }
10283       else
10284         {
10285           /* The name is already allocated along with this objfile, so
10286              we don't need to duplicate it for the type.  */
10287           TYPE_TAG_NAME (type) = (char *) name;
10288           if (die->tag == DW_TAG_class_type)
10289             TYPE_NAME (type) = TYPE_TAG_NAME (type);
10290         }
10291     }
10292
10293   if (die->tag == DW_TAG_structure_type)
10294     {
10295       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10296     }
10297   else if (die->tag == DW_TAG_union_type)
10298     {
10299       TYPE_CODE (type) = TYPE_CODE_UNION;
10300     }
10301   else
10302     {
10303       TYPE_CODE (type) = TYPE_CODE_CLASS;
10304     }
10305
10306   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
10307     TYPE_DECLARED_CLASS (type) = 1;
10308
10309   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10310   if (attr)
10311     {
10312       TYPE_LENGTH (type) = DW_UNSND (attr);
10313     }
10314   else
10315     {
10316       TYPE_LENGTH (type) = 0;
10317     }
10318
10319   if (producer_is_icc (cu))
10320     {
10321       /* ICC does not output the required DW_AT_declaration
10322          on incomplete types, but gives them a size of zero.  */
10323     }
10324   else
10325     TYPE_STUB_SUPPORTED (type) = 1;
10326
10327   if (die_is_declaration (die, cu))
10328     TYPE_STUB (type) = 1;
10329   else if (attr == NULL && die->child == NULL
10330            && producer_is_realview (cu->producer))
10331     /* RealView does not output the required DW_AT_declaration
10332        on incomplete types.  */
10333     TYPE_STUB (type) = 1;
10334
10335   /* We need to add the type field to the die immediately so we don't
10336      infinitely recurse when dealing with pointers to the structure
10337      type within the structure itself.  */
10338   set_die_type (die, type, cu);
10339
10340   /* set_die_type should be already done.  */
10341   set_descriptive_type (type, die, cu);
10342
10343   return type;
10344 }
10345
10346 /* Finish creating a structure or union type, including filling in
10347    its members and creating a symbol for it.  */
10348
10349 static void
10350 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
10351 {
10352   struct objfile *objfile = cu->objfile;
10353   struct die_info *child_die = die->child;
10354   struct type *type;
10355
10356   type = get_die_type (die, cu);
10357   if (type == NULL)
10358     type = read_structure_type (die, cu);
10359
10360   if (die->child != NULL && ! die_is_declaration (die, cu))
10361     {
10362       struct field_info fi;
10363       struct die_info *child_die;
10364       VEC (symbolp) *template_args = NULL;
10365       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
10366
10367       memset (&fi, 0, sizeof (struct field_info));
10368
10369       child_die = die->child;
10370
10371       while (child_die && child_die->tag)
10372         {
10373           if (child_die->tag == DW_TAG_member
10374               || child_die->tag == DW_TAG_variable)
10375             {
10376               /* NOTE: carlton/2002-11-05: A C++ static data member
10377                  should be a DW_TAG_member that is a declaration, but
10378                  all versions of G++ as of this writing (so through at
10379                  least 3.2.1) incorrectly generate DW_TAG_variable
10380                  tags for them instead.  */
10381               dwarf2_add_field (&fi, child_die, cu);
10382             }
10383           else if (child_die->tag == DW_TAG_subprogram)
10384             {
10385               /* C++ member function.  */
10386               dwarf2_add_member_fn (&fi, child_die, type, cu);
10387             }
10388           else if (child_die->tag == DW_TAG_inheritance)
10389             {
10390               /* C++ base class field.  */
10391               dwarf2_add_field (&fi, child_die, cu);
10392             }
10393           else if (child_die->tag == DW_TAG_typedef)
10394             dwarf2_add_typedef (&fi, child_die, cu);
10395           else if (child_die->tag == DW_TAG_template_type_param
10396                    || child_die->tag == DW_TAG_template_value_param)
10397             {
10398               struct symbol *arg = new_symbol (child_die, NULL, cu);
10399
10400               if (arg != NULL)
10401                 VEC_safe_push (symbolp, template_args, arg);
10402             }
10403
10404           child_die = sibling_die (child_die);
10405         }
10406
10407       /* Attach template arguments to type.  */
10408       if (! VEC_empty (symbolp, template_args))
10409         {
10410           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10411           TYPE_N_TEMPLATE_ARGUMENTS (type)
10412             = VEC_length (symbolp, template_args);
10413           TYPE_TEMPLATE_ARGUMENTS (type)
10414             = obstack_alloc (&objfile->objfile_obstack,
10415                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
10416                               * sizeof (struct symbol *)));
10417           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
10418                   VEC_address (symbolp, template_args),
10419                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
10420                    * sizeof (struct symbol *)));
10421           VEC_free (symbolp, template_args);
10422         }
10423
10424       /* Attach fields and member functions to the type.  */
10425       if (fi.nfields)
10426         dwarf2_attach_fields_to_type (&fi, type, cu);
10427       if (fi.nfnfields)
10428         {
10429           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
10430
10431           /* Get the type which refers to the base class (possibly this
10432              class itself) which contains the vtable pointer for the current
10433              class from the DW_AT_containing_type attribute.  This use of
10434              DW_AT_containing_type is a GNU extension.  */
10435
10436           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10437             {
10438               struct type *t = die_containing_type (die, cu);
10439
10440               TYPE_VPTR_BASETYPE (type) = t;
10441               if (type == t)
10442                 {
10443                   int i;
10444
10445                   /* Our own class provides vtbl ptr.  */
10446                   for (i = TYPE_NFIELDS (t) - 1;
10447                        i >= TYPE_N_BASECLASSES (t);
10448                        --i)
10449                     {
10450                       const char *fieldname = TYPE_FIELD_NAME (t, i);
10451
10452                       if (is_vtable_name (fieldname, cu))
10453                         {
10454                           TYPE_VPTR_FIELDNO (type) = i;
10455                           break;
10456                         }
10457                     }
10458
10459                   /* Complain if virtual function table field not found.  */
10460                   if (i < TYPE_N_BASECLASSES (t))
10461                     complaint (&symfile_complaints,
10462                                _("virtual function table pointer "
10463                                  "not found when defining class '%s'"),
10464                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
10465                                "");
10466                 }
10467               else
10468                 {
10469                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
10470                 }
10471             }
10472           else if (cu->producer
10473                    && strncmp (cu->producer,
10474                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
10475             {
10476               /* The IBM XLC compiler does not provide direct indication
10477                  of the containing type, but the vtable pointer is
10478                  always named __vfp.  */
10479
10480               int i;
10481
10482               for (i = TYPE_NFIELDS (type) - 1;
10483                    i >= TYPE_N_BASECLASSES (type);
10484                    --i)
10485                 {
10486                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
10487                     {
10488                       TYPE_VPTR_FIELDNO (type) = i;
10489                       TYPE_VPTR_BASETYPE (type) = type;
10490                       break;
10491                     }
10492                 }
10493             }
10494         }
10495
10496       /* Copy fi.typedef_field_list linked list elements content into the
10497          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
10498       if (fi.typedef_field_list)
10499         {
10500           int i = fi.typedef_field_list_count;
10501
10502           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10503           TYPE_TYPEDEF_FIELD_ARRAY (type)
10504             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
10505           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
10506
10507           /* Reverse the list order to keep the debug info elements order.  */
10508           while (--i >= 0)
10509             {
10510               struct typedef_field *dest, *src;
10511
10512               dest = &TYPE_TYPEDEF_FIELD (type, i);
10513               src = &fi.typedef_field_list->field;
10514               fi.typedef_field_list = fi.typedef_field_list->next;
10515               *dest = *src;
10516             }
10517         }
10518
10519       do_cleanups (back_to);
10520
10521       if (HAVE_CPLUS_STRUCT (type))
10522         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
10523     }
10524
10525   quirk_gcc_member_function_pointer (type, objfile);
10526
10527   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
10528      snapshots) has been known to create a die giving a declaration
10529      for a class that has, as a child, a die giving a definition for a
10530      nested class.  So we have to process our children even if the
10531      current die is a declaration.  Normally, of course, a declaration
10532      won't have any children at all.  */
10533
10534   while (child_die != NULL && child_die->tag)
10535     {
10536       if (child_die->tag == DW_TAG_member
10537           || child_die->tag == DW_TAG_variable
10538           || child_die->tag == DW_TAG_inheritance
10539           || child_die->tag == DW_TAG_template_value_param
10540           || child_die->tag == DW_TAG_template_type_param)
10541         {
10542           /* Do nothing.  */
10543         }
10544       else
10545         process_die (child_die, cu);
10546
10547       child_die = sibling_die (child_die);
10548     }
10549
10550   /* Do not consider external references.  According to the DWARF standard,
10551      these DIEs are identified by the fact that they have no byte_size
10552      attribute, and a declaration attribute.  */
10553   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
10554       || !die_is_declaration (die, cu))
10555     new_symbol (die, type, cu);
10556 }
10557
10558 /* Given a DW_AT_enumeration_type die, set its type.  We do not
10559    complete the type's fields yet, or create any symbols.  */
10560
10561 static struct type *
10562 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
10563 {
10564   struct objfile *objfile = cu->objfile;
10565   struct type *type;
10566   struct attribute *attr;
10567   const char *name;
10568
10569   /* If the definition of this type lives in .debug_types, read that type.
10570      Don't follow DW_AT_specification though, that will take us back up
10571      the chain and we want to go down.  */
10572   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
10573   if (attr)
10574     {
10575       struct dwarf2_cu *type_cu = cu;
10576       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
10577
10578       type = read_type_die (type_die, type_cu);
10579
10580       /* TYPE_CU may not be the same as CU.
10581          Ensure TYPE is recorded in CU's type_hash table.  */
10582       return set_die_type (die, type, cu);
10583     }
10584
10585   type = alloc_type (objfile);
10586
10587   TYPE_CODE (type) = TYPE_CODE_ENUM;
10588   name = dwarf2_full_name (NULL, die, cu);
10589   if (name != NULL)
10590     TYPE_TAG_NAME (type) = (char *) name;
10591
10592   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10593   if (attr)
10594     {
10595       TYPE_LENGTH (type) = DW_UNSND (attr);
10596     }
10597   else
10598     {
10599       TYPE_LENGTH (type) = 0;
10600     }
10601
10602   /* The enumeration DIE can be incomplete.  In Ada, any type can be
10603      declared as private in the package spec, and then defined only
10604      inside the package body.  Such types are known as Taft Amendment
10605      Types.  When another package uses such a type, an incomplete DIE
10606      may be generated by the compiler.  */
10607   if (die_is_declaration (die, cu))
10608     TYPE_STUB (type) = 1;
10609
10610   return set_die_type (die, type, cu);
10611 }
10612
10613 /* Given a pointer to a die which begins an enumeration, process all
10614    the dies that define the members of the enumeration, and create the
10615    symbol for the enumeration type.
10616
10617    NOTE: We reverse the order of the element list.  */
10618
10619 static void
10620 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
10621 {
10622   struct type *this_type;
10623
10624   this_type = get_die_type (die, cu);
10625   if (this_type == NULL)
10626     this_type = read_enumeration_type (die, cu);
10627
10628   if (die->child != NULL)
10629     {
10630       struct die_info *child_die;
10631       struct symbol *sym;
10632       struct field *fields = NULL;
10633       int num_fields = 0;
10634       int unsigned_enum = 1;
10635       char *name;
10636       int flag_enum = 1;
10637       ULONGEST mask = 0;
10638
10639       child_die = die->child;
10640       while (child_die && child_die->tag)
10641         {
10642           if (child_die->tag != DW_TAG_enumerator)
10643             {
10644               process_die (child_die, cu);
10645             }
10646           else
10647             {
10648               name = dwarf2_name (child_die, cu);
10649               if (name)
10650                 {
10651                   sym = new_symbol (child_die, this_type, cu);
10652                   if (SYMBOL_VALUE (sym) < 0)
10653                     {
10654                       unsigned_enum = 0;
10655                       flag_enum = 0;
10656                     }
10657                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
10658                     flag_enum = 0;
10659                   else
10660                     mask |= SYMBOL_VALUE (sym);
10661
10662                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
10663                     {
10664                       fields = (struct field *)
10665                         xrealloc (fields,
10666                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
10667                                   * sizeof (struct field));
10668                     }
10669
10670                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
10671                   FIELD_TYPE (fields[num_fields]) = NULL;
10672                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
10673                   FIELD_BITSIZE (fields[num_fields]) = 0;
10674
10675                   num_fields++;
10676                 }
10677             }
10678
10679           child_die = sibling_die (child_die);
10680         }
10681
10682       if (num_fields)
10683         {
10684           TYPE_NFIELDS (this_type) = num_fields;
10685           TYPE_FIELDS (this_type) = (struct field *)
10686             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
10687           memcpy (TYPE_FIELDS (this_type), fields,
10688                   sizeof (struct field) * num_fields);
10689           xfree (fields);
10690         }
10691       if (unsigned_enum)
10692         TYPE_UNSIGNED (this_type) = 1;
10693       if (flag_enum)
10694         TYPE_FLAG_ENUM (this_type) = 1;
10695     }
10696
10697   /* If we are reading an enum from a .debug_types unit, and the enum
10698      is a declaration, and the enum is not the signatured type in the
10699      unit, then we do not want to add a symbol for it.  Adding a
10700      symbol would in some cases obscure the true definition of the
10701      enum, giving users an incomplete type when the definition is
10702      actually available.  Note that we do not want to do this for all
10703      enums which are just declarations, because C++0x allows forward
10704      enum declarations.  */
10705   if (cu->per_cu->is_debug_types
10706       && die_is_declaration (die, cu))
10707     {
10708       struct signatured_type *sig_type;
10709
10710       sig_type
10711         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
10712                                             cu->per_cu->info_or_types_section,
10713                                             cu->per_cu->offset);
10714       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
10715       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
10716         return;
10717     }
10718
10719   new_symbol (die, this_type, cu);
10720 }
10721
10722 /* Extract all information from a DW_TAG_array_type DIE and put it in
10723    the DIE's type field.  For now, this only handles one dimensional
10724    arrays.  */
10725
10726 static struct type *
10727 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
10728 {
10729   struct objfile *objfile = cu->objfile;
10730   struct die_info *child_die;
10731   struct type *type;
10732   struct type *element_type, *range_type, *index_type;
10733   struct type **range_types = NULL;
10734   struct attribute *attr;
10735   int ndim = 0;
10736   struct cleanup *back_to;
10737   char *name;
10738
10739   element_type = die_type (die, cu);
10740
10741   /* The die_type call above may have already set the type for this DIE.  */
10742   type = get_die_type (die, cu);
10743   if (type)
10744     return type;
10745
10746   /* Irix 6.2 native cc creates array types without children for
10747      arrays with unspecified length.  */
10748   if (die->child == NULL)
10749     {
10750       index_type = objfile_type (objfile)->builtin_int;
10751       range_type = create_range_type (NULL, index_type, 0, -1);
10752       type = create_array_type (NULL, element_type, range_type);
10753       return set_die_type (die, type, cu);
10754     }
10755
10756   back_to = make_cleanup (null_cleanup, NULL);
10757   child_die = die->child;
10758   while (child_die && child_die->tag)
10759     {
10760       if (child_die->tag == DW_TAG_subrange_type)
10761         {
10762           struct type *child_type = read_type_die (child_die, cu);
10763
10764           if (child_type != NULL)
10765             {
10766               /* The range type was succesfully read.  Save it for the
10767                  array type creation.  */
10768               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
10769                 {
10770                   range_types = (struct type **)
10771                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
10772                               * sizeof (struct type *));
10773                   if (ndim == 0)
10774                     make_cleanup (free_current_contents, &range_types);
10775                 }
10776               range_types[ndim++] = child_type;
10777             }
10778         }
10779       child_die = sibling_die (child_die);
10780     }
10781
10782   /* Dwarf2 dimensions are output from left to right, create the
10783      necessary array types in backwards order.  */
10784
10785   type = element_type;
10786
10787   if (read_array_order (die, cu) == DW_ORD_col_major)
10788     {
10789       int i = 0;
10790
10791       while (i < ndim)
10792         type = create_array_type (NULL, type, range_types[i++]);
10793     }
10794   else
10795     {
10796       while (ndim-- > 0)
10797         type = create_array_type (NULL, type, range_types[ndim]);
10798     }
10799
10800   /* Understand Dwarf2 support for vector types (like they occur on
10801      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
10802      array type.  This is not part of the Dwarf2/3 standard yet, but a
10803      custom vendor extension.  The main difference between a regular
10804      array and the vector variant is that vectors are passed by value
10805      to functions.  */
10806   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
10807   if (attr)
10808     make_vector_type (type);
10809
10810   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
10811      implementation may choose to implement triple vectors using this
10812      attribute.  */
10813   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10814   if (attr)
10815     {
10816       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
10817         TYPE_LENGTH (type) = DW_UNSND (attr);
10818       else
10819         complaint (&symfile_complaints,
10820                    _("DW_AT_byte_size for array type smaller "
10821                      "than the total size of elements"));
10822     }
10823
10824   name = dwarf2_name (die, cu);
10825   if (name)
10826     TYPE_NAME (type) = name;
10827
10828   /* Install the type in the die.  */
10829   set_die_type (die, type, cu);
10830
10831   /* set_die_type should be already done.  */
10832   set_descriptive_type (type, die, cu);
10833
10834   do_cleanups (back_to);
10835
10836   return type;
10837 }
10838
10839 static enum dwarf_array_dim_ordering
10840 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
10841 {
10842   struct attribute *attr;
10843
10844   attr = dwarf2_attr (die, DW_AT_ordering, cu);
10845
10846   if (attr) return DW_SND (attr);
10847
10848   /* GNU F77 is a special case, as at 08/2004 array type info is the
10849      opposite order to the dwarf2 specification, but data is still
10850      laid out as per normal fortran.
10851
10852      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
10853      version checking.  */
10854
10855   if (cu->language == language_fortran
10856       && cu->producer && strstr (cu->producer, "GNU F77"))
10857     {
10858       return DW_ORD_row_major;
10859     }
10860
10861   switch (cu->language_defn->la_array_ordering)
10862     {
10863     case array_column_major:
10864       return DW_ORD_col_major;
10865     case array_row_major:
10866     default:
10867       return DW_ORD_row_major;
10868     };
10869 }
10870
10871 /* Extract all information from a DW_TAG_set_type DIE and put it in
10872    the DIE's type field.  */
10873
10874 static struct type *
10875 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
10876 {
10877   struct type *domain_type, *set_type;
10878   struct attribute *attr;
10879
10880   domain_type = die_type (die, cu);
10881
10882   /* The die_type call above may have already set the type for this DIE.  */
10883   set_type = get_die_type (die, cu);
10884   if (set_type)
10885     return set_type;
10886
10887   set_type = create_set_type (NULL, domain_type);
10888
10889   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10890   if (attr)
10891     TYPE_LENGTH (set_type) = DW_UNSND (attr);
10892
10893   return set_die_type (die, set_type, cu);
10894 }
10895
10896 /* First cut: install each common block member as a global variable.  */
10897
10898 static void
10899 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
10900 {
10901   struct die_info *child_die;
10902   struct attribute *attr;
10903   struct symbol *sym;
10904   CORE_ADDR base = (CORE_ADDR) 0;
10905
10906   attr = dwarf2_attr (die, DW_AT_location, cu);
10907   if (attr)
10908     {
10909       /* Support the .debug_loc offsets.  */
10910       if (attr_form_is_block (attr))
10911         {
10912           base = decode_locdesc (DW_BLOCK (attr), cu);
10913         }
10914       else if (attr_form_is_section_offset (attr))
10915         {
10916           dwarf2_complex_location_expr_complaint ();
10917         }
10918       else
10919         {
10920           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
10921                                                  "common block member");
10922         }
10923     }
10924   if (die->child != NULL)
10925     {
10926       child_die = die->child;
10927       while (child_die && child_die->tag)
10928         {
10929           LONGEST offset;
10930
10931           sym = new_symbol (child_die, NULL, cu);
10932           if (sym != NULL
10933               && handle_data_member_location (child_die, cu, &offset))
10934             {
10935               SYMBOL_VALUE_ADDRESS (sym) = base + offset;
10936               add_symbol_to_list (sym, &global_symbols);
10937             }
10938           child_die = sibling_die (child_die);
10939         }
10940     }
10941 }
10942
10943 /* Create a type for a C++ namespace.  */
10944
10945 static struct type *
10946 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
10947 {
10948   struct objfile *objfile = cu->objfile;
10949   const char *previous_prefix, *name;
10950   int is_anonymous;
10951   struct type *type;
10952
10953   /* For extensions, reuse the type of the original namespace.  */
10954   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
10955     {
10956       struct die_info *ext_die;
10957       struct dwarf2_cu *ext_cu = cu;
10958
10959       ext_die = dwarf2_extension (die, &ext_cu);
10960       type = read_type_die (ext_die, ext_cu);
10961
10962       /* EXT_CU may not be the same as CU.
10963          Ensure TYPE is recorded in CU's type_hash table.  */
10964       return set_die_type (die, type, cu);
10965     }
10966
10967   name = namespace_name (die, &is_anonymous, cu);
10968
10969   /* Now build the name of the current namespace.  */
10970
10971   previous_prefix = determine_prefix (die, cu);
10972   if (previous_prefix[0] != '\0')
10973     name = typename_concat (&objfile->objfile_obstack,
10974                             previous_prefix, name, 0, cu);
10975
10976   /* Create the type.  */
10977   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
10978                     objfile);
10979   TYPE_NAME (type) = (char *) name;
10980   TYPE_TAG_NAME (type) = TYPE_NAME (type);
10981
10982   return set_die_type (die, type, cu);
10983 }
10984
10985 /* Read a C++ namespace.  */
10986
10987 static void
10988 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
10989 {
10990   struct objfile *objfile = cu->objfile;
10991   int is_anonymous;
10992
10993   /* Add a symbol associated to this if we haven't seen the namespace
10994      before.  Also, add a using directive if it's an anonymous
10995      namespace.  */
10996
10997   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
10998     {
10999       struct type *type;
11000
11001       type = read_type_die (die, cu);
11002       new_symbol (die, type, cu);
11003
11004       namespace_name (die, &is_anonymous, cu);
11005       if (is_anonymous)
11006         {
11007           const char *previous_prefix = determine_prefix (die, cu);
11008
11009           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
11010                                   NULL, NULL, &objfile->objfile_obstack);
11011         }
11012     }
11013
11014   if (die->child != NULL)
11015     {
11016       struct die_info *child_die = die->child;
11017
11018       while (child_die && child_die->tag)
11019         {
11020           process_die (child_die, cu);
11021           child_die = sibling_die (child_die);
11022         }
11023     }
11024 }
11025
11026 /* Read a Fortran module as type.  This DIE can be only a declaration used for
11027    imported module.  Still we need that type as local Fortran "use ... only"
11028    declaration imports depend on the created type in determine_prefix.  */
11029
11030 static struct type *
11031 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
11032 {
11033   struct objfile *objfile = cu->objfile;
11034   char *module_name;
11035   struct type *type;
11036
11037   module_name = dwarf2_name (die, cu);
11038   if (!module_name)
11039     complaint (&symfile_complaints,
11040                _("DW_TAG_module has no name, offset 0x%x"),
11041                die->offset.sect_off);
11042   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
11043
11044   /* determine_prefix uses TYPE_TAG_NAME.  */
11045   TYPE_TAG_NAME (type) = TYPE_NAME (type);
11046
11047   return set_die_type (die, type, cu);
11048 }
11049
11050 /* Read a Fortran module.  */
11051
11052 static void
11053 read_module (struct die_info *die, struct dwarf2_cu *cu)
11054 {
11055   struct die_info *child_die = die->child;
11056
11057   while (child_die && child_die->tag)
11058     {
11059       process_die (child_die, cu);
11060       child_die = sibling_die (child_die);
11061     }
11062 }
11063
11064 /* Return the name of the namespace represented by DIE.  Set
11065    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
11066    namespace.  */
11067
11068 static const char *
11069 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
11070 {
11071   struct die_info *current_die;
11072   const char *name = NULL;
11073
11074   /* Loop through the extensions until we find a name.  */
11075
11076   for (current_die = die;
11077        current_die != NULL;
11078        current_die = dwarf2_extension (die, &cu))
11079     {
11080       name = dwarf2_name (current_die, cu);
11081       if (name != NULL)
11082         break;
11083     }
11084
11085   /* Is it an anonymous namespace?  */
11086
11087   *is_anonymous = (name == NULL);
11088   if (*is_anonymous)
11089     name = CP_ANONYMOUS_NAMESPACE_STR;
11090
11091   return name;
11092 }
11093
11094 /* Extract all information from a DW_TAG_pointer_type DIE and add to
11095    the user defined type vector.  */
11096
11097 static struct type *
11098 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
11099 {
11100   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
11101   struct comp_unit_head *cu_header = &cu->header;
11102   struct type *type;
11103   struct attribute *attr_byte_size;
11104   struct attribute *attr_address_class;
11105   int byte_size, addr_class;
11106   struct type *target_type;
11107
11108   target_type = die_type (die, cu);
11109
11110   /* The die_type call above may have already set the type for this DIE.  */
11111   type = get_die_type (die, cu);
11112   if (type)
11113     return type;
11114
11115   type = lookup_pointer_type (target_type);
11116
11117   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
11118   if (attr_byte_size)
11119     byte_size = DW_UNSND (attr_byte_size);
11120   else
11121     byte_size = cu_header->addr_size;
11122
11123   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
11124   if (attr_address_class)
11125     addr_class = DW_UNSND (attr_address_class);
11126   else
11127     addr_class = DW_ADDR_none;
11128
11129   /* If the pointer size or address class is different than the
11130      default, create a type variant marked as such and set the
11131      length accordingly.  */
11132   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
11133     {
11134       if (gdbarch_address_class_type_flags_p (gdbarch))
11135         {
11136           int type_flags;
11137
11138           type_flags = gdbarch_address_class_type_flags
11139                          (gdbarch, byte_size, addr_class);
11140           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
11141                       == 0);
11142           type = make_type_with_address_space (type, type_flags);
11143         }
11144       else if (TYPE_LENGTH (type) != byte_size)
11145         {
11146           complaint (&symfile_complaints,
11147                      _("invalid pointer size %d"), byte_size);
11148         }
11149       else
11150         {
11151           /* Should we also complain about unhandled address classes?  */
11152         }
11153     }
11154
11155   TYPE_LENGTH (type) = byte_size;
11156   return set_die_type (die, type, cu);
11157 }
11158
11159 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
11160    the user defined type vector.  */
11161
11162 static struct type *
11163 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
11164 {
11165   struct type *type;
11166   struct type *to_type;
11167   struct type *domain;
11168
11169   to_type = die_type (die, cu);
11170   domain = die_containing_type (die, cu);
11171
11172   /* The calls above may have already set the type for this DIE.  */
11173   type = get_die_type (die, cu);
11174   if (type)
11175     return type;
11176
11177   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
11178     type = lookup_methodptr_type (to_type);
11179   else
11180     type = lookup_memberptr_type (to_type, domain);
11181
11182   return set_die_type (die, type, cu);
11183 }
11184
11185 /* Extract all information from a DW_TAG_reference_type DIE and add to
11186    the user defined type vector.  */
11187
11188 static struct type *
11189 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
11190 {
11191   struct comp_unit_head *cu_header = &cu->header;
11192   struct type *type, *target_type;
11193   struct attribute *attr;
11194
11195   target_type = die_type (die, cu);
11196
11197   /* The die_type call above may have already set the type for this DIE.  */
11198   type = get_die_type (die, cu);
11199   if (type)
11200     return type;
11201
11202   type = lookup_reference_type (target_type);
11203   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11204   if (attr)
11205     {
11206       TYPE_LENGTH (type) = DW_UNSND (attr);
11207     }
11208   else
11209     {
11210       TYPE_LENGTH (type) = cu_header->addr_size;
11211     }
11212   return set_die_type (die, type, cu);
11213 }
11214
11215 static struct type *
11216 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
11217 {
11218   struct type *base_type, *cv_type;
11219
11220   base_type = die_type (die, cu);
11221
11222   /* The die_type call above may have already set the type for this DIE.  */
11223   cv_type = get_die_type (die, cu);
11224   if (cv_type)
11225     return cv_type;
11226
11227   /* In case the const qualifier is applied to an array type, the element type
11228      is so qualified, not the array type (section 6.7.3 of C99).  */
11229   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
11230     {
11231       struct type *el_type, *inner_array;
11232
11233       base_type = copy_type (base_type);
11234       inner_array = base_type;
11235
11236       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
11237         {
11238           TYPE_TARGET_TYPE (inner_array) =
11239             copy_type (TYPE_TARGET_TYPE (inner_array));
11240           inner_array = TYPE_TARGET_TYPE (inner_array);
11241         }
11242
11243       el_type = TYPE_TARGET_TYPE (inner_array);
11244       TYPE_TARGET_TYPE (inner_array) =
11245         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
11246
11247       return set_die_type (die, base_type, cu);
11248     }
11249
11250   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
11251   return set_die_type (die, cv_type, cu);
11252 }
11253
11254 static struct type *
11255 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
11256 {
11257   struct type *base_type, *cv_type;
11258
11259   base_type = die_type (die, cu);
11260
11261   /* The die_type call above may have already set the type for this DIE.  */
11262   cv_type = get_die_type (die, cu);
11263   if (cv_type)
11264     return cv_type;
11265
11266   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
11267   return set_die_type (die, cv_type, cu);
11268 }
11269
11270 /* Extract all information from a DW_TAG_string_type DIE and add to
11271    the user defined type vector.  It isn't really a user defined type,
11272    but it behaves like one, with other DIE's using an AT_user_def_type
11273    attribute to reference it.  */
11274
11275 static struct type *
11276 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
11277 {
11278   struct objfile *objfile = cu->objfile;
11279   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11280   struct type *type, *range_type, *index_type, *char_type;
11281   struct attribute *attr;
11282   unsigned int length;
11283
11284   attr = dwarf2_attr (die, DW_AT_string_length, cu);
11285   if (attr)
11286     {
11287       length = DW_UNSND (attr);
11288     }
11289   else
11290     {
11291       /* Check for the DW_AT_byte_size attribute.  */
11292       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11293       if (attr)
11294         {
11295           length = DW_UNSND (attr);
11296         }
11297       else
11298         {
11299           length = 1;
11300         }
11301     }
11302
11303   index_type = objfile_type (objfile)->builtin_int;
11304   range_type = create_range_type (NULL, index_type, 1, length);
11305   char_type = language_string_char_type (cu->language_defn, gdbarch);
11306   type = create_string_type (NULL, char_type, range_type);
11307
11308   return set_die_type (die, type, cu);
11309 }
11310
11311 /* Handle DIES due to C code like:
11312
11313    struct foo
11314    {
11315    int (*funcp)(int a, long l);
11316    int b;
11317    };
11318
11319    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
11320
11321 static struct type *
11322 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
11323 {
11324   struct objfile *objfile = cu->objfile;
11325   struct type *type;            /* Type that this function returns.  */
11326   struct type *ftype;           /* Function that returns above type.  */
11327   struct attribute *attr;
11328
11329   type = die_type (die, cu);
11330
11331   /* The die_type call above may have already set the type for this DIE.  */
11332   ftype = get_die_type (die, cu);
11333   if (ftype)
11334     return ftype;
11335
11336   ftype = lookup_function_type (type);
11337
11338   /* All functions in C++, Pascal and Java have prototypes.  */
11339   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
11340   if ((attr && (DW_UNSND (attr) != 0))
11341       || cu->language == language_cplus
11342       || cu->language == language_java
11343       || cu->language == language_pascal)
11344     TYPE_PROTOTYPED (ftype) = 1;
11345   else if (producer_is_realview (cu->producer))
11346     /* RealView does not emit DW_AT_prototyped.  We can not
11347        distinguish prototyped and unprototyped functions; default to
11348        prototyped, since that is more common in modern code (and
11349        RealView warns about unprototyped functions).  */
11350     TYPE_PROTOTYPED (ftype) = 1;
11351
11352   /* Store the calling convention in the type if it's available in
11353      the subroutine die.  Otherwise set the calling convention to
11354      the default value DW_CC_normal.  */
11355   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
11356   if (attr)
11357     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
11358   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
11359     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
11360   else
11361     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
11362
11363   /* We need to add the subroutine type to the die immediately so
11364      we don't infinitely recurse when dealing with parameters
11365      declared as the same subroutine type.  */
11366   set_die_type (die, ftype, cu);
11367
11368   if (die->child != NULL)
11369     {
11370       struct type *void_type = objfile_type (objfile)->builtin_void;
11371       struct die_info *child_die;
11372       int nparams, iparams;
11373
11374       /* Count the number of parameters.
11375          FIXME: GDB currently ignores vararg functions, but knows about
11376          vararg member functions.  */
11377       nparams = 0;
11378       child_die = die->child;
11379       while (child_die && child_die->tag)
11380         {
11381           if (child_die->tag == DW_TAG_formal_parameter)
11382             nparams++;
11383           else if (child_die->tag == DW_TAG_unspecified_parameters)
11384             TYPE_VARARGS (ftype) = 1;
11385           child_die = sibling_die (child_die);
11386         }
11387
11388       /* Allocate storage for parameters and fill them in.  */
11389       TYPE_NFIELDS (ftype) = nparams;
11390       TYPE_FIELDS (ftype) = (struct field *)
11391         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
11392
11393       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
11394          even if we error out during the parameters reading below.  */
11395       for (iparams = 0; iparams < nparams; iparams++)
11396         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
11397
11398       iparams = 0;
11399       child_die = die->child;
11400       while (child_die && child_die->tag)
11401         {
11402           if (child_die->tag == DW_TAG_formal_parameter)
11403             {
11404               struct type *arg_type;
11405
11406               /* DWARF version 2 has no clean way to discern C++
11407                  static and non-static member functions.  G++ helps
11408                  GDB by marking the first parameter for non-static
11409                  member functions (which is the this pointer) as
11410                  artificial.  We pass this information to
11411                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
11412
11413                  DWARF version 3 added DW_AT_object_pointer, which GCC
11414                  4.5 does not yet generate.  */
11415               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
11416               if (attr)
11417                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
11418               else
11419                 {
11420                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
11421
11422                   /* GCC/43521: In java, the formal parameter
11423                      "this" is sometimes not marked with DW_AT_artificial.  */
11424                   if (cu->language == language_java)
11425                     {
11426                       const char *name = dwarf2_name (child_die, cu);
11427
11428                       if (name && !strcmp (name, "this"))
11429                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
11430                     }
11431                 }
11432               arg_type = die_type (child_die, cu);
11433
11434               /* RealView does not mark THIS as const, which the testsuite
11435                  expects.  GCC marks THIS as const in method definitions,
11436                  but not in the class specifications (GCC PR 43053).  */
11437               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
11438                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
11439                 {
11440                   int is_this = 0;
11441                   struct dwarf2_cu *arg_cu = cu;
11442                   const char *name = dwarf2_name (child_die, cu);
11443
11444                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
11445                   if (attr)
11446                     {
11447                       /* If the compiler emits this, use it.  */
11448                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
11449                         is_this = 1;
11450                     }
11451                   else if (name && strcmp (name, "this") == 0)
11452                     /* Function definitions will have the argument names.  */
11453                     is_this = 1;
11454                   else if (name == NULL && iparams == 0)
11455                     /* Declarations may not have the names, so like
11456                        elsewhere in GDB, assume an artificial first
11457                        argument is "this".  */
11458                     is_this = 1;
11459
11460                   if (is_this)
11461                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
11462                                              arg_type, 0);
11463                 }
11464
11465               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
11466               iparams++;
11467             }
11468           child_die = sibling_die (child_die);
11469         }
11470     }
11471
11472   return ftype;
11473 }
11474
11475 static struct type *
11476 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
11477 {
11478   struct objfile *objfile = cu->objfile;
11479   const char *name = NULL;
11480   struct type *this_type, *target_type;
11481
11482   name = dwarf2_full_name (NULL, die, cu);
11483   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
11484                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
11485   TYPE_NAME (this_type) = (char *) name;
11486   set_die_type (die, this_type, cu);
11487   target_type = die_type (die, cu);
11488   if (target_type != this_type)
11489     TYPE_TARGET_TYPE (this_type) = target_type;
11490   else
11491     {
11492       /* Self-referential typedefs are, it seems, not allowed by the DWARF
11493          spec and cause infinite loops in GDB.  */
11494       complaint (&symfile_complaints,
11495                  _("Self-referential DW_TAG_typedef "
11496                    "- DIE at 0x%x [in module %s]"),
11497                  die->offset.sect_off, objfile->name);
11498       TYPE_TARGET_TYPE (this_type) = NULL;
11499     }
11500   return this_type;
11501 }
11502
11503 /* Find a representation of a given base type and install
11504    it in the TYPE field of the die.  */
11505
11506 static struct type *
11507 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
11508 {
11509   struct objfile *objfile = cu->objfile;
11510   struct type *type;
11511   struct attribute *attr;
11512   int encoding = 0, size = 0;
11513   char *name;
11514   enum type_code code = TYPE_CODE_INT;
11515   int type_flags = 0;
11516   struct type *target_type = NULL;
11517
11518   attr = dwarf2_attr (die, DW_AT_encoding, cu);
11519   if (attr)
11520     {
11521       encoding = DW_UNSND (attr);
11522     }
11523   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11524   if (attr)
11525     {
11526       size = DW_UNSND (attr);
11527     }
11528   name = dwarf2_name (die, cu);
11529   if (!name)
11530     {
11531       complaint (&symfile_complaints,
11532                  _("DW_AT_name missing from DW_TAG_base_type"));
11533     }
11534
11535   switch (encoding)
11536     {
11537       case DW_ATE_address:
11538         /* Turn DW_ATE_address into a void * pointer.  */
11539         code = TYPE_CODE_PTR;
11540         type_flags |= TYPE_FLAG_UNSIGNED;
11541         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
11542         break;
11543       case DW_ATE_boolean:
11544         code = TYPE_CODE_BOOL;
11545         type_flags |= TYPE_FLAG_UNSIGNED;
11546         break;
11547       case DW_ATE_complex_float:
11548         code = TYPE_CODE_COMPLEX;
11549         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
11550         break;
11551       case DW_ATE_decimal_float:
11552         code = TYPE_CODE_DECFLOAT;
11553         break;
11554       case DW_ATE_float:
11555         code = TYPE_CODE_FLT;
11556         break;
11557       case DW_ATE_signed:
11558         break;
11559       case DW_ATE_unsigned:
11560         type_flags |= TYPE_FLAG_UNSIGNED;
11561         if (cu->language == language_fortran
11562             && name
11563             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
11564           code = TYPE_CODE_CHAR;
11565         break;
11566       case DW_ATE_signed_char:
11567         if (cu->language == language_ada || cu->language == language_m2
11568             || cu->language == language_pascal
11569             || cu->language == language_fortran)
11570           code = TYPE_CODE_CHAR;
11571         break;
11572       case DW_ATE_unsigned_char:
11573         if (cu->language == language_ada || cu->language == language_m2
11574             || cu->language == language_pascal
11575             || cu->language == language_fortran)
11576           code = TYPE_CODE_CHAR;
11577         type_flags |= TYPE_FLAG_UNSIGNED;
11578         break;
11579       case DW_ATE_UTF:
11580         /* We just treat this as an integer and then recognize the
11581            type by name elsewhere.  */
11582         break;
11583
11584       default:
11585         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
11586                    dwarf_type_encoding_name (encoding));
11587         break;
11588     }
11589
11590   type = init_type (code, size, type_flags, NULL, objfile);
11591   TYPE_NAME (type) = name;
11592   TYPE_TARGET_TYPE (type) = target_type;
11593
11594   if (name && strcmp (name, "char") == 0)
11595     TYPE_NOSIGN (type) = 1;
11596
11597   return set_die_type (die, type, cu);
11598 }
11599
11600 /* Read the given DW_AT_subrange DIE.  */
11601
11602 static struct type *
11603 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
11604 {
11605   struct type *base_type;
11606   struct type *range_type;
11607   struct attribute *attr;
11608   LONGEST low, high;
11609   int low_default_is_valid;
11610   char *name;
11611   LONGEST negative_mask;
11612
11613   base_type = die_type (die, cu);
11614   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
11615   check_typedef (base_type);
11616
11617   /* The die_type call above may have already set the type for this DIE.  */
11618   range_type = get_die_type (die, cu);
11619   if (range_type)
11620     return range_type;
11621
11622   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
11623      omitting DW_AT_lower_bound.  */
11624   switch (cu->language)
11625     {
11626     case language_c:
11627     case language_cplus:
11628       low = 0;
11629       low_default_is_valid = 1;
11630       break;
11631     case language_fortran:
11632       low = 1;
11633       low_default_is_valid = 1;
11634       break;
11635     case language_d:
11636     case language_java:
11637     case language_objc:
11638       low = 0;
11639       low_default_is_valid = (cu->header.version >= 4);
11640       break;
11641     case language_ada:
11642     case language_m2:
11643     case language_pascal:
11644       low = 1;
11645       low_default_is_valid = (cu->header.version >= 4);
11646       break;
11647     default:
11648       low = 0;
11649       low_default_is_valid = 0;
11650       break;
11651     }
11652
11653   /* FIXME: For variable sized arrays either of these could be
11654      a variable rather than a constant value.  We'll allow it,
11655      but we don't know how to handle it.  */
11656   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
11657   if (attr)
11658     low = dwarf2_get_attr_constant_value (attr, low);
11659   else if (!low_default_is_valid)
11660     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
11661                                       "- DIE at 0x%x [in module %s]"),
11662                die->offset.sect_off, cu->objfile->name);
11663
11664   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
11665   if (attr)
11666     {
11667       if (attr_form_is_block (attr) || is_ref_attr (attr))
11668         {
11669           /* GCC encodes arrays with unspecified or dynamic length
11670              with a DW_FORM_block1 attribute or a reference attribute.
11671              FIXME: GDB does not yet know how to handle dynamic
11672              arrays properly, treat them as arrays with unspecified
11673              length for now.
11674
11675              FIXME: jimb/2003-09-22: GDB does not really know
11676              how to handle arrays of unspecified length
11677              either; we just represent them as zero-length
11678              arrays.  Choose an appropriate upper bound given
11679              the lower bound we've computed above.  */
11680           high = low - 1;
11681         }
11682       else
11683         high = dwarf2_get_attr_constant_value (attr, 1);
11684     }
11685   else
11686     {
11687       attr = dwarf2_attr (die, DW_AT_count, cu);
11688       if (attr)
11689         {
11690           int count = dwarf2_get_attr_constant_value (attr, 1);
11691           high = low + count - 1;
11692         }
11693       else
11694         {
11695           /* Unspecified array length.  */
11696           high = low - 1;
11697         }
11698     }
11699
11700   /* Dwarf-2 specifications explicitly allows to create subrange types
11701      without specifying a base type.
11702      In that case, the base type must be set to the type of
11703      the lower bound, upper bound or count, in that order, if any of these
11704      three attributes references an object that has a type.
11705      If no base type is found, the Dwarf-2 specifications say that
11706      a signed integer type of size equal to the size of an address should
11707      be used.
11708      For the following C code: `extern char gdb_int [];'
11709      GCC produces an empty range DIE.
11710      FIXME: muller/2010-05-28: Possible references to object for low bound,
11711      high bound or count are not yet handled by this code.  */
11712   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
11713     {
11714       struct objfile *objfile = cu->objfile;
11715       struct gdbarch *gdbarch = get_objfile_arch (objfile);
11716       int addr_size = gdbarch_addr_bit (gdbarch) /8;
11717       struct type *int_type = objfile_type (objfile)->builtin_int;
11718
11719       /* Test "int", "long int", and "long long int" objfile types,
11720          and select the first one having a size above or equal to the
11721          architecture address size.  */
11722       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
11723         base_type = int_type;
11724       else
11725         {
11726           int_type = objfile_type (objfile)->builtin_long;
11727           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
11728             base_type = int_type;
11729           else
11730             {
11731               int_type = objfile_type (objfile)->builtin_long_long;
11732               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
11733                 base_type = int_type;
11734             }
11735         }
11736     }
11737
11738   negative_mask =
11739     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
11740   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
11741     low |= negative_mask;
11742   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
11743     high |= negative_mask;
11744
11745   range_type = create_range_type (NULL, base_type, low, high);
11746
11747   /* Mark arrays with dynamic length at least as an array of unspecified
11748      length.  GDB could check the boundary but before it gets implemented at
11749      least allow accessing the array elements.  */
11750   if (attr && attr_form_is_block (attr))
11751     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
11752
11753   /* Ada expects an empty array on no boundary attributes.  */
11754   if (attr == NULL && cu->language != language_ada)
11755     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
11756
11757   name = dwarf2_name (die, cu);
11758   if (name)
11759     TYPE_NAME (range_type) = name;
11760
11761   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11762   if (attr)
11763     TYPE_LENGTH (range_type) = DW_UNSND (attr);
11764
11765   set_die_type (die, range_type, cu);
11766
11767   /* set_die_type should be already done.  */
11768   set_descriptive_type (range_type, die, cu);
11769
11770   return range_type;
11771 }
11772
11773 static struct type *
11774 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
11775 {
11776   struct type *type;
11777
11778   /* For now, we only support the C meaning of an unspecified type: void.  */
11779
11780   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
11781   TYPE_NAME (type) = dwarf2_name (die, cu);
11782
11783   return set_die_type (die, type, cu);
11784 }
11785
11786 /* Read a single die and all its descendents.  Set the die's sibling
11787    field to NULL; set other fields in the die correctly, and set all
11788    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
11789    location of the info_ptr after reading all of those dies.  PARENT
11790    is the parent of the die in question.  */
11791
11792 static struct die_info *
11793 read_die_and_children (const struct die_reader_specs *reader,
11794                        gdb_byte *info_ptr,
11795                        gdb_byte **new_info_ptr,
11796                        struct die_info *parent)
11797 {
11798   struct die_info *die;
11799   gdb_byte *cur_ptr;
11800   int has_children;
11801
11802   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
11803   if (die == NULL)
11804     {
11805       *new_info_ptr = cur_ptr;
11806       return NULL;
11807     }
11808   store_in_ref_table (die, reader->cu);
11809
11810   if (has_children)
11811     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
11812   else
11813     {
11814       die->child = NULL;
11815       *new_info_ptr = cur_ptr;
11816     }
11817
11818   die->sibling = NULL;
11819   die->parent = parent;
11820   return die;
11821 }
11822
11823 /* Read a die, all of its descendents, and all of its siblings; set
11824    all of the fields of all of the dies correctly.  Arguments are as
11825    in read_die_and_children.  */
11826
11827 static struct die_info *
11828 read_die_and_siblings (const struct die_reader_specs *reader,
11829                        gdb_byte *info_ptr,
11830                        gdb_byte **new_info_ptr,
11831                        struct die_info *parent)
11832 {
11833   struct die_info *first_die, *last_sibling;
11834   gdb_byte *cur_ptr;
11835
11836   cur_ptr = info_ptr;
11837   first_die = last_sibling = NULL;
11838
11839   while (1)
11840     {
11841       struct die_info *die
11842         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
11843
11844       if (die == NULL)
11845         {
11846           *new_info_ptr = cur_ptr;
11847           return first_die;
11848         }
11849
11850       if (!first_die)
11851         first_die = die;
11852       else
11853         last_sibling->sibling = die;
11854
11855       last_sibling = die;
11856     }
11857 }
11858
11859 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
11860    attributes.
11861    The caller is responsible for filling in the extra attributes
11862    and updating (*DIEP)->num_attrs.
11863    Set DIEP to point to a newly allocated die with its information,
11864    except for its child, sibling, and parent fields.
11865    Set HAS_CHILDREN to tell whether the die has children or not.  */
11866
11867 static gdb_byte *
11868 read_full_die_1 (const struct die_reader_specs *reader,
11869                  struct die_info **diep, gdb_byte *info_ptr,
11870                  int *has_children, int num_extra_attrs)
11871 {
11872   unsigned int abbrev_number, bytes_read, i;
11873   sect_offset offset;
11874   struct abbrev_info *abbrev;
11875   struct die_info *die;
11876   struct dwarf2_cu *cu = reader->cu;
11877   bfd *abfd = reader->abfd;
11878
11879   offset.sect_off = info_ptr - reader->buffer;
11880   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11881   info_ptr += bytes_read;
11882   if (!abbrev_number)
11883     {
11884       *diep = NULL;
11885       *has_children = 0;
11886       return info_ptr;
11887     }
11888
11889   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
11890   if (!abbrev)
11891     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
11892            abbrev_number,
11893            bfd_get_filename (abfd));
11894
11895   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
11896   die->offset = offset;
11897   die->tag = abbrev->tag;
11898   die->abbrev = abbrev_number;
11899
11900   /* Make the result usable.
11901      The caller needs to update num_attrs after adding the extra
11902      attributes.  */
11903   die->num_attrs = abbrev->num_attrs;
11904
11905   for (i = 0; i < abbrev->num_attrs; ++i)
11906     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
11907                                info_ptr);
11908
11909   *diep = die;
11910   *has_children = abbrev->has_children;
11911   return info_ptr;
11912 }
11913
11914 /* Read a die and all its attributes.
11915    Set DIEP to point to a newly allocated die with its information,
11916    except for its child, sibling, and parent fields.
11917    Set HAS_CHILDREN to tell whether the die has children or not.  */
11918
11919 static gdb_byte *
11920 read_full_die (const struct die_reader_specs *reader,
11921                struct die_info **diep, gdb_byte *info_ptr,
11922                int *has_children)
11923 {
11924   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
11925 }
11926 \f
11927 /* Abbreviation tables.
11928
11929    In DWARF version 2, the description of the debugging information is
11930    stored in a separate .debug_abbrev section.  Before we read any
11931    dies from a section we read in all abbreviations and install them
11932    in a hash table.  */
11933
11934 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
11935
11936 static struct abbrev_info *
11937 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
11938 {
11939   struct abbrev_info *abbrev;
11940
11941   abbrev = (struct abbrev_info *)
11942     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
11943   memset (abbrev, 0, sizeof (struct abbrev_info));
11944   return abbrev;
11945 }
11946
11947 /* Add an abbreviation to the table.  */
11948
11949 static void
11950 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
11951                          unsigned int abbrev_number,
11952                          struct abbrev_info *abbrev)
11953 {
11954   unsigned int hash_number;
11955
11956   hash_number = abbrev_number % ABBREV_HASH_SIZE;
11957   abbrev->next = abbrev_table->abbrevs[hash_number];
11958   abbrev_table->abbrevs[hash_number] = abbrev;
11959 }
11960
11961 /* Look up an abbrev in the table.
11962    Returns NULL if the abbrev is not found.  */
11963
11964 static struct abbrev_info *
11965 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
11966                             unsigned int abbrev_number)
11967 {
11968   unsigned int hash_number;
11969   struct abbrev_info *abbrev;
11970
11971   hash_number = abbrev_number % ABBREV_HASH_SIZE;
11972   abbrev = abbrev_table->abbrevs[hash_number];
11973
11974   while (abbrev)
11975     {
11976       if (abbrev->number == abbrev_number)
11977         return abbrev;
11978       abbrev = abbrev->next;
11979     }
11980   return NULL;
11981 }
11982
11983 /* Read in an abbrev table.  */
11984
11985 static struct abbrev_table *
11986 abbrev_table_read_table (struct dwarf2_section_info *section,
11987                          sect_offset offset)
11988 {
11989   struct objfile *objfile = dwarf2_per_objfile->objfile;
11990   bfd *abfd = section->asection->owner;
11991   struct abbrev_table *abbrev_table;
11992   gdb_byte *abbrev_ptr;
11993   struct abbrev_info *cur_abbrev;
11994   unsigned int abbrev_number, bytes_read, abbrev_name;
11995   unsigned int abbrev_form;
11996   struct attr_abbrev *cur_attrs;
11997   unsigned int allocated_attrs;
11998
11999   abbrev_table = XMALLOC (struct abbrev_table);
12000   abbrev_table->offset = offset;
12001   obstack_init (&abbrev_table->abbrev_obstack);
12002   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
12003                                          (ABBREV_HASH_SIZE
12004                                           * sizeof (struct abbrev_info *)));
12005   memset (abbrev_table->abbrevs, 0,
12006           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
12007
12008   dwarf2_read_section (objfile, section);
12009   abbrev_ptr = section->buffer + offset.sect_off;
12010   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12011   abbrev_ptr += bytes_read;
12012
12013   allocated_attrs = ATTR_ALLOC_CHUNK;
12014   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
12015
12016   /* Loop until we reach an abbrev number of 0.  */
12017   while (abbrev_number)
12018     {
12019       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
12020
12021       /* read in abbrev header */
12022       cur_abbrev->number = abbrev_number;
12023       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12024       abbrev_ptr += bytes_read;
12025       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
12026       abbrev_ptr += 1;
12027
12028       /* now read in declarations */
12029       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12030       abbrev_ptr += bytes_read;
12031       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12032       abbrev_ptr += bytes_read;
12033       while (abbrev_name)
12034         {
12035           if (cur_abbrev->num_attrs == allocated_attrs)
12036             {
12037               allocated_attrs += ATTR_ALLOC_CHUNK;
12038               cur_attrs
12039                 = xrealloc (cur_attrs, (allocated_attrs
12040                                         * sizeof (struct attr_abbrev)));
12041             }
12042
12043           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
12044           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
12045           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12046           abbrev_ptr += bytes_read;
12047           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12048           abbrev_ptr += bytes_read;
12049         }
12050
12051       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
12052                                          (cur_abbrev->num_attrs
12053                                           * sizeof (struct attr_abbrev)));
12054       memcpy (cur_abbrev->attrs, cur_attrs,
12055               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
12056
12057       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
12058
12059       /* Get next abbreviation.
12060          Under Irix6 the abbreviations for a compilation unit are not
12061          always properly terminated with an abbrev number of 0.
12062          Exit loop if we encounter an abbreviation which we have
12063          already read (which means we are about to read the abbreviations
12064          for the next compile unit) or if the end of the abbreviation
12065          table is reached.  */
12066       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
12067         break;
12068       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12069       abbrev_ptr += bytes_read;
12070       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
12071         break;
12072     }
12073
12074   xfree (cur_attrs);
12075   return abbrev_table;
12076 }
12077
12078 /* Free the resources held by ABBREV_TABLE.  */
12079
12080 static void
12081 abbrev_table_free (struct abbrev_table *abbrev_table)
12082 {
12083   obstack_free (&abbrev_table->abbrev_obstack, NULL);
12084   xfree (abbrev_table);
12085 }
12086
12087 /* Same as abbrev_table_free but as a cleanup.
12088    We pass in a pointer to the pointer to the table so that we can
12089    set the pointer to NULL when we're done.  It also simplifies
12090    build_type_unit_groups.  */
12091
12092 static void
12093 abbrev_table_free_cleanup (void *table_ptr)
12094 {
12095   struct abbrev_table **abbrev_table_ptr = table_ptr;
12096
12097   if (*abbrev_table_ptr != NULL)
12098     abbrev_table_free (*abbrev_table_ptr);
12099   *abbrev_table_ptr = NULL;
12100 }
12101
12102 /* Read the abbrev table for CU from ABBREV_SECTION.  */
12103
12104 static void
12105 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
12106                      struct dwarf2_section_info *abbrev_section)
12107 {
12108   cu->abbrev_table =
12109     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
12110 }
12111
12112 /* Release the memory used by the abbrev table for a compilation unit.  */
12113
12114 static void
12115 dwarf2_free_abbrev_table (void *ptr_to_cu)
12116 {
12117   struct dwarf2_cu *cu = ptr_to_cu;
12118
12119   abbrev_table_free (cu->abbrev_table);
12120   /* Set this to NULL so that we SEGV if we try to read it later,
12121      and also because free_comp_unit verifies this is NULL.  */
12122   cu->abbrev_table = NULL;
12123 }
12124 \f
12125 /* Returns nonzero if TAG represents a type that we might generate a partial
12126    symbol for.  */
12127
12128 static int
12129 is_type_tag_for_partial (int tag)
12130 {
12131   switch (tag)
12132     {
12133 #if 0
12134     /* Some types that would be reasonable to generate partial symbols for,
12135        that we don't at present.  */
12136     case DW_TAG_array_type:
12137     case DW_TAG_file_type:
12138     case DW_TAG_ptr_to_member_type:
12139     case DW_TAG_set_type:
12140     case DW_TAG_string_type:
12141     case DW_TAG_subroutine_type:
12142 #endif
12143     case DW_TAG_base_type:
12144     case DW_TAG_class_type:
12145     case DW_TAG_interface_type:
12146     case DW_TAG_enumeration_type:
12147     case DW_TAG_structure_type:
12148     case DW_TAG_subrange_type:
12149     case DW_TAG_typedef:
12150     case DW_TAG_union_type:
12151       return 1;
12152     default:
12153       return 0;
12154     }
12155 }
12156
12157 /* Load all DIEs that are interesting for partial symbols into memory.  */
12158
12159 static struct partial_die_info *
12160 load_partial_dies (const struct die_reader_specs *reader,
12161                    gdb_byte *info_ptr, int building_psymtab)
12162 {
12163   struct dwarf2_cu *cu = reader->cu;
12164   struct objfile *objfile = cu->objfile;
12165   struct partial_die_info *part_die;
12166   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
12167   struct abbrev_info *abbrev;
12168   unsigned int bytes_read;
12169   unsigned int load_all = 0;
12170   int nesting_level = 1;
12171
12172   parent_die = NULL;
12173   last_die = NULL;
12174
12175   gdb_assert (cu->per_cu != NULL);
12176   if (cu->per_cu->load_all_dies)
12177     load_all = 1;
12178
12179   cu->partial_dies
12180     = htab_create_alloc_ex (cu->header.length / 12,
12181                             partial_die_hash,
12182                             partial_die_eq,
12183                             NULL,
12184                             &cu->comp_unit_obstack,
12185                             hashtab_obstack_allocate,
12186                             dummy_obstack_deallocate);
12187
12188   part_die = obstack_alloc (&cu->comp_unit_obstack,
12189                             sizeof (struct partial_die_info));
12190
12191   while (1)
12192     {
12193       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
12194
12195       /* A NULL abbrev means the end of a series of children.  */
12196       if (abbrev == NULL)
12197         {
12198           if (--nesting_level == 0)
12199             {
12200               /* PART_DIE was probably the last thing allocated on the
12201                  comp_unit_obstack, so we could call obstack_free
12202                  here.  We don't do that because the waste is small,
12203                  and will be cleaned up when we're done with this
12204                  compilation unit.  This way, we're also more robust
12205                  against other users of the comp_unit_obstack.  */
12206               return first_die;
12207             }
12208           info_ptr += bytes_read;
12209           last_die = parent_die;
12210           parent_die = parent_die->die_parent;
12211           continue;
12212         }
12213
12214       /* Check for template arguments.  We never save these; if
12215          they're seen, we just mark the parent, and go on our way.  */
12216       if (parent_die != NULL
12217           && cu->language == language_cplus
12218           && (abbrev->tag == DW_TAG_template_type_param
12219               || abbrev->tag == DW_TAG_template_value_param))
12220         {
12221           parent_die->has_template_arguments = 1;
12222
12223           if (!load_all)
12224             {
12225               /* We don't need a partial DIE for the template argument.  */
12226               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
12227               continue;
12228             }
12229         }
12230
12231       /* We only recurse into c++ subprograms looking for template arguments.
12232          Skip their other children.  */
12233       if (!load_all
12234           && cu->language == language_cplus
12235           && parent_die != NULL
12236           && parent_die->tag == DW_TAG_subprogram)
12237         {
12238           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
12239           continue;
12240         }
12241
12242       /* Check whether this DIE is interesting enough to save.  Normally
12243          we would not be interested in members here, but there may be
12244          later variables referencing them via DW_AT_specification (for
12245          static members).  */
12246       if (!load_all
12247           && !is_type_tag_for_partial (abbrev->tag)
12248           && abbrev->tag != DW_TAG_constant
12249           && abbrev->tag != DW_TAG_enumerator
12250           && abbrev->tag != DW_TAG_subprogram
12251           && abbrev->tag != DW_TAG_lexical_block
12252           && abbrev->tag != DW_TAG_variable
12253           && abbrev->tag != DW_TAG_namespace
12254           && abbrev->tag != DW_TAG_module
12255           && abbrev->tag != DW_TAG_member
12256           && abbrev->tag != DW_TAG_imported_unit)
12257         {
12258           /* Otherwise we skip to the next sibling, if any.  */
12259           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
12260           continue;
12261         }
12262
12263       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
12264                                    info_ptr);
12265
12266       /* This two-pass algorithm for processing partial symbols has a
12267          high cost in cache pressure.  Thus, handle some simple cases
12268          here which cover the majority of C partial symbols.  DIEs
12269          which neither have specification tags in them, nor could have
12270          specification tags elsewhere pointing at them, can simply be
12271          processed and discarded.
12272
12273          This segment is also optional; scan_partial_symbols and
12274          add_partial_symbol will handle these DIEs if we chain
12275          them in normally.  When compilers which do not emit large
12276          quantities of duplicate debug information are more common,
12277          this code can probably be removed.  */
12278
12279       /* Any complete simple types at the top level (pretty much all
12280          of them, for a language without namespaces), can be processed
12281          directly.  */
12282       if (parent_die == NULL
12283           && part_die->has_specification == 0
12284           && part_die->is_declaration == 0
12285           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
12286               || part_die->tag == DW_TAG_base_type
12287               || part_die->tag == DW_TAG_subrange_type))
12288         {
12289           if (building_psymtab && part_die->name != NULL)
12290             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
12291                                  VAR_DOMAIN, LOC_TYPEDEF,
12292                                  &objfile->static_psymbols,
12293                                  0, (CORE_ADDR) 0, cu->language, objfile);
12294           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
12295           continue;
12296         }
12297
12298       /* The exception for DW_TAG_typedef with has_children above is
12299          a workaround of GCC PR debug/47510.  In the case of this complaint
12300          type_name_no_tag_or_error will error on such types later.
12301
12302          GDB skipped children of DW_TAG_typedef by the shortcut above and then
12303          it could not find the child DIEs referenced later, this is checked
12304          above.  In correct DWARF DW_TAG_typedef should have no children.  */
12305
12306       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
12307         complaint (&symfile_complaints,
12308                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
12309                      "- DIE at 0x%x [in module %s]"),
12310                    part_die->offset.sect_off, objfile->name);
12311
12312       /* If we're at the second level, and we're an enumerator, and
12313          our parent has no specification (meaning possibly lives in a
12314          namespace elsewhere), then we can add the partial symbol now
12315          instead of queueing it.  */
12316       if (part_die->tag == DW_TAG_enumerator
12317           && parent_die != NULL
12318           && parent_die->die_parent == NULL
12319           && parent_die->tag == DW_TAG_enumeration_type
12320           && parent_die->has_specification == 0)
12321         {
12322           if (part_die->name == NULL)
12323             complaint (&symfile_complaints,
12324                        _("malformed enumerator DIE ignored"));
12325           else if (building_psymtab)
12326             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
12327                                  VAR_DOMAIN, LOC_CONST,
12328                                  (cu->language == language_cplus
12329                                   || cu->language == language_java)
12330                                  ? &objfile->global_psymbols
12331                                  : &objfile->static_psymbols,
12332                                  0, (CORE_ADDR) 0, cu->language, objfile);
12333
12334           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
12335           continue;
12336         }
12337
12338       /* We'll save this DIE so link it in.  */
12339       part_die->die_parent = parent_die;
12340       part_die->die_sibling = NULL;
12341       part_die->die_child = NULL;
12342
12343       if (last_die && last_die == parent_die)
12344         last_die->die_child = part_die;
12345       else if (last_die)
12346         last_die->die_sibling = part_die;
12347
12348       last_die = part_die;
12349
12350       if (first_die == NULL)
12351         first_die = part_die;
12352
12353       /* Maybe add the DIE to the hash table.  Not all DIEs that we
12354          find interesting need to be in the hash table, because we
12355          also have the parent/sibling/child chains; only those that we
12356          might refer to by offset later during partial symbol reading.
12357
12358          For now this means things that might have be the target of a
12359          DW_AT_specification, DW_AT_abstract_origin, or
12360          DW_AT_extension.  DW_AT_extension will refer only to
12361          namespaces; DW_AT_abstract_origin refers to functions (and
12362          many things under the function DIE, but we do not recurse
12363          into function DIEs during partial symbol reading) and
12364          possibly variables as well; DW_AT_specification refers to
12365          declarations.  Declarations ought to have the DW_AT_declaration
12366          flag.  It happens that GCC forgets to put it in sometimes, but
12367          only for functions, not for types.
12368
12369          Adding more things than necessary to the hash table is harmless
12370          except for the performance cost.  Adding too few will result in
12371          wasted time in find_partial_die, when we reread the compilation
12372          unit with load_all_dies set.  */
12373
12374       if (load_all
12375           || abbrev->tag == DW_TAG_constant
12376           || abbrev->tag == DW_TAG_subprogram
12377           || abbrev->tag == DW_TAG_variable
12378           || abbrev->tag == DW_TAG_namespace
12379           || part_die->is_declaration)
12380         {
12381           void **slot;
12382
12383           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
12384                                            part_die->offset.sect_off, INSERT);
12385           *slot = part_die;
12386         }
12387
12388       part_die = obstack_alloc (&cu->comp_unit_obstack,
12389                                 sizeof (struct partial_die_info));
12390
12391       /* For some DIEs we want to follow their children (if any).  For C
12392          we have no reason to follow the children of structures; for other
12393          languages we have to, so that we can get at method physnames
12394          to infer fully qualified class names, for DW_AT_specification,
12395          and for C++ template arguments.  For C++, we also look one level
12396          inside functions to find template arguments (if the name of the
12397          function does not already contain the template arguments).
12398
12399          For Ada, we need to scan the children of subprograms and lexical
12400          blocks as well because Ada allows the definition of nested
12401          entities that could be interesting for the debugger, such as
12402          nested subprograms for instance.  */
12403       if (last_die->has_children
12404           && (load_all
12405               || last_die->tag == DW_TAG_namespace
12406               || last_die->tag == DW_TAG_module
12407               || last_die->tag == DW_TAG_enumeration_type
12408               || (cu->language == language_cplus
12409                   && last_die->tag == DW_TAG_subprogram
12410                   && (last_die->name == NULL
12411                       || strchr (last_die->name, '<') == NULL))
12412               || (cu->language != language_c
12413                   && (last_die->tag == DW_TAG_class_type
12414                       || last_die->tag == DW_TAG_interface_type
12415                       || last_die->tag == DW_TAG_structure_type
12416                       || last_die->tag == DW_TAG_union_type))
12417               || (cu->language == language_ada
12418                   && (last_die->tag == DW_TAG_subprogram
12419                       || last_die->tag == DW_TAG_lexical_block))))
12420         {
12421           nesting_level++;
12422           parent_die = last_die;
12423           continue;
12424         }
12425
12426       /* Otherwise we skip to the next sibling, if any.  */
12427       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
12428
12429       /* Back to the top, do it again.  */
12430     }
12431 }
12432
12433 /* Read a minimal amount of information into the minimal die structure.  */
12434
12435 static gdb_byte *
12436 read_partial_die (const struct die_reader_specs *reader,
12437                   struct partial_die_info *part_die,
12438                   struct abbrev_info *abbrev, unsigned int abbrev_len,
12439                   gdb_byte *info_ptr)
12440 {
12441   struct dwarf2_cu *cu = reader->cu;
12442   struct objfile *objfile = cu->objfile;
12443   gdb_byte *buffer = reader->buffer;
12444   unsigned int i;
12445   struct attribute attr;
12446   int has_low_pc_attr = 0;
12447   int has_high_pc_attr = 0;
12448   int high_pc_relative = 0;
12449
12450   memset (part_die, 0, sizeof (struct partial_die_info));
12451
12452   part_die->offset.sect_off = info_ptr - buffer;
12453
12454   info_ptr += abbrev_len;
12455
12456   if (abbrev == NULL)
12457     return info_ptr;
12458
12459   part_die->tag = abbrev->tag;
12460   part_die->has_children = abbrev->has_children;
12461
12462   for (i = 0; i < abbrev->num_attrs; ++i)
12463     {
12464       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
12465
12466       /* Store the data if it is of an attribute we want to keep in a
12467          partial symbol table.  */
12468       switch (attr.name)
12469         {
12470         case DW_AT_name:
12471           switch (part_die->tag)
12472             {
12473             case DW_TAG_compile_unit:
12474             case DW_TAG_partial_unit:
12475             case DW_TAG_type_unit:
12476               /* Compilation units have a DW_AT_name that is a filename, not
12477                  a source language identifier.  */
12478             case DW_TAG_enumeration_type:
12479             case DW_TAG_enumerator:
12480               /* These tags always have simple identifiers already; no need
12481                  to canonicalize them.  */
12482               part_die->name = DW_STRING (&attr);
12483               break;
12484             default:
12485               part_die->name
12486                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
12487                                             &objfile->objfile_obstack);
12488               break;
12489             }
12490           break;
12491         case DW_AT_linkage_name:
12492         case DW_AT_MIPS_linkage_name:
12493           /* Note that both forms of linkage name might appear.  We
12494              assume they will be the same, and we only store the last
12495              one we see.  */
12496           if (cu->language == language_ada)
12497             part_die->name = DW_STRING (&attr);
12498           part_die->linkage_name = DW_STRING (&attr);
12499           break;
12500         case DW_AT_low_pc:
12501           has_low_pc_attr = 1;
12502           part_die->lowpc = DW_ADDR (&attr);
12503           break;
12504         case DW_AT_high_pc:
12505           has_high_pc_attr = 1;
12506           if (attr.form == DW_FORM_addr
12507               || attr.form == DW_FORM_GNU_addr_index)
12508             part_die->highpc = DW_ADDR (&attr);
12509           else
12510             {
12511               high_pc_relative = 1;
12512               part_die->highpc = DW_UNSND (&attr);
12513             }
12514           break;
12515         case DW_AT_location:
12516           /* Support the .debug_loc offsets.  */
12517           if (attr_form_is_block (&attr))
12518             {
12519                part_die->d.locdesc = DW_BLOCK (&attr);
12520             }
12521           else if (attr_form_is_section_offset (&attr))
12522             {
12523               dwarf2_complex_location_expr_complaint ();
12524             }
12525           else
12526             {
12527               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12528                                                      "partial symbol information");
12529             }
12530           break;
12531         case DW_AT_external:
12532           part_die->is_external = DW_UNSND (&attr);
12533           break;
12534         case DW_AT_declaration:
12535           part_die->is_declaration = DW_UNSND (&attr);
12536           break;
12537         case DW_AT_type:
12538           part_die->has_type = 1;
12539           break;
12540         case DW_AT_abstract_origin:
12541         case DW_AT_specification:
12542         case DW_AT_extension:
12543           part_die->has_specification = 1;
12544           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
12545           break;
12546         case DW_AT_sibling:
12547           /* Ignore absolute siblings, they might point outside of
12548              the current compile unit.  */
12549           if (attr.form == DW_FORM_ref_addr)
12550             complaint (&symfile_complaints,
12551                        _("ignoring absolute DW_AT_sibling"));
12552           else
12553             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
12554           break;
12555         case DW_AT_byte_size:
12556           part_die->has_byte_size = 1;
12557           break;
12558         case DW_AT_calling_convention:
12559           /* DWARF doesn't provide a way to identify a program's source-level
12560              entry point.  DW_AT_calling_convention attributes are only meant
12561              to describe functions' calling conventions.
12562
12563              However, because it's a necessary piece of information in
12564              Fortran, and because DW_CC_program is the only piece of debugging
12565              information whose definition refers to a 'main program' at all,
12566              several compilers have begun marking Fortran main programs with
12567              DW_CC_program --- even when those functions use the standard
12568              calling conventions.
12569
12570              So until DWARF specifies a way to provide this information and
12571              compilers pick up the new representation, we'll support this
12572              practice.  */
12573           if (DW_UNSND (&attr) == DW_CC_program
12574               && cu->language == language_fortran)
12575             {
12576               set_main_name (part_die->name);
12577
12578               /* As this DIE has a static linkage the name would be difficult
12579                  to look up later.  */
12580               language_of_main = language_fortran;
12581             }
12582           break;
12583         case DW_AT_inline:
12584           if (DW_UNSND (&attr) == DW_INL_inlined
12585               || DW_UNSND (&attr) == DW_INL_declared_inlined)
12586             part_die->may_be_inlined = 1;
12587           break;
12588
12589         case DW_AT_import:
12590           if (part_die->tag == DW_TAG_imported_unit)
12591             part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
12592           break;
12593
12594         default:
12595           break;
12596         }
12597     }
12598
12599   if (high_pc_relative)
12600     part_die->highpc += part_die->lowpc;
12601
12602   if (has_low_pc_attr && has_high_pc_attr)
12603     {
12604       /* When using the GNU linker, .gnu.linkonce. sections are used to
12605          eliminate duplicate copies of functions and vtables and such.
12606          The linker will arbitrarily choose one and discard the others.
12607          The AT_*_pc values for such functions refer to local labels in
12608          these sections.  If the section from that file was discarded, the
12609          labels are not in the output, so the relocs get a value of 0.
12610          If this is a discarded function, mark the pc bounds as invalid,
12611          so that GDB will ignore it.  */
12612       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
12613         {
12614           struct gdbarch *gdbarch = get_objfile_arch (objfile);
12615
12616           complaint (&symfile_complaints,
12617                      _("DW_AT_low_pc %s is zero "
12618                        "for DIE at 0x%x [in module %s]"),
12619                      paddress (gdbarch, part_die->lowpc),
12620                      part_die->offset.sect_off, objfile->name);
12621         }
12622       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
12623       else if (part_die->lowpc >= part_die->highpc)
12624         {
12625           struct gdbarch *gdbarch = get_objfile_arch (objfile);
12626
12627           complaint (&symfile_complaints,
12628                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
12629                        "for DIE at 0x%x [in module %s]"),
12630                      paddress (gdbarch, part_die->lowpc),
12631                      paddress (gdbarch, part_die->highpc),
12632                      part_die->offset.sect_off, objfile->name);
12633         }
12634       else
12635         part_die->has_pc_info = 1;
12636     }
12637
12638   return info_ptr;
12639 }
12640
12641 /* Find a cached partial DIE at OFFSET in CU.  */
12642
12643 static struct partial_die_info *
12644 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
12645 {
12646   struct partial_die_info *lookup_die = NULL;
12647   struct partial_die_info part_die;
12648
12649   part_die.offset = offset;
12650   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
12651                                     offset.sect_off);
12652
12653   return lookup_die;
12654 }
12655
12656 /* Find a partial DIE at OFFSET, which may or may not be in CU,
12657    except in the case of .debug_types DIEs which do not reference
12658    outside their CU (they do however referencing other types via
12659    DW_FORM_ref_sig8).  */
12660
12661 static struct partial_die_info *
12662 find_partial_die (sect_offset offset, struct dwarf2_cu *cu)
12663 {
12664   struct objfile *objfile = cu->objfile;
12665   struct dwarf2_per_cu_data *per_cu = NULL;
12666   struct partial_die_info *pd = NULL;
12667
12668   if (offset_in_cu_p (&cu->header, offset))
12669     {
12670       pd = find_partial_die_in_comp_unit (offset, cu);
12671       if (pd != NULL)
12672         return pd;
12673       /* We missed recording what we needed.
12674          Load all dies and try again.  */
12675       per_cu = cu->per_cu;
12676     }
12677   else
12678     {
12679       /* TUs don't reference other CUs/TUs (except via type signatures).  */
12680       if (cu->per_cu->is_debug_types)
12681         {
12682           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
12683                    " external reference to offset 0x%lx [in module %s].\n"),
12684                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
12685                  bfd_get_filename (objfile->obfd));
12686         }
12687       per_cu = dwarf2_find_containing_comp_unit (offset, objfile);
12688
12689       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
12690         load_partial_comp_unit (per_cu);
12691
12692       per_cu->cu->last_used = 0;
12693       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
12694     }
12695
12696   /* If we didn't find it, and not all dies have been loaded,
12697      load them all and try again.  */
12698
12699   if (pd == NULL && per_cu->load_all_dies == 0)
12700     {
12701       per_cu->load_all_dies = 1;
12702
12703       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
12704          THIS_CU->cu may already be in use.  So we can't just free it and
12705          replace its DIEs with the ones we read in.  Instead, we leave those
12706          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
12707          and clobber THIS_CU->cu->partial_dies with the hash table for the new
12708          set.  */
12709       load_partial_comp_unit (per_cu);
12710
12711       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
12712     }
12713
12714   if (pd == NULL)
12715     internal_error (__FILE__, __LINE__,
12716                     _("could not find partial DIE 0x%x "
12717                       "in cache [from module %s]\n"),
12718                     offset.sect_off, bfd_get_filename (objfile->obfd));
12719   return pd;
12720 }
12721
12722 /* See if we can figure out if the class lives in a namespace.  We do
12723    this by looking for a member function; its demangled name will
12724    contain namespace info, if there is any.  */
12725
12726 static void
12727 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
12728                                   struct dwarf2_cu *cu)
12729 {
12730   /* NOTE: carlton/2003-10-07: Getting the info this way changes
12731      what template types look like, because the demangler
12732      frequently doesn't give the same name as the debug info.  We
12733      could fix this by only using the demangled name to get the
12734      prefix (but see comment in read_structure_type).  */
12735
12736   struct partial_die_info *real_pdi;
12737   struct partial_die_info *child_pdi;
12738
12739   /* If this DIE (this DIE's specification, if any) has a parent, then
12740      we should not do this.  We'll prepend the parent's fully qualified
12741      name when we create the partial symbol.  */
12742
12743   real_pdi = struct_pdi;
12744   while (real_pdi->has_specification)
12745     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
12746
12747   if (real_pdi->die_parent != NULL)
12748     return;
12749
12750   for (child_pdi = struct_pdi->die_child;
12751        child_pdi != NULL;
12752        child_pdi = child_pdi->die_sibling)
12753     {
12754       if (child_pdi->tag == DW_TAG_subprogram
12755           && child_pdi->linkage_name != NULL)
12756         {
12757           char *actual_class_name
12758             = language_class_name_from_physname (cu->language_defn,
12759                                                  child_pdi->linkage_name);
12760           if (actual_class_name != NULL)
12761             {
12762               struct_pdi->name
12763                 = obsavestring (actual_class_name,
12764                                 strlen (actual_class_name),
12765                                 &cu->objfile->objfile_obstack);
12766               xfree (actual_class_name);
12767             }
12768           break;
12769         }
12770     }
12771 }
12772
12773 /* Adjust PART_DIE before generating a symbol for it.  This function
12774    may set the is_external flag or change the DIE's name.  */
12775
12776 static void
12777 fixup_partial_die (struct partial_die_info *part_die,
12778                    struct dwarf2_cu *cu)
12779 {
12780   /* Once we've fixed up a die, there's no point in doing so again.
12781      This also avoids a memory leak if we were to call
12782      guess_partial_die_structure_name multiple times.  */
12783   if (part_die->fixup_called)
12784     return;
12785
12786   /* If we found a reference attribute and the DIE has no name, try
12787      to find a name in the referred to DIE.  */
12788
12789   if (part_die->name == NULL && part_die->has_specification)
12790     {
12791       struct partial_die_info *spec_die;
12792
12793       spec_die = find_partial_die (part_die->spec_offset, cu);
12794
12795       fixup_partial_die (spec_die, cu);
12796
12797       if (spec_die->name)
12798         {
12799           part_die->name = spec_die->name;
12800
12801           /* Copy DW_AT_external attribute if it is set.  */
12802           if (spec_die->is_external)
12803             part_die->is_external = spec_die->is_external;
12804         }
12805     }
12806
12807   /* Set default names for some unnamed DIEs.  */
12808
12809   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
12810     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
12811
12812   /* If there is no parent die to provide a namespace, and there are
12813      children, see if we can determine the namespace from their linkage
12814      name.  */
12815   if (cu->language == language_cplus
12816       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
12817       && part_die->die_parent == NULL
12818       && part_die->has_children
12819       && (part_die->tag == DW_TAG_class_type
12820           || part_die->tag == DW_TAG_structure_type
12821           || part_die->tag == DW_TAG_union_type))
12822     guess_partial_die_structure_name (part_die, cu);
12823
12824   /* GCC might emit a nameless struct or union that has a linkage
12825      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
12826   if (part_die->name == NULL
12827       && (part_die->tag == DW_TAG_class_type
12828           || part_die->tag == DW_TAG_interface_type
12829           || part_die->tag == DW_TAG_structure_type
12830           || part_die->tag == DW_TAG_union_type)
12831       && part_die->linkage_name != NULL)
12832     {
12833       char *demangled;
12834
12835       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
12836       if (demangled)
12837         {
12838           const char *base;
12839
12840           /* Strip any leading namespaces/classes, keep only the base name.
12841              DW_AT_name for named DIEs does not contain the prefixes.  */
12842           base = strrchr (demangled, ':');
12843           if (base && base > demangled && base[-1] == ':')
12844             base++;
12845           else
12846             base = demangled;
12847
12848           part_die->name = obsavestring (base, strlen (base),
12849                                          &cu->objfile->objfile_obstack);
12850           xfree (demangled);
12851         }
12852     }
12853
12854   part_die->fixup_called = 1;
12855 }
12856
12857 /* Read an attribute value described by an attribute form.  */
12858
12859 static gdb_byte *
12860 read_attribute_value (const struct die_reader_specs *reader,
12861                       struct attribute *attr, unsigned form,
12862                       gdb_byte *info_ptr)
12863 {
12864   struct dwarf2_cu *cu = reader->cu;
12865   bfd *abfd = reader->abfd;
12866   struct comp_unit_head *cu_header = &cu->header;
12867   unsigned int bytes_read;
12868   struct dwarf_block *blk;
12869
12870   attr->form = form;
12871   switch (form)
12872     {
12873     case DW_FORM_ref_addr:
12874       if (cu->header.version == 2)
12875         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
12876       else
12877         DW_UNSND (attr) = read_offset (abfd, info_ptr,
12878                                        &cu->header, &bytes_read);
12879       info_ptr += bytes_read;
12880       break;
12881     case DW_FORM_addr:
12882       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
12883       info_ptr += bytes_read;
12884       break;
12885     case DW_FORM_block2:
12886       blk = dwarf_alloc_block (cu);
12887       blk->size = read_2_bytes (abfd, info_ptr);
12888       info_ptr += 2;
12889       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12890       info_ptr += blk->size;
12891       DW_BLOCK (attr) = blk;
12892       break;
12893     case DW_FORM_block4:
12894       blk = dwarf_alloc_block (cu);
12895       blk->size = read_4_bytes (abfd, info_ptr);
12896       info_ptr += 4;
12897       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12898       info_ptr += blk->size;
12899       DW_BLOCK (attr) = blk;
12900       break;
12901     case DW_FORM_data2:
12902       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
12903       info_ptr += 2;
12904       break;
12905     case DW_FORM_data4:
12906       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
12907       info_ptr += 4;
12908       break;
12909     case DW_FORM_data8:
12910       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
12911       info_ptr += 8;
12912       break;
12913     case DW_FORM_sec_offset:
12914       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
12915       info_ptr += bytes_read;
12916       break;
12917     case DW_FORM_string:
12918       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
12919       DW_STRING_IS_CANONICAL (attr) = 0;
12920       info_ptr += bytes_read;
12921       break;
12922     case DW_FORM_strp:
12923       DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
12924                                                &bytes_read);
12925       DW_STRING_IS_CANONICAL (attr) = 0;
12926       info_ptr += bytes_read;
12927       break;
12928     case DW_FORM_exprloc:
12929     case DW_FORM_block:
12930       blk = dwarf_alloc_block (cu);
12931       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12932       info_ptr += bytes_read;
12933       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12934       info_ptr += blk->size;
12935       DW_BLOCK (attr) = blk;
12936       break;
12937     case DW_FORM_block1:
12938       blk = dwarf_alloc_block (cu);
12939       blk->size = read_1_byte (abfd, info_ptr);
12940       info_ptr += 1;
12941       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12942       info_ptr += blk->size;
12943       DW_BLOCK (attr) = blk;
12944       break;
12945     case DW_FORM_data1:
12946       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
12947       info_ptr += 1;
12948       break;
12949     case DW_FORM_flag:
12950       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
12951       info_ptr += 1;
12952       break;
12953     case DW_FORM_flag_present:
12954       DW_UNSND (attr) = 1;
12955       break;
12956     case DW_FORM_sdata:
12957       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
12958       info_ptr += bytes_read;
12959       break;
12960     case DW_FORM_udata:
12961       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12962       info_ptr += bytes_read;
12963       break;
12964     case DW_FORM_ref1:
12965       DW_UNSND (attr) = (cu->header.offset.sect_off
12966                          + read_1_byte (abfd, info_ptr));
12967       info_ptr += 1;
12968       break;
12969     case DW_FORM_ref2:
12970       DW_UNSND (attr) = (cu->header.offset.sect_off
12971                          + read_2_bytes (abfd, info_ptr));
12972       info_ptr += 2;
12973       break;
12974     case DW_FORM_ref4:
12975       DW_UNSND (attr) = (cu->header.offset.sect_off
12976                          + read_4_bytes (abfd, info_ptr));
12977       info_ptr += 4;
12978       break;
12979     case DW_FORM_ref8:
12980       DW_UNSND (attr) = (cu->header.offset.sect_off
12981                          + read_8_bytes (abfd, info_ptr));
12982       info_ptr += 8;
12983       break;
12984     case DW_FORM_ref_sig8:
12985       /* Convert the signature to something we can record in DW_UNSND
12986          for later lookup.
12987          NOTE: This is NULL if the type wasn't found.  */
12988       DW_SIGNATURED_TYPE (attr) =
12989         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
12990       info_ptr += 8;
12991       break;
12992     case DW_FORM_ref_udata:
12993       DW_UNSND (attr) = (cu->header.offset.sect_off
12994                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
12995       info_ptr += bytes_read;
12996       break;
12997     case DW_FORM_indirect:
12998       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12999       info_ptr += bytes_read;
13000       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
13001       break;
13002     case DW_FORM_GNU_addr_index:
13003       if (reader->dwo_file == NULL)
13004         {
13005           /* For now flag a hard error.
13006              Later we can turn this into a complaint.  */
13007           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
13008                  dwarf_form_name (form),
13009                  bfd_get_filename (abfd));
13010         }
13011       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
13012       info_ptr += bytes_read;
13013       break;
13014     case DW_FORM_GNU_str_index:
13015       if (reader->dwo_file == NULL)
13016         {
13017           /* For now flag a hard error.
13018              Later we can turn this into a complaint if warranted.  */
13019           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
13020                  dwarf_form_name (form),
13021                  bfd_get_filename (abfd));
13022         }
13023       {
13024         ULONGEST str_index =
13025           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13026
13027         DW_STRING (attr) = read_str_index (reader, cu, str_index);
13028         DW_STRING_IS_CANONICAL (attr) = 0;
13029         info_ptr += bytes_read;
13030       }
13031       break;
13032     default:
13033       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
13034              dwarf_form_name (form),
13035              bfd_get_filename (abfd));
13036     }
13037
13038   /* We have seen instances where the compiler tried to emit a byte
13039      size attribute of -1 which ended up being encoded as an unsigned
13040      0xffffffff.  Although 0xffffffff is technically a valid size value,
13041      an object of this size seems pretty unlikely so we can relatively
13042      safely treat these cases as if the size attribute was invalid and
13043      treat them as zero by default.  */
13044   if (attr->name == DW_AT_byte_size
13045       && form == DW_FORM_data4
13046       && DW_UNSND (attr) >= 0xffffffff)
13047     {
13048       complaint
13049         (&symfile_complaints,
13050          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
13051          hex_string (DW_UNSND (attr)));
13052       DW_UNSND (attr) = 0;
13053     }
13054
13055   return info_ptr;
13056 }
13057
13058 /* Read an attribute described by an abbreviated attribute.  */
13059
13060 static gdb_byte *
13061 read_attribute (const struct die_reader_specs *reader,
13062                 struct attribute *attr, struct attr_abbrev *abbrev,
13063                 gdb_byte *info_ptr)
13064 {
13065   attr->name = abbrev->name;
13066   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
13067 }
13068
13069 /* Read dwarf information from a buffer.  */
13070
13071 static unsigned int
13072 read_1_byte (bfd *abfd, gdb_byte *buf)
13073 {
13074   return bfd_get_8 (abfd, buf);
13075 }
13076
13077 static int
13078 read_1_signed_byte (bfd *abfd, gdb_byte *buf)
13079 {
13080   return bfd_get_signed_8 (abfd, buf);
13081 }
13082
13083 static unsigned int
13084 read_2_bytes (bfd *abfd, gdb_byte *buf)
13085 {
13086   return bfd_get_16 (abfd, buf);
13087 }
13088
13089 static int
13090 read_2_signed_bytes (bfd *abfd, gdb_byte *buf)
13091 {
13092   return bfd_get_signed_16 (abfd, buf);
13093 }
13094
13095 static unsigned int
13096 read_4_bytes (bfd *abfd, gdb_byte *buf)
13097 {
13098   return bfd_get_32 (abfd, buf);
13099 }
13100
13101 static int
13102 read_4_signed_bytes (bfd *abfd, gdb_byte *buf)
13103 {
13104   return bfd_get_signed_32 (abfd, buf);
13105 }
13106
13107 static ULONGEST
13108 read_8_bytes (bfd *abfd, gdb_byte *buf)
13109 {
13110   return bfd_get_64 (abfd, buf);
13111 }
13112
13113 static CORE_ADDR
13114 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
13115               unsigned int *bytes_read)
13116 {
13117   struct comp_unit_head *cu_header = &cu->header;
13118   CORE_ADDR retval = 0;
13119
13120   if (cu_header->signed_addr_p)
13121     {
13122       switch (cu_header->addr_size)
13123         {
13124         case 2:
13125           retval = bfd_get_signed_16 (abfd, buf);
13126           break;
13127         case 4:
13128           retval = bfd_get_signed_32 (abfd, buf);
13129           break;
13130         case 8:
13131           retval = bfd_get_signed_64 (abfd, buf);
13132           break;
13133         default:
13134           internal_error (__FILE__, __LINE__,
13135                           _("read_address: bad switch, signed [in module %s]"),
13136                           bfd_get_filename (abfd));
13137         }
13138     }
13139   else
13140     {
13141       switch (cu_header->addr_size)
13142         {
13143         case 2:
13144           retval = bfd_get_16 (abfd, buf);
13145           break;
13146         case 4:
13147           retval = bfd_get_32 (abfd, buf);
13148           break;
13149         case 8:
13150           retval = bfd_get_64 (abfd, buf);
13151           break;
13152         default:
13153           internal_error (__FILE__, __LINE__,
13154                           _("read_address: bad switch, "
13155                             "unsigned [in module %s]"),
13156                           bfd_get_filename (abfd));
13157         }
13158     }
13159
13160   *bytes_read = cu_header->addr_size;
13161   return retval;
13162 }
13163
13164 /* Read the initial length from a section.  The (draft) DWARF 3
13165    specification allows the initial length to take up either 4 bytes
13166    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
13167    bytes describe the length and all offsets will be 8 bytes in length
13168    instead of 4.
13169
13170    An older, non-standard 64-bit format is also handled by this
13171    function.  The older format in question stores the initial length
13172    as an 8-byte quantity without an escape value.  Lengths greater
13173    than 2^32 aren't very common which means that the initial 4 bytes
13174    is almost always zero.  Since a length value of zero doesn't make
13175    sense for the 32-bit format, this initial zero can be considered to
13176    be an escape value which indicates the presence of the older 64-bit
13177    format.  As written, the code can't detect (old format) lengths
13178    greater than 4GB.  If it becomes necessary to handle lengths
13179    somewhat larger than 4GB, we could allow other small values (such
13180    as the non-sensical values of 1, 2, and 3) to also be used as
13181    escape values indicating the presence of the old format.
13182
13183    The value returned via bytes_read should be used to increment the
13184    relevant pointer after calling read_initial_length().
13185
13186    [ Note:  read_initial_length() and read_offset() are based on the
13187      document entitled "DWARF Debugging Information Format", revision
13188      3, draft 8, dated November 19, 2001.  This document was obtained
13189      from:
13190
13191         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
13192
13193      This document is only a draft and is subject to change.  (So beware.)
13194
13195      Details regarding the older, non-standard 64-bit format were
13196      determined empirically by examining 64-bit ELF files produced by
13197      the SGI toolchain on an IRIX 6.5 machine.
13198
13199      - Kevin, July 16, 2002
13200    ] */
13201
13202 static LONGEST
13203 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
13204 {
13205   LONGEST length = bfd_get_32 (abfd, buf);
13206
13207   if (length == 0xffffffff)
13208     {
13209       length = bfd_get_64 (abfd, buf + 4);
13210       *bytes_read = 12;
13211     }
13212   else if (length == 0)
13213     {
13214       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
13215       length = bfd_get_64 (abfd, buf);
13216       *bytes_read = 8;
13217     }
13218   else
13219     {
13220       *bytes_read = 4;
13221     }
13222
13223   return length;
13224 }
13225
13226 /* Cover function for read_initial_length.
13227    Returns the length of the object at BUF, and stores the size of the
13228    initial length in *BYTES_READ and stores the size that offsets will be in
13229    *OFFSET_SIZE.
13230    If the initial length size is not equivalent to that specified in
13231    CU_HEADER then issue a complaint.
13232    This is useful when reading non-comp-unit headers.  */
13233
13234 static LONGEST
13235 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
13236                                         const struct comp_unit_head *cu_header,
13237                                         unsigned int *bytes_read,
13238                                         unsigned int *offset_size)
13239 {
13240   LONGEST length = read_initial_length (abfd, buf, bytes_read);
13241
13242   gdb_assert (cu_header->initial_length_size == 4
13243               || cu_header->initial_length_size == 8
13244               || cu_header->initial_length_size == 12);
13245
13246   if (cu_header->initial_length_size != *bytes_read)
13247     complaint (&symfile_complaints,
13248                _("intermixed 32-bit and 64-bit DWARF sections"));
13249
13250   *offset_size = (*bytes_read == 4) ? 4 : 8;
13251   return length;
13252 }
13253
13254 /* Read an offset from the data stream.  The size of the offset is
13255    given by cu_header->offset_size.  */
13256
13257 static LONGEST
13258 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
13259              unsigned int *bytes_read)
13260 {
13261   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
13262
13263   *bytes_read = cu_header->offset_size;
13264   return offset;
13265 }
13266
13267 /* Read an offset from the data stream.  */
13268
13269 static LONGEST
13270 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
13271 {
13272   LONGEST retval = 0;
13273
13274   switch (offset_size)
13275     {
13276     case 4:
13277       retval = bfd_get_32 (abfd, buf);
13278       break;
13279     case 8:
13280       retval = bfd_get_64 (abfd, buf);
13281       break;
13282     default:
13283       internal_error (__FILE__, __LINE__,
13284                       _("read_offset_1: bad switch [in module %s]"),
13285                       bfd_get_filename (abfd));
13286     }
13287
13288   return retval;
13289 }
13290
13291 static gdb_byte *
13292 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
13293 {
13294   /* If the size of a host char is 8 bits, we can return a pointer
13295      to the buffer, otherwise we have to copy the data to a buffer
13296      allocated on the temporary obstack.  */
13297   gdb_assert (HOST_CHAR_BIT == 8);
13298   return buf;
13299 }
13300
13301 static char *
13302 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
13303 {
13304   /* If the size of a host char is 8 bits, we can return a pointer
13305      to the string, otherwise we have to copy the string to a buffer
13306      allocated on the temporary obstack.  */
13307   gdb_assert (HOST_CHAR_BIT == 8);
13308   if (*buf == '\0')
13309     {
13310       *bytes_read_ptr = 1;
13311       return NULL;
13312     }
13313   *bytes_read_ptr = strlen ((char *) buf) + 1;
13314   return (char *) buf;
13315 }
13316
13317 static char *
13318 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
13319 {
13320   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
13321   if (dwarf2_per_objfile->str.buffer == NULL)
13322     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
13323            bfd_get_filename (abfd));
13324   if (str_offset >= dwarf2_per_objfile->str.size)
13325     error (_("DW_FORM_strp pointing outside of "
13326              ".debug_str section [in module %s]"),
13327            bfd_get_filename (abfd));
13328   gdb_assert (HOST_CHAR_BIT == 8);
13329   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
13330     return NULL;
13331   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
13332 }
13333
13334 static char *
13335 read_indirect_string (bfd *abfd, gdb_byte *buf,
13336                       const struct comp_unit_head *cu_header,
13337                       unsigned int *bytes_read_ptr)
13338 {
13339   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
13340
13341   return read_indirect_string_at_offset (abfd, str_offset);
13342 }
13343
13344 static ULONGEST
13345 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
13346 {
13347   ULONGEST result;
13348   unsigned int num_read;
13349   int i, shift;
13350   unsigned char byte;
13351
13352   result = 0;
13353   shift = 0;
13354   num_read = 0;
13355   i = 0;
13356   while (1)
13357     {
13358       byte = bfd_get_8 (abfd, buf);
13359       buf++;
13360       num_read++;
13361       result |= ((ULONGEST) (byte & 127) << shift);
13362       if ((byte & 128) == 0)
13363         {
13364           break;
13365         }
13366       shift += 7;
13367     }
13368   *bytes_read_ptr = num_read;
13369   return result;
13370 }
13371
13372 static LONGEST
13373 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
13374 {
13375   LONGEST result;
13376   int i, shift, num_read;
13377   unsigned char byte;
13378
13379   result = 0;
13380   shift = 0;
13381   num_read = 0;
13382   i = 0;
13383   while (1)
13384     {
13385       byte = bfd_get_8 (abfd, buf);
13386       buf++;
13387       num_read++;
13388       result |= ((LONGEST) (byte & 127) << shift);
13389       shift += 7;
13390       if ((byte & 128) == 0)
13391         {
13392           break;
13393         }
13394     }
13395   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
13396     result |= -(((LONGEST) 1) << shift);
13397   *bytes_read_ptr = num_read;
13398   return result;
13399 }
13400
13401 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
13402    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
13403    ADDR_SIZE is the size of addresses from the CU header.  */
13404
13405 static CORE_ADDR
13406 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
13407 {
13408   struct objfile *objfile = dwarf2_per_objfile->objfile;
13409   bfd *abfd = objfile->obfd;
13410   const gdb_byte *info_ptr;
13411
13412   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
13413   if (dwarf2_per_objfile->addr.buffer == NULL)
13414     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
13415            objfile->name);
13416   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
13417     error (_("DW_FORM_addr_index pointing outside of "
13418              ".debug_addr section [in module %s]"),
13419            objfile->name);
13420   info_ptr = (dwarf2_per_objfile->addr.buffer
13421               + addr_base + addr_index * addr_size);
13422   if (addr_size == 4)
13423     return bfd_get_32 (abfd, info_ptr);
13424   else
13425     return bfd_get_64 (abfd, info_ptr);
13426 }
13427
13428 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
13429
13430 static CORE_ADDR
13431 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
13432 {
13433   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
13434 }
13435
13436 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
13437
13438 static CORE_ADDR
13439 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
13440                              unsigned int *bytes_read)
13441 {
13442   bfd *abfd = cu->objfile->obfd;
13443   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
13444
13445   return read_addr_index (cu, addr_index);
13446 }
13447
13448 /* Data structure to pass results from dwarf2_read_addr_index_reader
13449    back to dwarf2_read_addr_index.  */
13450
13451 struct dwarf2_read_addr_index_data
13452 {
13453   ULONGEST addr_base;
13454   int addr_size;
13455 };
13456
13457 /* die_reader_func for dwarf2_read_addr_index.  */
13458
13459 static void
13460 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
13461                                gdb_byte *info_ptr,
13462                                struct die_info *comp_unit_die,
13463                                int has_children,
13464                                void *data)
13465 {
13466   struct dwarf2_cu *cu = reader->cu;
13467   struct dwarf2_read_addr_index_data *aidata =
13468     (struct dwarf2_read_addr_index_data *) data;
13469
13470   aidata->addr_base = cu->addr_base;
13471   aidata->addr_size = cu->header.addr_size;
13472 }
13473
13474 /* Given an index in .debug_addr, fetch the value.
13475    NOTE: This can be called during dwarf expression evaluation,
13476    long after the debug information has been read, and thus per_cu->cu
13477    may no longer exist.  */
13478
13479 CORE_ADDR
13480 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
13481                         unsigned int addr_index)
13482 {
13483   struct objfile *objfile = per_cu->objfile;
13484   struct dwarf2_cu *cu = per_cu->cu;
13485   ULONGEST addr_base;
13486   int addr_size;
13487
13488   /* This is intended to be called from outside this file.  */
13489   dw2_setup (objfile);
13490
13491   /* We need addr_base and addr_size.
13492      If we don't have PER_CU->cu, we have to get it.
13493      Nasty, but the alternative is storing the needed info in PER_CU,
13494      which at this point doesn't seem justified: it's not clear how frequently
13495      it would get used and it would increase the size of every PER_CU.
13496      Entry points like dwarf2_per_cu_addr_size do a similar thing
13497      so we're not in uncharted territory here.
13498      Alas we need to be a bit more complicated as addr_base is contained
13499      in the DIE.
13500
13501      We don't need to read the entire CU(/TU).
13502      We just need the header and top level die.
13503      IWBN to use the aging mechanism to let us lazily later discard the CU.
13504      See however init_cutu_and_read_dies_simple.  */
13505
13506   if (cu != NULL)
13507     {
13508       addr_base = cu->addr_base;
13509       addr_size = cu->header.addr_size;
13510     }
13511   else
13512     {
13513       struct dwarf2_read_addr_index_data aidata;
13514
13515       init_cutu_and_read_dies_simple (per_cu, dwarf2_read_addr_index_reader,
13516                                       &aidata);
13517       addr_base = aidata.addr_base;
13518       addr_size = aidata.addr_size;
13519     }
13520
13521   return read_addr_index_1 (addr_index, addr_base, addr_size);
13522 }
13523
13524 /* Given a DW_AT_str_index, fetch the string.  */
13525
13526 static char *
13527 read_str_index (const struct die_reader_specs *reader,
13528                 struct dwarf2_cu *cu, ULONGEST str_index)
13529 {
13530   struct objfile *objfile = dwarf2_per_objfile->objfile;
13531   const char *dwo_name = objfile->name;
13532   bfd *abfd = objfile->obfd;
13533   struct dwo_sections *sections = &reader->dwo_file->sections;
13534   gdb_byte *info_ptr;
13535   ULONGEST str_offset;
13536
13537   dwarf2_read_section (objfile, &sections->str);
13538   dwarf2_read_section (objfile, &sections->str_offsets);
13539   if (sections->str.buffer == NULL)
13540     error (_("DW_FORM_str_index used without .debug_str.dwo section"
13541              " in CU at offset 0x%lx [in module %s]"),
13542            (long) cu->header.offset.sect_off, dwo_name);
13543   if (sections->str_offsets.buffer == NULL)
13544     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
13545              " in CU at offset 0x%lx [in module %s]"),
13546            (long) cu->header.offset.sect_off, dwo_name);
13547   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
13548     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
13549              " section in CU at offset 0x%lx [in module %s]"),
13550            (long) cu->header.offset.sect_off, dwo_name);
13551   info_ptr = (sections->str_offsets.buffer
13552               + str_index * cu->header.offset_size);
13553   if (cu->header.offset_size == 4)
13554     str_offset = bfd_get_32 (abfd, info_ptr);
13555   else
13556     str_offset = bfd_get_64 (abfd, info_ptr);
13557   if (str_offset >= sections->str.size)
13558     error (_("Offset from DW_FORM_str_index pointing outside of"
13559              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
13560            (long) cu->header.offset.sect_off, dwo_name);
13561   return (char *) (sections->str.buffer + str_offset);
13562 }
13563
13564 /* Return the length of an LEB128 number in BUF.  */
13565
13566 static int
13567 leb128_size (const gdb_byte *buf)
13568 {
13569   const gdb_byte *begin = buf;
13570   gdb_byte byte;
13571
13572   while (1)
13573     {
13574       byte = *buf++;
13575       if ((byte & 128) == 0)
13576         return buf - begin;
13577     }
13578 }
13579
13580 static void
13581 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
13582 {
13583   switch (lang)
13584     {
13585     case DW_LANG_C89:
13586     case DW_LANG_C99:
13587     case DW_LANG_C:
13588       cu->language = language_c;
13589       break;
13590     case DW_LANG_C_plus_plus:
13591       cu->language = language_cplus;
13592       break;
13593     case DW_LANG_D:
13594       cu->language = language_d;
13595       break;
13596     case DW_LANG_Fortran77:
13597     case DW_LANG_Fortran90:
13598     case DW_LANG_Fortran95:
13599       cu->language = language_fortran;
13600       break;
13601     case DW_LANG_Go:
13602       cu->language = language_go;
13603       break;
13604     case DW_LANG_Mips_Assembler:
13605       cu->language = language_asm;
13606       break;
13607     case DW_LANG_Java:
13608       cu->language = language_java;
13609       break;
13610     case DW_LANG_Ada83:
13611     case DW_LANG_Ada95:
13612       cu->language = language_ada;
13613       break;
13614     case DW_LANG_Modula2:
13615       cu->language = language_m2;
13616       break;
13617     case DW_LANG_Pascal83:
13618       cu->language = language_pascal;
13619       break;
13620     case DW_LANG_ObjC:
13621       cu->language = language_objc;
13622       break;
13623     case DW_LANG_Cobol74:
13624     case DW_LANG_Cobol85:
13625     default:
13626       cu->language = language_minimal;
13627       break;
13628     }
13629   cu->language_defn = language_def (cu->language);
13630 }
13631
13632 /* Return the named attribute or NULL if not there.  */
13633
13634 static struct attribute *
13635 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
13636 {
13637   for (;;)
13638     {
13639       unsigned int i;
13640       struct attribute *spec = NULL;
13641
13642       for (i = 0; i < die->num_attrs; ++i)
13643         {
13644           if (die->attrs[i].name == name)
13645             return &die->attrs[i];
13646           if (die->attrs[i].name == DW_AT_specification
13647               || die->attrs[i].name == DW_AT_abstract_origin)
13648             spec = &die->attrs[i];
13649         }
13650
13651       if (!spec)
13652         break;
13653
13654       die = follow_die_ref (die, spec, &cu);
13655     }
13656
13657   return NULL;
13658 }
13659
13660 /* Return the named attribute or NULL if not there,
13661    but do not follow DW_AT_specification, etc.
13662    This is for use in contexts where we're reading .debug_types dies.
13663    Following DW_AT_specification, DW_AT_abstract_origin will take us
13664    back up the chain, and we want to go down.  */
13665
13666 static struct attribute *
13667 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
13668 {
13669   unsigned int i;
13670
13671   for (i = 0; i < die->num_attrs; ++i)
13672     if (die->attrs[i].name == name)
13673       return &die->attrs[i];
13674
13675   return NULL;
13676 }
13677
13678 /* Return non-zero iff the attribute NAME is defined for the given DIE,
13679    and holds a non-zero value.  This function should only be used for
13680    DW_FORM_flag or DW_FORM_flag_present attributes.  */
13681
13682 static int
13683 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
13684 {
13685   struct attribute *attr = dwarf2_attr (die, name, cu);
13686
13687   return (attr && DW_UNSND (attr));
13688 }
13689
13690 static int
13691 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
13692 {
13693   /* A DIE is a declaration if it has a DW_AT_declaration attribute
13694      which value is non-zero.  However, we have to be careful with
13695      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
13696      (via dwarf2_flag_true_p) follows this attribute.  So we may
13697      end up accidently finding a declaration attribute that belongs
13698      to a different DIE referenced by the specification attribute,
13699      even though the given DIE does not have a declaration attribute.  */
13700   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
13701           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
13702 }
13703
13704 /* Return the die giving the specification for DIE, if there is
13705    one.  *SPEC_CU is the CU containing DIE on input, and the CU
13706    containing the return value on output.  If there is no
13707    specification, but there is an abstract origin, that is
13708    returned.  */
13709
13710 static struct die_info *
13711 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
13712 {
13713   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
13714                                              *spec_cu);
13715
13716   if (spec_attr == NULL)
13717     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
13718
13719   if (spec_attr == NULL)
13720     return NULL;
13721   else
13722     return follow_die_ref (die, spec_attr, spec_cu);
13723 }
13724
13725 /* Free the line_header structure *LH, and any arrays and strings it
13726    refers to.
13727    NOTE: This is also used as a "cleanup" function.  */
13728
13729 static void
13730 free_line_header (struct line_header *lh)
13731 {
13732   if (lh->standard_opcode_lengths)
13733     xfree (lh->standard_opcode_lengths);
13734
13735   /* Remember that all the lh->file_names[i].name pointers are
13736      pointers into debug_line_buffer, and don't need to be freed.  */
13737   if (lh->file_names)
13738     xfree (lh->file_names);
13739
13740   /* Similarly for the include directory names.  */
13741   if (lh->include_dirs)
13742     xfree (lh->include_dirs);
13743
13744   xfree (lh);
13745 }
13746
13747 /* Add an entry to LH's include directory table.  */
13748
13749 static void
13750 add_include_dir (struct line_header *lh, char *include_dir)
13751 {
13752   /* Grow the array if necessary.  */
13753   if (lh->include_dirs_size == 0)
13754     {
13755       lh->include_dirs_size = 1; /* for testing */
13756       lh->include_dirs = xmalloc (lh->include_dirs_size
13757                                   * sizeof (*lh->include_dirs));
13758     }
13759   else if (lh->num_include_dirs >= lh->include_dirs_size)
13760     {
13761       lh->include_dirs_size *= 2;
13762       lh->include_dirs = xrealloc (lh->include_dirs,
13763                                    (lh->include_dirs_size
13764                                     * sizeof (*lh->include_dirs)));
13765     }
13766
13767   lh->include_dirs[lh->num_include_dirs++] = include_dir;
13768 }
13769
13770 /* Add an entry to LH's file name table.  */
13771
13772 static void
13773 add_file_name (struct line_header *lh,
13774                char *name,
13775                unsigned int dir_index,
13776                unsigned int mod_time,
13777                unsigned int length)
13778 {
13779   struct file_entry *fe;
13780
13781   /* Grow the array if necessary.  */
13782   if (lh->file_names_size == 0)
13783     {
13784       lh->file_names_size = 1; /* for testing */
13785       lh->file_names = xmalloc (lh->file_names_size
13786                                 * sizeof (*lh->file_names));
13787     }
13788   else if (lh->num_file_names >= lh->file_names_size)
13789     {
13790       lh->file_names_size *= 2;
13791       lh->file_names = xrealloc (lh->file_names,
13792                                  (lh->file_names_size
13793                                   * sizeof (*lh->file_names)));
13794     }
13795
13796   fe = &lh->file_names[lh->num_file_names++];
13797   fe->name = name;
13798   fe->dir_index = dir_index;
13799   fe->mod_time = mod_time;
13800   fe->length = length;
13801   fe->included_p = 0;
13802   fe->symtab = NULL;
13803 }
13804
13805 /* Read the statement program header starting at OFFSET in
13806    .debug_line, or .debug_line.dwo.  Return a pointer
13807    to a struct line_header, allocated using xmalloc.
13808
13809    NOTE: the strings in the include directory and file name tables of
13810    the returned object point into the dwarf line section buffer,
13811    and must not be freed.  */
13812
13813 static struct line_header *
13814 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
13815 {
13816   struct cleanup *back_to;
13817   struct line_header *lh;
13818   gdb_byte *line_ptr;
13819   unsigned int bytes_read, offset_size;
13820   int i;
13821   char *cur_dir, *cur_file;
13822   struct dwarf2_section_info *section;
13823   bfd *abfd;
13824
13825   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
13826      DWO file.  */
13827   if (cu->dwo_unit && cu->per_cu->is_debug_types)
13828     section = &cu->dwo_unit->dwo_file->sections.line;
13829   else
13830     section = &dwarf2_per_objfile->line;
13831
13832   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
13833   if (section->buffer == NULL)
13834     {
13835       if (cu->dwo_unit && cu->per_cu->is_debug_types)
13836         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
13837       else
13838         complaint (&symfile_complaints, _("missing .debug_line section"));
13839       return 0;
13840     }
13841
13842   /* We can't do this until we know the section is non-empty.
13843      Only then do we know we have such a section.  */
13844   abfd = section->asection->owner;
13845
13846   /* Make sure that at least there's room for the total_length field.
13847      That could be 12 bytes long, but we're just going to fudge that.  */
13848   if (offset + 4 >= section->size)
13849     {
13850       dwarf2_statement_list_fits_in_line_number_section_complaint ();
13851       return 0;
13852     }
13853
13854   lh = xmalloc (sizeof (*lh));
13855   memset (lh, 0, sizeof (*lh));
13856   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
13857                           (void *) lh);
13858
13859   line_ptr = section->buffer + offset;
13860
13861   /* Read in the header.  */
13862   lh->total_length =
13863     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
13864                                             &bytes_read, &offset_size);
13865   line_ptr += bytes_read;
13866   if (line_ptr + lh->total_length > (section->buffer + section->size))
13867     {
13868       dwarf2_statement_list_fits_in_line_number_section_complaint ();
13869       return 0;
13870     }
13871   lh->statement_program_end = line_ptr + lh->total_length;
13872   lh->version = read_2_bytes (abfd, line_ptr);
13873   line_ptr += 2;
13874   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
13875   line_ptr += offset_size;
13876   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
13877   line_ptr += 1;
13878   if (lh->version >= 4)
13879     {
13880       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
13881       line_ptr += 1;
13882     }
13883   else
13884     lh->maximum_ops_per_instruction = 1;
13885
13886   if (lh->maximum_ops_per_instruction == 0)
13887     {
13888       lh->maximum_ops_per_instruction = 1;
13889       complaint (&symfile_complaints,
13890                  _("invalid maximum_ops_per_instruction "
13891                    "in `.debug_line' section"));
13892     }
13893
13894   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
13895   line_ptr += 1;
13896   lh->line_base = read_1_signed_byte (abfd, line_ptr);
13897   line_ptr += 1;
13898   lh->line_range = read_1_byte (abfd, line_ptr);
13899   line_ptr += 1;
13900   lh->opcode_base = read_1_byte (abfd, line_ptr);
13901   line_ptr += 1;
13902   lh->standard_opcode_lengths
13903     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
13904
13905   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
13906   for (i = 1; i < lh->opcode_base; ++i)
13907     {
13908       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
13909       line_ptr += 1;
13910     }
13911
13912   /* Read directory table.  */
13913   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
13914     {
13915       line_ptr += bytes_read;
13916       add_include_dir (lh, cur_dir);
13917     }
13918   line_ptr += bytes_read;
13919
13920   /* Read file name table.  */
13921   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
13922     {
13923       unsigned int dir_index, mod_time, length;
13924
13925       line_ptr += bytes_read;
13926       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13927       line_ptr += bytes_read;
13928       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13929       line_ptr += bytes_read;
13930       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13931       line_ptr += bytes_read;
13932
13933       add_file_name (lh, cur_file, dir_index, mod_time, length);
13934     }
13935   line_ptr += bytes_read;
13936   lh->statement_program_start = line_ptr;
13937
13938   if (line_ptr > (section->buffer + section->size))
13939     complaint (&symfile_complaints,
13940                _("line number info header doesn't "
13941                  "fit in `.debug_line' section"));
13942
13943   discard_cleanups (back_to);
13944   return lh;
13945 }
13946
13947 /* Subroutine of dwarf_decode_lines to simplify it.
13948    Return the file name of the psymtab for included file FILE_INDEX
13949    in line header LH of PST.
13950    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
13951    If space for the result is malloc'd, it will be freed by a cleanup.
13952    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
13953
13954 static char *
13955 psymtab_include_file_name (const struct line_header *lh, int file_index,
13956                            const struct partial_symtab *pst,
13957                            const char *comp_dir)
13958 {
13959   const struct file_entry fe = lh->file_names [file_index];
13960   char *include_name = fe.name;
13961   char *include_name_to_compare = include_name;
13962   char *dir_name = NULL;
13963   const char *pst_filename;
13964   char *copied_name = NULL;
13965   int file_is_pst;
13966
13967   if (fe.dir_index)
13968     dir_name = lh->include_dirs[fe.dir_index - 1];
13969
13970   if (!IS_ABSOLUTE_PATH (include_name)
13971       && (dir_name != NULL || comp_dir != NULL))
13972     {
13973       /* Avoid creating a duplicate psymtab for PST.
13974          We do this by comparing INCLUDE_NAME and PST_FILENAME.
13975          Before we do the comparison, however, we need to account
13976          for DIR_NAME and COMP_DIR.
13977          First prepend dir_name (if non-NULL).  If we still don't
13978          have an absolute path prepend comp_dir (if non-NULL).
13979          However, the directory we record in the include-file's
13980          psymtab does not contain COMP_DIR (to match the
13981          corresponding symtab(s)).
13982
13983          Example:
13984
13985          bash$ cd /tmp
13986          bash$ gcc -g ./hello.c
13987          include_name = "hello.c"
13988          dir_name = "."
13989          DW_AT_comp_dir = comp_dir = "/tmp"
13990          DW_AT_name = "./hello.c"  */
13991
13992       if (dir_name != NULL)
13993         {
13994           include_name = concat (dir_name, SLASH_STRING,
13995                                  include_name, (char *)NULL);
13996           include_name_to_compare = include_name;
13997           make_cleanup (xfree, include_name);
13998         }
13999       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
14000         {
14001           include_name_to_compare = concat (comp_dir, SLASH_STRING,
14002                                             include_name, (char *)NULL);
14003         }
14004     }
14005
14006   pst_filename = pst->filename;
14007   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
14008     {
14009       copied_name = concat (pst->dirname, SLASH_STRING,
14010                             pst_filename, (char *)NULL);
14011       pst_filename = copied_name;
14012     }
14013
14014   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
14015
14016   if (include_name_to_compare != include_name)
14017     xfree (include_name_to_compare);
14018   if (copied_name != NULL)
14019     xfree (copied_name);
14020
14021   if (file_is_pst)
14022     return NULL;
14023   return include_name;
14024 }
14025
14026 /* Ignore this record_line request.  */
14027
14028 static void
14029 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
14030 {
14031   return;
14032 }
14033
14034 /* Subroutine of dwarf_decode_lines to simplify it.
14035    Process the line number information in LH.  */
14036
14037 static void
14038 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
14039                       struct dwarf2_cu *cu, struct partial_symtab *pst)
14040 {
14041   gdb_byte *line_ptr, *extended_end;
14042   gdb_byte *line_end;
14043   unsigned int bytes_read, extended_len;
14044   unsigned char op_code, extended_op, adj_opcode;
14045   CORE_ADDR baseaddr;
14046   struct objfile *objfile = cu->objfile;
14047   bfd *abfd = objfile->obfd;
14048   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14049   const int decode_for_pst_p = (pst != NULL);
14050   struct subfile *last_subfile = NULL;
14051   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
14052     = record_line;
14053
14054   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14055
14056   line_ptr = lh->statement_program_start;
14057   line_end = lh->statement_program_end;
14058
14059   /* Read the statement sequences until there's nothing left.  */
14060   while (line_ptr < line_end)
14061     {
14062       /* state machine registers  */
14063       CORE_ADDR address = 0;
14064       unsigned int file = 1;
14065       unsigned int line = 1;
14066       unsigned int column = 0;
14067       int is_stmt = lh->default_is_stmt;
14068       int basic_block = 0;
14069       int end_sequence = 0;
14070       CORE_ADDR addr;
14071       unsigned char op_index = 0;
14072
14073       if (!decode_for_pst_p && lh->num_file_names >= file)
14074         {
14075           /* Start a subfile for the current file of the state machine.  */
14076           /* lh->include_dirs and lh->file_names are 0-based, but the
14077              directory and file name numbers in the statement program
14078              are 1-based.  */
14079           struct file_entry *fe = &lh->file_names[file - 1];
14080           char *dir = NULL;
14081
14082           if (fe->dir_index)
14083             dir = lh->include_dirs[fe->dir_index - 1];
14084
14085           dwarf2_start_subfile (fe->name, dir, comp_dir);
14086         }
14087
14088       /* Decode the table.  */
14089       while (!end_sequence)
14090         {
14091           op_code = read_1_byte (abfd, line_ptr);
14092           line_ptr += 1;
14093           if (line_ptr > line_end)
14094             {
14095               dwarf2_debug_line_missing_end_sequence_complaint ();
14096               break;
14097             }
14098
14099           if (op_code >= lh->opcode_base)
14100             {
14101               /* Special operand.  */
14102               adj_opcode = op_code - lh->opcode_base;
14103               address += (((op_index + (adj_opcode / lh->line_range))
14104                            / lh->maximum_ops_per_instruction)
14105                           * lh->minimum_instruction_length);
14106               op_index = ((op_index + (adj_opcode / lh->line_range))
14107                           % lh->maximum_ops_per_instruction);
14108               line += lh->line_base + (adj_opcode % lh->line_range);
14109               if (lh->num_file_names < file || file == 0)
14110                 dwarf2_debug_line_missing_file_complaint ();
14111               /* For now we ignore lines not starting on an
14112                  instruction boundary.  */
14113               else if (op_index == 0)
14114                 {
14115                   lh->file_names[file - 1].included_p = 1;
14116                   if (!decode_for_pst_p && is_stmt)
14117                     {
14118                       if (last_subfile != current_subfile)
14119                         {
14120                           addr = gdbarch_addr_bits_remove (gdbarch, address);
14121                           if (last_subfile)
14122                             (*p_record_line) (last_subfile, 0, addr);
14123                           last_subfile = current_subfile;
14124                         }
14125                       /* Append row to matrix using current values.  */
14126                       addr = gdbarch_addr_bits_remove (gdbarch, address);
14127                       (*p_record_line) (current_subfile, line, addr);
14128                     }
14129                 }
14130               basic_block = 0;
14131             }
14132           else switch (op_code)
14133             {
14134             case DW_LNS_extended_op:
14135               extended_len = read_unsigned_leb128 (abfd, line_ptr,
14136                                                    &bytes_read);
14137               line_ptr += bytes_read;
14138               extended_end = line_ptr + extended_len;
14139               extended_op = read_1_byte (abfd, line_ptr);
14140               line_ptr += 1;
14141               switch (extended_op)
14142                 {
14143                 case DW_LNE_end_sequence:
14144                   p_record_line = record_line;
14145                   end_sequence = 1;
14146                   break;
14147                 case DW_LNE_set_address:
14148                   address = read_address (abfd, line_ptr, cu, &bytes_read);
14149
14150                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
14151                     {
14152                       /* This line table is for a function which has been
14153                          GCd by the linker.  Ignore it.  PR gdb/12528 */
14154
14155                       long line_offset
14156                         = line_ptr - dwarf2_per_objfile->line.buffer;
14157
14158                       complaint (&symfile_complaints,
14159                                  _(".debug_line address at offset 0x%lx is 0 "
14160                                    "[in module %s]"),
14161                                  line_offset, objfile->name);
14162                       p_record_line = noop_record_line;
14163                     }
14164
14165                   op_index = 0;
14166                   line_ptr += bytes_read;
14167                   address += baseaddr;
14168                   break;
14169                 case DW_LNE_define_file:
14170                   {
14171                     char *cur_file;
14172                     unsigned int dir_index, mod_time, length;
14173
14174                     cur_file = read_direct_string (abfd, line_ptr,
14175                                                    &bytes_read);
14176                     line_ptr += bytes_read;
14177                     dir_index =
14178                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14179                     line_ptr += bytes_read;
14180                     mod_time =
14181                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14182                     line_ptr += bytes_read;
14183                     length =
14184                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14185                     line_ptr += bytes_read;
14186                     add_file_name (lh, cur_file, dir_index, mod_time, length);
14187                   }
14188                   break;
14189                 case DW_LNE_set_discriminator:
14190                   /* The discriminator is not interesting to the debugger;
14191                      just ignore it.  */
14192                   line_ptr = extended_end;
14193                   break;
14194                 default:
14195                   complaint (&symfile_complaints,
14196                              _("mangled .debug_line section"));
14197                   return;
14198                 }
14199               /* Make sure that we parsed the extended op correctly.  If e.g.
14200                  we expected a different address size than the producer used,
14201                  we may have read the wrong number of bytes.  */
14202               if (line_ptr != extended_end)
14203                 {
14204                   complaint (&symfile_complaints,
14205                              _("mangled .debug_line section"));
14206                   return;
14207                 }
14208               break;
14209             case DW_LNS_copy:
14210               if (lh->num_file_names < file || file == 0)
14211                 dwarf2_debug_line_missing_file_complaint ();
14212               else
14213                 {
14214                   lh->file_names[file - 1].included_p = 1;
14215                   if (!decode_for_pst_p && is_stmt)
14216                     {
14217                       if (last_subfile != current_subfile)
14218                         {
14219                           addr = gdbarch_addr_bits_remove (gdbarch, address);
14220                           if (last_subfile)
14221                             (*p_record_line) (last_subfile, 0, addr);
14222                           last_subfile = current_subfile;
14223                         }
14224                       addr = gdbarch_addr_bits_remove (gdbarch, address);
14225                       (*p_record_line) (current_subfile, line, addr);
14226                     }
14227                 }
14228               basic_block = 0;
14229               break;
14230             case DW_LNS_advance_pc:
14231               {
14232                 CORE_ADDR adjust
14233                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14234
14235                 address += (((op_index + adjust)
14236                              / lh->maximum_ops_per_instruction)
14237                             * lh->minimum_instruction_length);
14238                 op_index = ((op_index + adjust)
14239                             % lh->maximum_ops_per_instruction);
14240                 line_ptr += bytes_read;
14241               }
14242               break;
14243             case DW_LNS_advance_line:
14244               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
14245               line_ptr += bytes_read;
14246               break;
14247             case DW_LNS_set_file:
14248               {
14249                 /* The arrays lh->include_dirs and lh->file_names are
14250                    0-based, but the directory and file name numbers in
14251                    the statement program are 1-based.  */
14252                 struct file_entry *fe;
14253                 char *dir = NULL;
14254
14255                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14256                 line_ptr += bytes_read;
14257                 if (lh->num_file_names < file || file == 0)
14258                   dwarf2_debug_line_missing_file_complaint ();
14259                 else
14260                   {
14261                     fe = &lh->file_names[file - 1];
14262                     if (fe->dir_index)
14263                       dir = lh->include_dirs[fe->dir_index - 1];
14264                     if (!decode_for_pst_p)
14265                       {
14266                         last_subfile = current_subfile;
14267                         dwarf2_start_subfile (fe->name, dir, comp_dir);
14268                       }
14269                   }
14270               }
14271               break;
14272             case DW_LNS_set_column:
14273               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14274               line_ptr += bytes_read;
14275               break;
14276             case DW_LNS_negate_stmt:
14277               is_stmt = (!is_stmt);
14278               break;
14279             case DW_LNS_set_basic_block:
14280               basic_block = 1;
14281               break;
14282             /* Add to the address register of the state machine the
14283                address increment value corresponding to special opcode
14284                255.  I.e., this value is scaled by the minimum
14285                instruction length since special opcode 255 would have
14286                scaled the increment.  */
14287             case DW_LNS_const_add_pc:
14288               {
14289                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
14290
14291                 address += (((op_index + adjust)
14292                              / lh->maximum_ops_per_instruction)
14293                             * lh->minimum_instruction_length);
14294                 op_index = ((op_index + adjust)
14295                             % lh->maximum_ops_per_instruction);
14296               }
14297               break;
14298             case DW_LNS_fixed_advance_pc:
14299               address += read_2_bytes (abfd, line_ptr);
14300               op_index = 0;
14301               line_ptr += 2;
14302               break;
14303             default:
14304               {
14305                 /* Unknown standard opcode, ignore it.  */
14306                 int i;
14307
14308                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
14309                   {
14310                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14311                     line_ptr += bytes_read;
14312                   }
14313               }
14314             }
14315         }
14316       if (lh->num_file_names < file || file == 0)
14317         dwarf2_debug_line_missing_file_complaint ();
14318       else
14319         {
14320           lh->file_names[file - 1].included_p = 1;
14321           if (!decode_for_pst_p)
14322             {
14323               addr = gdbarch_addr_bits_remove (gdbarch, address);
14324               (*p_record_line) (current_subfile, 0, addr);
14325             }
14326         }
14327     }
14328 }
14329
14330 /* Decode the Line Number Program (LNP) for the given line_header
14331    structure and CU.  The actual information extracted and the type
14332    of structures created from the LNP depends on the value of PST.
14333
14334    1. If PST is NULL, then this procedure uses the data from the program
14335       to create all necessary symbol tables, and their linetables.
14336
14337    2. If PST is not NULL, this procedure reads the program to determine
14338       the list of files included by the unit represented by PST, and
14339       builds all the associated partial symbol tables.
14340
14341    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
14342    It is used for relative paths in the line table.
14343    NOTE: When processing partial symtabs (pst != NULL),
14344    comp_dir == pst->dirname.
14345
14346    NOTE: It is important that psymtabs have the same file name (via strcmp)
14347    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
14348    symtab we don't use it in the name of the psymtabs we create.
14349    E.g. expand_line_sal requires this when finding psymtabs to expand.
14350    A good testcase for this is mb-inline.exp.  */
14351
14352 static void
14353 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
14354                     struct dwarf2_cu *cu, struct partial_symtab *pst,
14355                     int want_line_info)
14356 {
14357   struct objfile *objfile = cu->objfile;
14358   const int decode_for_pst_p = (pst != NULL);
14359   struct subfile *first_subfile = current_subfile;
14360
14361   if (want_line_info)
14362     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
14363
14364   if (decode_for_pst_p)
14365     {
14366       int file_index;
14367
14368       /* Now that we're done scanning the Line Header Program, we can
14369          create the psymtab of each included file.  */
14370       for (file_index = 0; file_index < lh->num_file_names; file_index++)
14371         if (lh->file_names[file_index].included_p == 1)
14372           {
14373             char *include_name =
14374               psymtab_include_file_name (lh, file_index, pst, comp_dir);
14375             if (include_name != NULL)
14376               dwarf2_create_include_psymtab (include_name, pst, objfile);
14377           }
14378     }
14379   else
14380     {
14381       /* Make sure a symtab is created for every file, even files
14382          which contain only variables (i.e. no code with associated
14383          line numbers).  */
14384       int i;
14385
14386       for (i = 0; i < lh->num_file_names; i++)
14387         {
14388           char *dir = NULL;
14389           struct file_entry *fe;
14390
14391           fe = &lh->file_names[i];
14392           if (fe->dir_index)
14393             dir = lh->include_dirs[fe->dir_index - 1];
14394           dwarf2_start_subfile (fe->name, dir, comp_dir);
14395
14396           /* Skip the main file; we don't need it, and it must be
14397              allocated last, so that it will show up before the
14398              non-primary symtabs in the objfile's symtab list.  */
14399           if (current_subfile == first_subfile)
14400             continue;
14401
14402           if (current_subfile->symtab == NULL)
14403             current_subfile->symtab = allocate_symtab (current_subfile->name,
14404                                                        objfile);
14405           fe->symtab = current_subfile->symtab;
14406         }
14407     }
14408 }
14409
14410 /* Start a subfile for DWARF.  FILENAME is the name of the file and
14411    DIRNAME the name of the source directory which contains FILENAME
14412    or NULL if not known.  COMP_DIR is the compilation directory for the
14413    linetable's compilation unit or NULL if not known.
14414    This routine tries to keep line numbers from identical absolute and
14415    relative file names in a common subfile.
14416
14417    Using the `list' example from the GDB testsuite, which resides in
14418    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
14419    of /srcdir/list0.c yields the following debugging information for list0.c:
14420
14421    DW_AT_name:          /srcdir/list0.c
14422    DW_AT_comp_dir:              /compdir
14423    files.files[0].name: list0.h
14424    files.files[0].dir:  /srcdir
14425    files.files[1].name: list0.c
14426    files.files[1].dir:  /srcdir
14427
14428    The line number information for list0.c has to end up in a single
14429    subfile, so that `break /srcdir/list0.c:1' works as expected.
14430    start_subfile will ensure that this happens provided that we pass the
14431    concatenation of files.files[1].dir and files.files[1].name as the
14432    subfile's name.  */
14433
14434 static void
14435 dwarf2_start_subfile (char *filename, const char *dirname,
14436                       const char *comp_dir)
14437 {
14438   char *fullname;
14439
14440   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
14441      `start_symtab' will always pass the contents of DW_AT_comp_dir as
14442      second argument to start_subfile.  To be consistent, we do the
14443      same here.  In order not to lose the line information directory,
14444      we concatenate it to the filename when it makes sense.
14445      Note that the Dwarf3 standard says (speaking of filenames in line
14446      information): ``The directory index is ignored for file names
14447      that represent full path names''.  Thus ignoring dirname in the
14448      `else' branch below isn't an issue.  */
14449
14450   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
14451     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
14452   else
14453     fullname = filename;
14454
14455   start_subfile (fullname, comp_dir);
14456
14457   if (fullname != filename)
14458     xfree (fullname);
14459 }
14460
14461 /* Start a symtab for DWARF.
14462    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
14463
14464 static void
14465 dwarf2_start_symtab (struct dwarf2_cu *cu,
14466                      char *name, char *comp_dir, CORE_ADDR low_pc)
14467 {
14468   start_symtab (name, comp_dir, low_pc);
14469   record_debugformat ("DWARF 2");
14470   record_producer (cu->producer);
14471
14472   /* We assume that we're processing GCC output.  */
14473   processing_gcc_compilation = 2;
14474
14475   processing_has_namespace_info = 0;
14476 }
14477
14478 static void
14479 var_decode_location (struct attribute *attr, struct symbol *sym,
14480                      struct dwarf2_cu *cu)
14481 {
14482   struct objfile *objfile = cu->objfile;
14483   struct comp_unit_head *cu_header = &cu->header;
14484
14485   /* NOTE drow/2003-01-30: There used to be a comment and some special
14486      code here to turn a symbol with DW_AT_external and a
14487      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
14488      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
14489      with some versions of binutils) where shared libraries could have
14490      relocations against symbols in their debug information - the
14491      minimal symbol would have the right address, but the debug info
14492      would not.  It's no longer necessary, because we will explicitly
14493      apply relocations when we read in the debug information now.  */
14494
14495   /* A DW_AT_location attribute with no contents indicates that a
14496      variable has been optimized away.  */
14497   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
14498     {
14499       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
14500       return;
14501     }
14502
14503   /* Handle one degenerate form of location expression specially, to
14504      preserve GDB's previous behavior when section offsets are
14505      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
14506      then mark this symbol as LOC_STATIC.  */
14507
14508   if (attr_form_is_block (attr)
14509       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
14510            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
14511           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
14512               && (DW_BLOCK (attr)->size
14513                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
14514     {
14515       unsigned int dummy;
14516
14517       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
14518         SYMBOL_VALUE_ADDRESS (sym) =
14519           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
14520       else
14521         SYMBOL_VALUE_ADDRESS (sym) =
14522           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
14523       SYMBOL_CLASS (sym) = LOC_STATIC;
14524       fixup_symbol_section (sym, objfile);
14525       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
14526                                               SYMBOL_SECTION (sym));
14527       return;
14528     }
14529
14530   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
14531      expression evaluator, and use LOC_COMPUTED only when necessary
14532      (i.e. when the value of a register or memory location is
14533      referenced, or a thread-local block, etc.).  Then again, it might
14534      not be worthwhile.  I'm assuming that it isn't unless performance
14535      or memory numbers show me otherwise.  */
14536
14537   dwarf2_symbol_mark_computed (attr, sym, cu);
14538   SYMBOL_CLASS (sym) = LOC_COMPUTED;
14539
14540   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
14541     cu->has_loclist = 1;
14542 }
14543
14544 /* Given a pointer to a DWARF information entry, figure out if we need
14545    to make a symbol table entry for it, and if so, create a new entry
14546    and return a pointer to it.
14547    If TYPE is NULL, determine symbol type from the die, otherwise
14548    used the passed type.
14549    If SPACE is not NULL, use it to hold the new symbol.  If it is
14550    NULL, allocate a new symbol on the objfile's obstack.  */
14551
14552 static struct symbol *
14553 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
14554                  struct symbol *space)
14555 {
14556   struct objfile *objfile = cu->objfile;
14557   struct symbol *sym = NULL;
14558   char *name;
14559   struct attribute *attr = NULL;
14560   struct attribute *attr2 = NULL;
14561   CORE_ADDR baseaddr;
14562   struct pending **list_to_add = NULL;
14563
14564   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
14565
14566   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14567
14568   name = dwarf2_name (die, cu);
14569   if (name)
14570     {
14571       const char *linkagename;
14572       int suppress_add = 0;
14573
14574       if (space)
14575         sym = space;
14576       else
14577         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
14578       OBJSTAT (objfile, n_syms++);
14579
14580       /* Cache this symbol's name and the name's demangled form (if any).  */
14581       SYMBOL_SET_LANGUAGE (sym, cu->language);
14582       linkagename = dwarf2_physname (name, die, cu);
14583       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
14584
14585       /* Fortran does not have mangling standard and the mangling does differ
14586          between gfortran, iFort etc.  */
14587       if (cu->language == language_fortran
14588           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
14589         symbol_set_demangled_name (&(sym->ginfo),
14590                                    (char *) dwarf2_full_name (name, die, cu),
14591                                    NULL);
14592
14593       /* Default assumptions.
14594          Use the passed type or decode it from the die.  */
14595       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
14596       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
14597       if (type != NULL)
14598         SYMBOL_TYPE (sym) = type;
14599       else
14600         SYMBOL_TYPE (sym) = die_type (die, cu);
14601       attr = dwarf2_attr (die,
14602                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
14603                           cu);
14604       if (attr)
14605         {
14606           SYMBOL_LINE (sym) = DW_UNSND (attr);
14607         }
14608
14609       attr = dwarf2_attr (die,
14610                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
14611                           cu);
14612       if (attr)
14613         {
14614           int file_index = DW_UNSND (attr);
14615
14616           if (cu->line_header == NULL
14617               || file_index > cu->line_header->num_file_names)
14618             complaint (&symfile_complaints,
14619                        _("file index out of range"));
14620           else if (file_index > 0)
14621             {
14622               struct file_entry *fe;
14623
14624               fe = &cu->line_header->file_names[file_index - 1];
14625               SYMBOL_SYMTAB (sym) = fe->symtab;
14626             }
14627         }
14628
14629       switch (die->tag)
14630         {
14631         case DW_TAG_label:
14632           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14633           if (attr)
14634             {
14635               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
14636             }
14637           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
14638           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
14639           SYMBOL_CLASS (sym) = LOC_LABEL;
14640           add_symbol_to_list (sym, cu->list_in_scope);
14641           break;
14642         case DW_TAG_subprogram:
14643           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
14644              finish_block.  */
14645           SYMBOL_CLASS (sym) = LOC_BLOCK;
14646           attr2 = dwarf2_attr (die, DW_AT_external, cu);
14647           if ((attr2 && (DW_UNSND (attr2) != 0))
14648               || cu->language == language_ada)
14649             {
14650               /* Subprograms marked external are stored as a global symbol.
14651                  Ada subprograms, whether marked external or not, are always
14652                  stored as a global symbol, because we want to be able to
14653                  access them globally.  For instance, we want to be able
14654                  to break on a nested subprogram without having to
14655                  specify the context.  */
14656               list_to_add = &global_symbols;
14657             }
14658           else
14659             {
14660               list_to_add = cu->list_in_scope;
14661             }
14662           break;
14663         case DW_TAG_inlined_subroutine:
14664           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
14665              finish_block.  */
14666           SYMBOL_CLASS (sym) = LOC_BLOCK;
14667           SYMBOL_INLINED (sym) = 1;
14668           list_to_add = cu->list_in_scope;
14669           break;
14670         case DW_TAG_template_value_param:
14671           suppress_add = 1;
14672           /* Fall through.  */
14673         case DW_TAG_constant:
14674         case DW_TAG_variable:
14675         case DW_TAG_member:
14676           /* Compilation with minimal debug info may result in
14677              variables with missing type entries.  Change the
14678              misleading `void' type to something sensible.  */
14679           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
14680             SYMBOL_TYPE (sym)
14681               = objfile_type (objfile)->nodebug_data_symbol;
14682
14683           attr = dwarf2_attr (die, DW_AT_const_value, cu);
14684           /* In the case of DW_TAG_member, we should only be called for
14685              static const members.  */
14686           if (die->tag == DW_TAG_member)
14687             {
14688               /* dwarf2_add_field uses die_is_declaration,
14689                  so we do the same.  */
14690               gdb_assert (die_is_declaration (die, cu));
14691               gdb_assert (attr);
14692             }
14693           if (attr)
14694             {
14695               dwarf2_const_value (attr, sym, cu);
14696               attr2 = dwarf2_attr (die, DW_AT_external, cu);
14697               if (!suppress_add)
14698                 {
14699                   if (attr2 && (DW_UNSND (attr2) != 0))
14700                     list_to_add = &global_symbols;
14701                   else
14702                     list_to_add = cu->list_in_scope;
14703                 }
14704               break;
14705             }
14706           attr = dwarf2_attr (die, DW_AT_location, cu);
14707           if (attr)
14708             {
14709               var_decode_location (attr, sym, cu);
14710               attr2 = dwarf2_attr (die, DW_AT_external, cu);
14711               if (SYMBOL_CLASS (sym) == LOC_STATIC
14712                   && SYMBOL_VALUE_ADDRESS (sym) == 0
14713                   && !dwarf2_per_objfile->has_section_at_zero)
14714                 {
14715                   /* When a static variable is eliminated by the linker,
14716                      the corresponding debug information is not stripped
14717                      out, but the variable address is set to null;
14718                      do not add such variables into symbol table.  */
14719                 }
14720               else if (attr2 && (DW_UNSND (attr2) != 0))
14721                 {
14722                   /* Workaround gfortran PR debug/40040 - it uses
14723                      DW_AT_location for variables in -fPIC libraries which may
14724                      get overriden by other libraries/executable and get
14725                      a different address.  Resolve it by the minimal symbol
14726                      which may come from inferior's executable using copy
14727                      relocation.  Make this workaround only for gfortran as for
14728                      other compilers GDB cannot guess the minimal symbol
14729                      Fortran mangling kind.  */
14730                   if (cu->language == language_fortran && die->parent
14731                       && die->parent->tag == DW_TAG_module
14732                       && cu->producer
14733                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
14734                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
14735
14736                   /* A variable with DW_AT_external is never static,
14737                      but it may be block-scoped.  */
14738                   list_to_add = (cu->list_in_scope == &file_symbols
14739                                  ? &global_symbols : cu->list_in_scope);
14740                 }
14741               else
14742                 list_to_add = cu->list_in_scope;
14743             }
14744           else
14745             {
14746               /* We do not know the address of this symbol.
14747                  If it is an external symbol and we have type information
14748                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
14749                  The address of the variable will then be determined from
14750                  the minimal symbol table whenever the variable is
14751                  referenced.  */
14752               attr2 = dwarf2_attr (die, DW_AT_external, cu);
14753               if (attr2 && (DW_UNSND (attr2) != 0)
14754                   && dwarf2_attr (die, DW_AT_type, cu) != NULL)
14755                 {
14756                   /* A variable with DW_AT_external is never static, but it
14757                      may be block-scoped.  */
14758                   list_to_add = (cu->list_in_scope == &file_symbols
14759                                  ? &global_symbols : cu->list_in_scope);
14760
14761                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
14762                 }
14763               else if (!die_is_declaration (die, cu))
14764                 {
14765                   /* Use the default LOC_OPTIMIZED_OUT class.  */
14766                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
14767                   if (!suppress_add)
14768                     list_to_add = cu->list_in_scope;
14769                 }
14770             }
14771           break;
14772         case DW_TAG_formal_parameter:
14773           /* If we are inside a function, mark this as an argument.  If
14774              not, we might be looking at an argument to an inlined function
14775              when we do not have enough information to show inlined frames;
14776              pretend it's a local variable in that case so that the user can
14777              still see it.  */
14778           if (context_stack_depth > 0
14779               && context_stack[context_stack_depth - 1].name != NULL)
14780             SYMBOL_IS_ARGUMENT (sym) = 1;
14781           attr = dwarf2_attr (die, DW_AT_location, cu);
14782           if (attr)
14783             {
14784               var_decode_location (attr, sym, cu);
14785             }
14786           attr = dwarf2_attr (die, DW_AT_const_value, cu);
14787           if (attr)
14788             {
14789               dwarf2_const_value (attr, sym, cu);
14790             }
14791
14792           list_to_add = cu->list_in_scope;
14793           break;
14794         case DW_TAG_unspecified_parameters:
14795           /* From varargs functions; gdb doesn't seem to have any
14796              interest in this information, so just ignore it for now.
14797              (FIXME?) */
14798           break;
14799         case DW_TAG_template_type_param:
14800           suppress_add = 1;
14801           /* Fall through.  */
14802         case DW_TAG_class_type:
14803         case DW_TAG_interface_type:
14804         case DW_TAG_structure_type:
14805         case DW_TAG_union_type:
14806         case DW_TAG_set_type:
14807         case DW_TAG_enumeration_type:
14808           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14809           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
14810
14811           {
14812             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
14813                really ever be static objects: otherwise, if you try
14814                to, say, break of a class's method and you're in a file
14815                which doesn't mention that class, it won't work unless
14816                the check for all static symbols in lookup_symbol_aux
14817                saves you.  See the OtherFileClass tests in
14818                gdb.c++/namespace.exp.  */
14819
14820             if (!suppress_add)
14821               {
14822                 list_to_add = (cu->list_in_scope == &file_symbols
14823                                && (cu->language == language_cplus
14824                                    || cu->language == language_java)
14825                                ? &global_symbols : cu->list_in_scope);
14826
14827                 /* The semantics of C++ state that "struct foo {
14828                    ... }" also defines a typedef for "foo".  A Java
14829                    class declaration also defines a typedef for the
14830                    class.  */
14831                 if (cu->language == language_cplus
14832                     || cu->language == language_java
14833                     || cu->language == language_ada)
14834                   {
14835                     /* The symbol's name is already allocated along
14836                        with this objfile, so we don't need to
14837                        duplicate it for the type.  */
14838                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
14839                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
14840                   }
14841               }
14842           }
14843           break;
14844         case DW_TAG_typedef:
14845           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14846           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
14847           list_to_add = cu->list_in_scope;
14848           break;
14849         case DW_TAG_base_type:
14850         case DW_TAG_subrange_type:
14851           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14852           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
14853           list_to_add = cu->list_in_scope;
14854           break;
14855         case DW_TAG_enumerator:
14856           attr = dwarf2_attr (die, DW_AT_const_value, cu);
14857           if (attr)
14858             {
14859               dwarf2_const_value (attr, sym, cu);
14860             }
14861           {
14862             /* NOTE: carlton/2003-11-10: See comment above in the
14863                DW_TAG_class_type, etc. block.  */
14864
14865             list_to_add = (cu->list_in_scope == &file_symbols
14866                            && (cu->language == language_cplus
14867                                || cu->language == language_java)
14868                            ? &global_symbols : cu->list_in_scope);
14869           }
14870           break;
14871         case DW_TAG_namespace:
14872           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14873           list_to_add = &global_symbols;
14874           break;
14875         default:
14876           /* Not a tag we recognize.  Hopefully we aren't processing
14877              trash data, but since we must specifically ignore things
14878              we don't recognize, there is nothing else we should do at
14879              this point.  */
14880           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
14881                      dwarf_tag_name (die->tag));
14882           break;
14883         }
14884
14885       if (suppress_add)
14886         {
14887           sym->hash_next = objfile->template_symbols;
14888           objfile->template_symbols = sym;
14889           list_to_add = NULL;
14890         }
14891
14892       if (list_to_add != NULL)
14893         add_symbol_to_list (sym, list_to_add);
14894
14895       /* For the benefit of old versions of GCC, check for anonymous
14896          namespaces based on the demangled name.  */
14897       if (!processing_has_namespace_info
14898           && cu->language == language_cplus)
14899         cp_scan_for_anonymous_namespaces (sym, objfile);
14900     }
14901   return (sym);
14902 }
14903
14904 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
14905
14906 static struct symbol *
14907 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
14908 {
14909   return new_symbol_full (die, type, cu, NULL);
14910 }
14911
14912 /* Given an attr with a DW_FORM_dataN value in host byte order,
14913    zero-extend it as appropriate for the symbol's type.  The DWARF
14914    standard (v4) is not entirely clear about the meaning of using
14915    DW_FORM_dataN for a constant with a signed type, where the type is
14916    wider than the data.  The conclusion of a discussion on the DWARF
14917    list was that this is unspecified.  We choose to always zero-extend
14918    because that is the interpretation long in use by GCC.  */
14919
14920 static gdb_byte *
14921 dwarf2_const_value_data (struct attribute *attr, struct type *type,
14922                          const char *name, struct obstack *obstack,
14923                          struct dwarf2_cu *cu, LONGEST *value, int bits)
14924 {
14925   struct objfile *objfile = cu->objfile;
14926   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
14927                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
14928   LONGEST l = DW_UNSND (attr);
14929
14930   if (bits < sizeof (*value) * 8)
14931     {
14932       l &= ((LONGEST) 1 << bits) - 1;
14933       *value = l;
14934     }
14935   else if (bits == sizeof (*value) * 8)
14936     *value = l;
14937   else
14938     {
14939       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
14940       store_unsigned_integer (bytes, bits / 8, byte_order, l);
14941       return bytes;
14942     }
14943
14944   return NULL;
14945 }
14946
14947 /* Read a constant value from an attribute.  Either set *VALUE, or if
14948    the value does not fit in *VALUE, set *BYTES - either already
14949    allocated on the objfile obstack, or newly allocated on OBSTACK,
14950    or, set *BATON, if we translated the constant to a location
14951    expression.  */
14952
14953 static void
14954 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
14955                          const char *name, struct obstack *obstack,
14956                          struct dwarf2_cu *cu,
14957                          LONGEST *value, gdb_byte **bytes,
14958                          struct dwarf2_locexpr_baton **baton)
14959 {
14960   struct objfile *objfile = cu->objfile;
14961   struct comp_unit_head *cu_header = &cu->header;
14962   struct dwarf_block *blk;
14963   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
14964                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
14965
14966   *value = 0;
14967   *bytes = NULL;
14968   *baton = NULL;
14969
14970   switch (attr->form)
14971     {
14972     case DW_FORM_addr:
14973     case DW_FORM_GNU_addr_index:
14974       {
14975         gdb_byte *data;
14976
14977         if (TYPE_LENGTH (type) != cu_header->addr_size)
14978           dwarf2_const_value_length_mismatch_complaint (name,
14979                                                         cu_header->addr_size,
14980                                                         TYPE_LENGTH (type));
14981         /* Symbols of this form are reasonably rare, so we just
14982            piggyback on the existing location code rather than writing
14983            a new implementation of symbol_computed_ops.  */
14984         *baton = obstack_alloc (&objfile->objfile_obstack,
14985                                 sizeof (struct dwarf2_locexpr_baton));
14986         (*baton)->per_cu = cu->per_cu;
14987         gdb_assert ((*baton)->per_cu);
14988
14989         (*baton)->size = 2 + cu_header->addr_size;
14990         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
14991         (*baton)->data = data;
14992
14993         data[0] = DW_OP_addr;
14994         store_unsigned_integer (&data[1], cu_header->addr_size,
14995                                 byte_order, DW_ADDR (attr));
14996         data[cu_header->addr_size + 1] = DW_OP_stack_value;
14997       }
14998       break;
14999     case DW_FORM_string:
15000     case DW_FORM_strp:
15001     case DW_FORM_GNU_str_index:
15002       /* DW_STRING is already allocated on the objfile obstack, point
15003          directly to it.  */
15004       *bytes = (gdb_byte *) DW_STRING (attr);
15005       break;
15006     case DW_FORM_block1:
15007     case DW_FORM_block2:
15008     case DW_FORM_block4:
15009     case DW_FORM_block:
15010     case DW_FORM_exprloc:
15011       blk = DW_BLOCK (attr);
15012       if (TYPE_LENGTH (type) != blk->size)
15013         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
15014                                                       TYPE_LENGTH (type));
15015       *bytes = blk->data;
15016       break;
15017
15018       /* The DW_AT_const_value attributes are supposed to carry the
15019          symbol's value "represented as it would be on the target
15020          architecture."  By the time we get here, it's already been
15021          converted to host endianness, so we just need to sign- or
15022          zero-extend it as appropriate.  */
15023     case DW_FORM_data1:
15024       *bytes = dwarf2_const_value_data (attr, type, name,
15025                                         obstack, cu, value, 8);
15026       break;
15027     case DW_FORM_data2:
15028       *bytes = dwarf2_const_value_data (attr, type, name,
15029                                         obstack, cu, value, 16);
15030       break;
15031     case DW_FORM_data4:
15032       *bytes = dwarf2_const_value_data (attr, type, name,
15033                                         obstack, cu, value, 32);
15034       break;
15035     case DW_FORM_data8:
15036       *bytes = dwarf2_const_value_data (attr, type, name,
15037                                         obstack, cu, value, 64);
15038       break;
15039
15040     case DW_FORM_sdata:
15041       *value = DW_SND (attr);
15042       break;
15043
15044     case DW_FORM_udata:
15045       *value = DW_UNSND (attr);
15046       break;
15047
15048     default:
15049       complaint (&symfile_complaints,
15050                  _("unsupported const value attribute form: '%s'"),
15051                  dwarf_form_name (attr->form));
15052       *value = 0;
15053       break;
15054     }
15055 }
15056
15057
15058 /* Copy constant value from an attribute to a symbol.  */
15059
15060 static void
15061 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
15062                     struct dwarf2_cu *cu)
15063 {
15064   struct objfile *objfile = cu->objfile;
15065   struct comp_unit_head *cu_header = &cu->header;
15066   LONGEST value;
15067   gdb_byte *bytes;
15068   struct dwarf2_locexpr_baton *baton;
15069
15070   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
15071                            SYMBOL_PRINT_NAME (sym),
15072                            &objfile->objfile_obstack, cu,
15073                            &value, &bytes, &baton);
15074
15075   if (baton != NULL)
15076     {
15077       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
15078       SYMBOL_LOCATION_BATON (sym) = baton;
15079       SYMBOL_CLASS (sym) = LOC_COMPUTED;
15080     }
15081   else if (bytes != NULL)
15082      {
15083       SYMBOL_VALUE_BYTES (sym) = bytes;
15084       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
15085     }
15086   else
15087     {
15088       SYMBOL_VALUE (sym) = value;
15089       SYMBOL_CLASS (sym) = LOC_CONST;
15090     }
15091 }
15092
15093 /* Return the type of the die in question using its DW_AT_type attribute.  */
15094
15095 static struct type *
15096 die_type (struct die_info *die, struct dwarf2_cu *cu)
15097 {
15098   struct attribute *type_attr;
15099
15100   type_attr = dwarf2_attr (die, DW_AT_type, cu);
15101   if (!type_attr)
15102     {
15103       /* A missing DW_AT_type represents a void type.  */
15104       return objfile_type (cu->objfile)->builtin_void;
15105     }
15106
15107   return lookup_die_type (die, type_attr, cu);
15108 }
15109
15110 /* True iff CU's producer generates GNAT Ada auxiliary information
15111    that allows to find parallel types through that information instead
15112    of having to do expensive parallel lookups by type name.  */
15113
15114 static int
15115 need_gnat_info (struct dwarf2_cu *cu)
15116 {
15117   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
15118      of GNAT produces this auxiliary information, without any indication
15119      that it is produced.  Part of enhancing the FSF version of GNAT
15120      to produce that information will be to put in place an indicator
15121      that we can use in order to determine whether the descriptive type
15122      info is available or not.  One suggestion that has been made is
15123      to use a new attribute, attached to the CU die.  For now, assume
15124      that the descriptive type info is not available.  */
15125   return 0;
15126 }
15127
15128 /* Return the auxiliary type of the die in question using its
15129    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
15130    attribute is not present.  */
15131
15132 static struct type *
15133 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
15134 {
15135   struct attribute *type_attr;
15136
15137   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
15138   if (!type_attr)
15139     return NULL;
15140
15141   return lookup_die_type (die, type_attr, cu);
15142 }
15143
15144 /* If DIE has a descriptive_type attribute, then set the TYPE's
15145    descriptive type accordingly.  */
15146
15147 static void
15148 set_descriptive_type (struct type *type, struct die_info *die,
15149                       struct dwarf2_cu *cu)
15150 {
15151   struct type *descriptive_type = die_descriptive_type (die, cu);
15152
15153   if (descriptive_type)
15154     {
15155       ALLOCATE_GNAT_AUX_TYPE (type);
15156       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
15157     }
15158 }
15159
15160 /* Return the containing type of the die in question using its
15161    DW_AT_containing_type attribute.  */
15162
15163 static struct type *
15164 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
15165 {
15166   struct attribute *type_attr;
15167
15168   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
15169   if (!type_attr)
15170     error (_("Dwarf Error: Problem turning containing type into gdb type "
15171              "[in module %s]"), cu->objfile->name);
15172
15173   return lookup_die_type (die, type_attr, cu);
15174 }
15175
15176 /* Look up the type of DIE in CU using its type attribute ATTR.
15177    If there is no type substitute an error marker.  */
15178
15179 static struct type *
15180 lookup_die_type (struct die_info *die, struct attribute *attr,
15181                  struct dwarf2_cu *cu)
15182 {
15183   struct objfile *objfile = cu->objfile;
15184   struct type *this_type;
15185
15186   /* First see if we have it cached.  */
15187
15188   if (is_ref_attr (attr))
15189     {
15190       sect_offset offset = dwarf2_get_ref_die_offset (attr);
15191
15192       this_type = get_die_type_at_offset (offset, cu->per_cu);
15193     }
15194   else if (attr->form == DW_FORM_ref_sig8)
15195     {
15196       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
15197
15198       /* sig_type will be NULL if the signatured type is missing from
15199          the debug info.  */
15200       if (sig_type == NULL)
15201         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
15202                  "at 0x%x [in module %s]"),
15203                die->offset.sect_off, objfile->name);
15204
15205       gdb_assert (sig_type->per_cu.is_debug_types);
15206       /* If we haven't filled in type_offset_in_section yet, then we
15207          haven't read the type in yet.  */
15208       this_type = NULL;
15209       if (sig_type->type_offset_in_section.sect_off != 0)
15210         {
15211           this_type =
15212             get_die_type_at_offset (sig_type->type_offset_in_section,
15213                                     &sig_type->per_cu);
15214         }
15215     }
15216   else
15217     {
15218       dump_die_for_error (die);
15219       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
15220              dwarf_attr_name (attr->name), objfile->name);
15221     }
15222
15223   /* If not cached we need to read it in.  */
15224
15225   if (this_type == NULL)
15226     {
15227       struct die_info *type_die;
15228       struct dwarf2_cu *type_cu = cu;
15229
15230       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
15231       /* If we found the type now, it's probably because the type came
15232          from an inter-CU reference and the type's CU got expanded before
15233          ours.  */
15234       this_type = get_die_type (type_die, type_cu);
15235       if (this_type == NULL)
15236         this_type = read_type_die_1 (type_die, type_cu);
15237     }
15238
15239   /* If we still don't have a type use an error marker.  */
15240
15241   if (this_type == NULL)
15242     {
15243       char *message, *saved;
15244
15245       /* read_type_die already issued a complaint.  */
15246       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
15247                             objfile->name,
15248                             cu->header.offset.sect_off,
15249                             die->offset.sect_off);
15250       saved = obstack_copy0 (&objfile->objfile_obstack,
15251                              message, strlen (message));
15252       xfree (message);
15253
15254       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
15255     }
15256
15257   return this_type;
15258 }
15259
15260 /* Return the type in DIE, CU.
15261    Returns NULL for invalid types.
15262
15263    This first does a lookup in the appropriate type_hash table,
15264    and only reads the die in if necessary.
15265
15266    NOTE: This can be called when reading in partial or full symbols.  */
15267
15268 static struct type *
15269 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
15270 {
15271   struct type *this_type;
15272
15273   this_type = get_die_type (die, cu);
15274   if (this_type)
15275     return this_type;
15276
15277   return read_type_die_1 (die, cu);
15278 }
15279
15280 /* Read the type in DIE, CU.
15281    Returns NULL for invalid types.  */
15282
15283 static struct type *
15284 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
15285 {
15286   struct type *this_type = NULL;
15287
15288   switch (die->tag)
15289     {
15290     case DW_TAG_class_type:
15291     case DW_TAG_interface_type:
15292     case DW_TAG_structure_type:
15293     case DW_TAG_union_type:
15294       this_type = read_structure_type (die, cu);
15295       break;
15296     case DW_TAG_enumeration_type:
15297       this_type = read_enumeration_type (die, cu);
15298       break;
15299     case DW_TAG_subprogram:
15300     case DW_TAG_subroutine_type:
15301     case DW_TAG_inlined_subroutine:
15302       this_type = read_subroutine_type (die, cu);
15303       break;
15304     case DW_TAG_array_type:
15305       this_type = read_array_type (die, cu);
15306       break;
15307     case DW_TAG_set_type:
15308       this_type = read_set_type (die, cu);
15309       break;
15310     case DW_TAG_pointer_type:
15311       this_type = read_tag_pointer_type (die, cu);
15312       break;
15313     case DW_TAG_ptr_to_member_type:
15314       this_type = read_tag_ptr_to_member_type (die, cu);
15315       break;
15316     case DW_TAG_reference_type:
15317       this_type = read_tag_reference_type (die, cu);
15318       break;
15319     case DW_TAG_const_type:
15320       this_type = read_tag_const_type (die, cu);
15321       break;
15322     case DW_TAG_volatile_type:
15323       this_type = read_tag_volatile_type (die, cu);
15324       break;
15325     case DW_TAG_string_type:
15326       this_type = read_tag_string_type (die, cu);
15327       break;
15328     case DW_TAG_typedef:
15329       this_type = read_typedef (die, cu);
15330       break;
15331     case DW_TAG_subrange_type:
15332       this_type = read_subrange_type (die, cu);
15333       break;
15334     case DW_TAG_base_type:
15335       this_type = read_base_type (die, cu);
15336       break;
15337     case DW_TAG_unspecified_type:
15338       this_type = read_unspecified_type (die, cu);
15339       break;
15340     case DW_TAG_namespace:
15341       this_type = read_namespace_type (die, cu);
15342       break;
15343     case DW_TAG_module:
15344       this_type = read_module_type (die, cu);
15345       break;
15346     default:
15347       complaint (&symfile_complaints,
15348                  _("unexpected tag in read_type_die: '%s'"),
15349                  dwarf_tag_name (die->tag));
15350       break;
15351     }
15352
15353   return this_type;
15354 }
15355
15356 /* See if we can figure out if the class lives in a namespace.  We do
15357    this by looking for a member function; its demangled name will
15358    contain namespace info, if there is any.
15359    Return the computed name or NULL.
15360    Space for the result is allocated on the objfile's obstack.
15361    This is the full-die version of guess_partial_die_structure_name.
15362    In this case we know DIE has no useful parent.  */
15363
15364 static char *
15365 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
15366 {
15367   struct die_info *spec_die;
15368   struct dwarf2_cu *spec_cu;
15369   struct die_info *child;
15370
15371   spec_cu = cu;
15372   spec_die = die_specification (die, &spec_cu);
15373   if (spec_die != NULL)
15374     {
15375       die = spec_die;
15376       cu = spec_cu;
15377     }
15378
15379   for (child = die->child;
15380        child != NULL;
15381        child = child->sibling)
15382     {
15383       if (child->tag == DW_TAG_subprogram)
15384         {
15385           struct attribute *attr;
15386
15387           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
15388           if (attr == NULL)
15389             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
15390           if (attr != NULL)
15391             {
15392               char *actual_name
15393                 = language_class_name_from_physname (cu->language_defn,
15394                                                      DW_STRING (attr));
15395               char *name = NULL;
15396
15397               if (actual_name != NULL)
15398                 {
15399                   char *die_name = dwarf2_name (die, cu);
15400
15401                   if (die_name != NULL
15402                       && strcmp (die_name, actual_name) != 0)
15403                     {
15404                       /* Strip off the class name from the full name.
15405                          We want the prefix.  */
15406                       int die_name_len = strlen (die_name);
15407                       int actual_name_len = strlen (actual_name);
15408
15409                       /* Test for '::' as a sanity check.  */
15410                       if (actual_name_len > die_name_len + 2
15411                           && actual_name[actual_name_len
15412                                          - die_name_len - 1] == ':')
15413                         name =
15414                           obsavestring (actual_name,
15415                                         actual_name_len - die_name_len - 2,
15416                                         &cu->objfile->objfile_obstack);
15417                     }
15418                 }
15419               xfree (actual_name);
15420               return name;
15421             }
15422         }
15423     }
15424
15425   return NULL;
15426 }
15427
15428 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
15429    prefix part in such case.  See
15430    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15431
15432 static char *
15433 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
15434 {
15435   struct attribute *attr;
15436   char *base;
15437
15438   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
15439       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
15440     return NULL;
15441
15442   attr = dwarf2_attr (die, DW_AT_name, cu);
15443   if (attr != NULL && DW_STRING (attr) != NULL)
15444     return NULL;
15445
15446   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
15447   if (attr == NULL)
15448     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
15449   if (attr == NULL || DW_STRING (attr) == NULL)
15450     return NULL;
15451
15452   /* dwarf2_name had to be already called.  */
15453   gdb_assert (DW_STRING_IS_CANONICAL (attr));
15454
15455   /* Strip the base name, keep any leading namespaces/classes.  */
15456   base = strrchr (DW_STRING (attr), ':');
15457   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
15458     return "";
15459
15460   return obsavestring (DW_STRING (attr), &base[-1] - DW_STRING (attr),
15461                        &cu->objfile->objfile_obstack);
15462 }
15463
15464 /* Return the name of the namespace/class that DIE is defined within,
15465    or "" if we can't tell.  The caller should not xfree the result.
15466
15467    For example, if we're within the method foo() in the following
15468    code:
15469
15470    namespace N {
15471      class C {
15472        void foo () {
15473        }
15474      };
15475    }
15476
15477    then determine_prefix on foo's die will return "N::C".  */
15478
15479 static const char *
15480 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
15481 {
15482   struct die_info *parent, *spec_die;
15483   struct dwarf2_cu *spec_cu;
15484   struct type *parent_type;
15485   char *retval;
15486
15487   if (cu->language != language_cplus && cu->language != language_java
15488       && cu->language != language_fortran)
15489     return "";
15490
15491   retval = anonymous_struct_prefix (die, cu);
15492   if (retval)
15493     return retval;
15494
15495   /* We have to be careful in the presence of DW_AT_specification.
15496      For example, with GCC 3.4, given the code
15497
15498      namespace N {
15499        void foo() {
15500          // Definition of N::foo.
15501        }
15502      }
15503
15504      then we'll have a tree of DIEs like this:
15505
15506      1: DW_TAG_compile_unit
15507        2: DW_TAG_namespace        // N
15508          3: DW_TAG_subprogram     // declaration of N::foo
15509        4: DW_TAG_subprogram       // definition of N::foo
15510             DW_AT_specification   // refers to die #3
15511
15512      Thus, when processing die #4, we have to pretend that we're in
15513      the context of its DW_AT_specification, namely the contex of die
15514      #3.  */
15515   spec_cu = cu;
15516   spec_die = die_specification (die, &spec_cu);
15517   if (spec_die == NULL)
15518     parent = die->parent;
15519   else
15520     {
15521       parent = spec_die->parent;
15522       cu = spec_cu;
15523     }
15524
15525   if (parent == NULL)
15526     return "";
15527   else if (parent->building_fullname)
15528     {
15529       const char *name;
15530       const char *parent_name;
15531
15532       /* It has been seen on RealView 2.2 built binaries,
15533          DW_TAG_template_type_param types actually _defined_ as
15534          children of the parent class:
15535
15536          enum E {};
15537          template class <class Enum> Class{};
15538          Class<enum E> class_e;
15539
15540          1: DW_TAG_class_type (Class)
15541            2: DW_TAG_enumeration_type (E)
15542              3: DW_TAG_enumerator (enum1:0)
15543              3: DW_TAG_enumerator (enum2:1)
15544              ...
15545            2: DW_TAG_template_type_param
15546               DW_AT_type  DW_FORM_ref_udata (E)
15547
15548          Besides being broken debug info, it can put GDB into an
15549          infinite loop.  Consider:
15550
15551          When we're building the full name for Class<E>, we'll start
15552          at Class, and go look over its template type parameters,
15553          finding E.  We'll then try to build the full name of E, and
15554          reach here.  We're now trying to build the full name of E,
15555          and look over the parent DIE for containing scope.  In the
15556          broken case, if we followed the parent DIE of E, we'd again
15557          find Class, and once again go look at its template type
15558          arguments, etc., etc.  Simply don't consider such parent die
15559          as source-level parent of this die (it can't be, the language
15560          doesn't allow it), and break the loop here.  */
15561       name = dwarf2_name (die, cu);
15562       parent_name = dwarf2_name (parent, cu);
15563       complaint (&symfile_complaints,
15564                  _("template param type '%s' defined within parent '%s'"),
15565                  name ? name : "<unknown>",
15566                  parent_name ? parent_name : "<unknown>");
15567       return "";
15568     }
15569   else
15570     switch (parent->tag)
15571       {
15572       case DW_TAG_namespace:
15573         parent_type = read_type_die (parent, cu);
15574         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
15575            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
15576            Work around this problem here.  */
15577         if (cu->language == language_cplus
15578             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
15579           return "";
15580         /* We give a name to even anonymous namespaces.  */
15581         return TYPE_TAG_NAME (parent_type);
15582       case DW_TAG_class_type:
15583       case DW_TAG_interface_type:
15584       case DW_TAG_structure_type:
15585       case DW_TAG_union_type:
15586       case DW_TAG_module:
15587         parent_type = read_type_die (parent, cu);
15588         if (TYPE_TAG_NAME (parent_type) != NULL)
15589           return TYPE_TAG_NAME (parent_type);
15590         else
15591           /* An anonymous structure is only allowed non-static data
15592              members; no typedefs, no member functions, et cetera.
15593              So it does not need a prefix.  */
15594           return "";
15595       case DW_TAG_compile_unit:
15596       case DW_TAG_partial_unit:
15597         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
15598         if (cu->language == language_cplus
15599             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15600             && die->child != NULL
15601             && (die->tag == DW_TAG_class_type
15602                 || die->tag == DW_TAG_structure_type
15603                 || die->tag == DW_TAG_union_type))
15604           {
15605             char *name = guess_full_die_structure_name (die, cu);
15606             if (name != NULL)
15607               return name;
15608           }
15609         return "";
15610       default:
15611         return determine_prefix (parent, cu);
15612       }
15613 }
15614
15615 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
15616    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
15617    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
15618    an obconcat, otherwise allocate storage for the result.  The CU argument is
15619    used to determine the language and hence, the appropriate separator.  */
15620
15621 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
15622
15623 static char *
15624 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
15625                  int physname, struct dwarf2_cu *cu)
15626 {
15627   const char *lead = "";
15628   const char *sep;
15629
15630   if (suffix == NULL || suffix[0] == '\0'
15631       || prefix == NULL || prefix[0] == '\0')
15632     sep = "";
15633   else if (cu->language == language_java)
15634     sep = ".";
15635   else if (cu->language == language_fortran && physname)
15636     {
15637       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
15638          DW_AT_MIPS_linkage_name is preferred and used instead.  */
15639
15640       lead = "__";
15641       sep = "_MOD_";
15642     }
15643   else
15644     sep = "::";
15645
15646   if (prefix == NULL)
15647     prefix = "";
15648   if (suffix == NULL)
15649     suffix = "";
15650
15651   if (obs == NULL)
15652     {
15653       char *retval
15654         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
15655
15656       strcpy (retval, lead);
15657       strcat (retval, prefix);
15658       strcat (retval, sep);
15659       strcat (retval, suffix);
15660       return retval;
15661     }
15662   else
15663     {
15664       /* We have an obstack.  */
15665       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
15666     }
15667 }
15668
15669 /* Return sibling of die, NULL if no sibling.  */
15670
15671 static struct die_info *
15672 sibling_die (struct die_info *die)
15673 {
15674   return die->sibling;
15675 }
15676
15677 /* Get name of a die, return NULL if not found.  */
15678
15679 static char *
15680 dwarf2_canonicalize_name (char *name, struct dwarf2_cu *cu,
15681                           struct obstack *obstack)
15682 {
15683   if (name && cu->language == language_cplus)
15684     {
15685       char *canon_name = cp_canonicalize_string (name);
15686
15687       if (canon_name != NULL)
15688         {
15689           if (strcmp (canon_name, name) != 0)
15690             name = obsavestring (canon_name, strlen (canon_name),
15691                                  obstack);
15692           xfree (canon_name);
15693         }
15694     }
15695
15696   return name;
15697 }
15698
15699 /* Get name of a die, return NULL if not found.  */
15700
15701 static char *
15702 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
15703 {
15704   struct attribute *attr;
15705
15706   attr = dwarf2_attr (die, DW_AT_name, cu);
15707   if ((!attr || !DW_STRING (attr))
15708       && die->tag != DW_TAG_class_type
15709       && die->tag != DW_TAG_interface_type
15710       && die->tag != DW_TAG_structure_type
15711       && die->tag != DW_TAG_union_type)
15712     return NULL;
15713
15714   switch (die->tag)
15715     {
15716     case DW_TAG_compile_unit:
15717     case DW_TAG_partial_unit:
15718       /* Compilation units have a DW_AT_name that is a filename, not
15719          a source language identifier.  */
15720     case DW_TAG_enumeration_type:
15721     case DW_TAG_enumerator:
15722       /* These tags always have simple identifiers already; no need
15723          to canonicalize them.  */
15724       return DW_STRING (attr);
15725
15726     case DW_TAG_subprogram:
15727       /* Java constructors will all be named "<init>", so return
15728          the class name when we see this special case.  */
15729       if (cu->language == language_java
15730           && DW_STRING (attr) != NULL
15731           && strcmp (DW_STRING (attr), "<init>") == 0)
15732         {
15733           struct dwarf2_cu *spec_cu = cu;
15734           struct die_info *spec_die;
15735
15736           /* GCJ will output '<init>' for Java constructor names.
15737              For this special case, return the name of the parent class.  */
15738
15739           /* GCJ may output suprogram DIEs with AT_specification set.
15740              If so, use the name of the specified DIE.  */
15741           spec_die = die_specification (die, &spec_cu);
15742           if (spec_die != NULL)
15743             return dwarf2_name (spec_die, spec_cu);
15744
15745           do
15746             {
15747               die = die->parent;
15748               if (die->tag == DW_TAG_class_type)
15749                 return dwarf2_name (die, cu);
15750             }
15751           while (die->tag != DW_TAG_compile_unit
15752                  && die->tag != DW_TAG_partial_unit);
15753         }
15754       break;
15755
15756     case DW_TAG_class_type:
15757     case DW_TAG_interface_type:
15758     case DW_TAG_structure_type:
15759     case DW_TAG_union_type:
15760       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
15761          structures or unions.  These were of the form "._%d" in GCC 4.1,
15762          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
15763          and GCC 4.4.  We work around this problem by ignoring these.  */
15764       if (attr && DW_STRING (attr)
15765           && (strncmp (DW_STRING (attr), "._", 2) == 0
15766               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
15767         return NULL;
15768
15769       /* GCC might emit a nameless typedef that has a linkage name.  See
15770          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15771       if (!attr || DW_STRING (attr) == NULL)
15772         {
15773           char *demangled = NULL;
15774
15775           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
15776           if (attr == NULL)
15777             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
15778
15779           if (attr == NULL || DW_STRING (attr) == NULL)
15780             return NULL;
15781
15782           /* Avoid demangling DW_STRING (attr) the second time on a second
15783              call for the same DIE.  */
15784           if (!DW_STRING_IS_CANONICAL (attr))
15785             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
15786
15787           if (demangled)
15788             {
15789               char *base;
15790
15791               /* FIXME: we already did this for the partial symbol... */
15792               DW_STRING (attr) = obsavestring (demangled, strlen (demangled),
15793                                                &cu->objfile->objfile_obstack);
15794               DW_STRING_IS_CANONICAL (attr) = 1;
15795               xfree (demangled);
15796
15797               /* Strip any leading namespaces/classes, keep only the base name.
15798                  DW_AT_name for named DIEs does not contain the prefixes.  */
15799               base = strrchr (DW_STRING (attr), ':');
15800               if (base && base > DW_STRING (attr) && base[-1] == ':')
15801                 return &base[1];
15802               else
15803                 return DW_STRING (attr);
15804             }
15805         }
15806       break;
15807
15808     default:
15809       break;
15810     }
15811
15812   if (!DW_STRING_IS_CANONICAL (attr))
15813     {
15814       DW_STRING (attr)
15815         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
15816                                     &cu->objfile->objfile_obstack);
15817       DW_STRING_IS_CANONICAL (attr) = 1;
15818     }
15819   return DW_STRING (attr);
15820 }
15821
15822 /* Return the die that this die in an extension of, or NULL if there
15823    is none.  *EXT_CU is the CU containing DIE on input, and the CU
15824    containing the return value on output.  */
15825
15826 static struct die_info *
15827 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
15828 {
15829   struct attribute *attr;
15830
15831   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
15832   if (attr == NULL)
15833     return NULL;
15834
15835   return follow_die_ref (die, attr, ext_cu);
15836 }
15837
15838 /* Convert a DIE tag into its string name.  */
15839
15840 static const char *
15841 dwarf_tag_name (unsigned tag)
15842 {
15843   const char *name = get_DW_TAG_name (tag);
15844
15845   if (name == NULL)
15846     return "DW_TAG_<unknown>";
15847
15848   return name;
15849 }
15850
15851 /* Convert a DWARF attribute code into its string name.  */
15852
15853 static const char *
15854 dwarf_attr_name (unsigned attr)
15855 {
15856   const char *name;
15857
15858 #ifdef MIPS /* collides with DW_AT_HP_block_index */
15859   if (attr == DW_AT_MIPS_fde)
15860     return "DW_AT_MIPS_fde";
15861 #else
15862   if (attr == DW_AT_HP_block_index)
15863     return "DW_AT_HP_block_index";
15864 #endif
15865
15866   name = get_DW_AT_name (attr);
15867
15868   if (name == NULL)
15869     return "DW_AT_<unknown>";
15870
15871   return name;
15872 }
15873
15874 /* Convert a DWARF value form code into its string name.  */
15875
15876 static const char *
15877 dwarf_form_name (unsigned form)
15878 {
15879   const char *name = get_DW_FORM_name (form);
15880
15881   if (name == NULL)
15882     return "DW_FORM_<unknown>";
15883
15884   return name;
15885 }
15886
15887 static char *
15888 dwarf_bool_name (unsigned mybool)
15889 {
15890   if (mybool)
15891     return "TRUE";
15892   else
15893     return "FALSE";
15894 }
15895
15896 /* Convert a DWARF type code into its string name.  */
15897
15898 static const char *
15899 dwarf_type_encoding_name (unsigned enc)
15900 {
15901   const char *name = get_DW_ATE_name (enc);
15902
15903   if (name == NULL)
15904     return "DW_ATE_<unknown>";
15905
15906   return name;
15907 }
15908
15909 static void
15910 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
15911 {
15912   unsigned int i;
15913
15914   print_spaces (indent, f);
15915   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
15916            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
15917
15918   if (die->parent != NULL)
15919     {
15920       print_spaces (indent, f);
15921       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
15922                           die->parent->offset.sect_off);
15923     }
15924
15925   print_spaces (indent, f);
15926   fprintf_unfiltered (f, "  has children: %s\n",
15927            dwarf_bool_name (die->child != NULL));
15928
15929   print_spaces (indent, f);
15930   fprintf_unfiltered (f, "  attributes:\n");
15931
15932   for (i = 0; i < die->num_attrs; ++i)
15933     {
15934       print_spaces (indent, f);
15935       fprintf_unfiltered (f, "    %s (%s) ",
15936                dwarf_attr_name (die->attrs[i].name),
15937                dwarf_form_name (die->attrs[i].form));
15938
15939       switch (die->attrs[i].form)
15940         {
15941         case DW_FORM_addr:
15942         case DW_FORM_GNU_addr_index:
15943           fprintf_unfiltered (f, "address: ");
15944           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
15945           break;
15946         case DW_FORM_block2:
15947         case DW_FORM_block4:
15948         case DW_FORM_block:
15949         case DW_FORM_block1:
15950           fprintf_unfiltered (f, "block: size %d",
15951                               DW_BLOCK (&die->attrs[i])->size);
15952           break;
15953         case DW_FORM_exprloc:
15954           fprintf_unfiltered (f, "expression: size %u",
15955                               DW_BLOCK (&die->attrs[i])->size);
15956           break;
15957         case DW_FORM_ref_addr:
15958           fprintf_unfiltered (f, "ref address: ");
15959           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
15960           break;
15961         case DW_FORM_ref1:
15962         case DW_FORM_ref2:
15963         case DW_FORM_ref4:
15964         case DW_FORM_ref8:
15965         case DW_FORM_ref_udata:
15966           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
15967                               (long) (DW_UNSND (&die->attrs[i])));
15968           break;
15969         case DW_FORM_data1:
15970         case DW_FORM_data2:
15971         case DW_FORM_data4:
15972         case DW_FORM_data8:
15973         case DW_FORM_udata:
15974         case DW_FORM_sdata:
15975           fprintf_unfiltered (f, "constant: %s",
15976                               pulongest (DW_UNSND (&die->attrs[i])));
15977           break;
15978         case DW_FORM_sec_offset:
15979           fprintf_unfiltered (f, "section offset: %s",
15980                               pulongest (DW_UNSND (&die->attrs[i])));
15981           break;
15982         case DW_FORM_ref_sig8:
15983           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
15984             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
15985                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
15986           else
15987             fprintf_unfiltered (f, "signatured type, offset: unknown");
15988           break;
15989         case DW_FORM_string:
15990         case DW_FORM_strp:
15991         case DW_FORM_GNU_str_index:
15992           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
15993                    DW_STRING (&die->attrs[i])
15994                    ? DW_STRING (&die->attrs[i]) : "",
15995                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
15996           break;
15997         case DW_FORM_flag:
15998           if (DW_UNSND (&die->attrs[i]))
15999             fprintf_unfiltered (f, "flag: TRUE");
16000           else
16001             fprintf_unfiltered (f, "flag: FALSE");
16002           break;
16003         case DW_FORM_flag_present:
16004           fprintf_unfiltered (f, "flag: TRUE");
16005           break;
16006         case DW_FORM_indirect:
16007           /* The reader will have reduced the indirect form to
16008              the "base form" so this form should not occur.  */
16009           fprintf_unfiltered (f, 
16010                               "unexpected attribute form: DW_FORM_indirect");
16011           break;
16012         default:
16013           fprintf_unfiltered (f, "unsupported attribute form: %d.",
16014                    die->attrs[i].form);
16015           break;
16016         }
16017       fprintf_unfiltered (f, "\n");
16018     }
16019 }
16020
16021 static void
16022 dump_die_for_error (struct die_info *die)
16023 {
16024   dump_die_shallow (gdb_stderr, 0, die);
16025 }
16026
16027 static void
16028 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
16029 {
16030   int indent = level * 4;
16031
16032   gdb_assert (die != NULL);
16033
16034   if (level >= max_level)
16035     return;
16036
16037   dump_die_shallow (f, indent, die);
16038
16039   if (die->child != NULL)
16040     {
16041       print_spaces (indent, f);
16042       fprintf_unfiltered (f, "  Children:");
16043       if (level + 1 < max_level)
16044         {
16045           fprintf_unfiltered (f, "\n");
16046           dump_die_1 (f, level + 1, max_level, die->child);
16047         }
16048       else
16049         {
16050           fprintf_unfiltered (f,
16051                               " [not printed, max nesting level reached]\n");
16052         }
16053     }
16054
16055   if (die->sibling != NULL && level > 0)
16056     {
16057       dump_die_1 (f, level, max_level, die->sibling);
16058     }
16059 }
16060
16061 /* This is called from the pdie macro in gdbinit.in.
16062    It's not static so gcc will keep a copy callable from gdb.  */
16063
16064 void
16065 dump_die (struct die_info *die, int max_level)
16066 {
16067   dump_die_1 (gdb_stdlog, 0, max_level, die);
16068 }
16069
16070 static void
16071 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
16072 {
16073   void **slot;
16074
16075   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
16076                                    INSERT);
16077
16078   *slot = die;
16079 }
16080
16081 /* DW_ADDR is always stored already as sect_offset; despite for the forms
16082    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
16083
16084 static int
16085 is_ref_attr (struct attribute *attr)
16086 {
16087   switch (attr->form)
16088     {
16089     case DW_FORM_ref_addr:
16090     case DW_FORM_ref1:
16091     case DW_FORM_ref2:
16092     case DW_FORM_ref4:
16093     case DW_FORM_ref8:
16094     case DW_FORM_ref_udata:
16095       return 1;
16096     default:
16097       return 0;
16098     }
16099 }
16100
16101 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
16102    required kind.  */
16103
16104 static sect_offset
16105 dwarf2_get_ref_die_offset (struct attribute *attr)
16106 {
16107   sect_offset retval = { DW_UNSND (attr) };
16108
16109   if (is_ref_attr (attr))
16110     return retval;
16111
16112   retval.sect_off = 0;
16113   complaint (&symfile_complaints,
16114              _("unsupported die ref attribute form: '%s'"),
16115              dwarf_form_name (attr->form));
16116   return retval;
16117 }
16118
16119 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
16120  * the value held by the attribute is not constant.  */
16121
16122 static LONGEST
16123 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
16124 {
16125   if (attr->form == DW_FORM_sdata)
16126     return DW_SND (attr);
16127   else if (attr->form == DW_FORM_udata
16128            || attr->form == DW_FORM_data1
16129            || attr->form == DW_FORM_data2
16130            || attr->form == DW_FORM_data4
16131            || attr->form == DW_FORM_data8)
16132     return DW_UNSND (attr);
16133   else
16134     {
16135       complaint (&symfile_complaints,
16136                  _("Attribute value is not a constant (%s)"),
16137                  dwarf_form_name (attr->form));
16138       return default_value;
16139     }
16140 }
16141
16142 /* Follow reference or signature attribute ATTR of SRC_DIE.
16143    On entry *REF_CU is the CU of SRC_DIE.
16144    On exit *REF_CU is the CU of the result.  */
16145
16146 static struct die_info *
16147 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
16148                        struct dwarf2_cu **ref_cu)
16149 {
16150   struct die_info *die;
16151
16152   if (is_ref_attr (attr))
16153     die = follow_die_ref (src_die, attr, ref_cu);
16154   else if (attr->form == DW_FORM_ref_sig8)
16155     die = follow_die_sig (src_die, attr, ref_cu);
16156   else
16157     {
16158       dump_die_for_error (src_die);
16159       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
16160              (*ref_cu)->objfile->name);
16161     }
16162
16163   return die;
16164 }
16165
16166 /* Follow reference OFFSET.
16167    On entry *REF_CU is the CU of the source die referencing OFFSET.
16168    On exit *REF_CU is the CU of the result.
16169    Returns NULL if OFFSET is invalid.  */
16170
16171 static struct die_info *
16172 follow_die_offset (sect_offset offset, struct dwarf2_cu **ref_cu)
16173 {
16174   struct die_info temp_die;
16175   struct dwarf2_cu *target_cu, *cu = *ref_cu;
16176
16177   gdb_assert (cu->per_cu != NULL);
16178
16179   target_cu = cu;
16180
16181   if (cu->per_cu->is_debug_types)
16182     {
16183       /* .debug_types CUs cannot reference anything outside their CU.
16184          If they need to, they have to reference a signatured type via
16185          DW_FORM_ref_sig8.  */
16186       if (! offset_in_cu_p (&cu->header, offset))
16187         return NULL;
16188     }
16189   else if (! offset_in_cu_p (&cu->header, offset))
16190     {
16191       struct dwarf2_per_cu_data *per_cu;
16192
16193       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
16194
16195       /* If necessary, add it to the queue and load its DIEs.  */
16196       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
16197         load_full_comp_unit (per_cu, cu->language);
16198
16199       target_cu = per_cu->cu;
16200     }
16201   else if (cu->dies == NULL)
16202     {
16203       /* We're loading full DIEs during partial symbol reading.  */
16204       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
16205       load_full_comp_unit (cu->per_cu, language_minimal);
16206     }
16207
16208   *ref_cu = target_cu;
16209   temp_die.offset = offset;
16210   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
16211 }
16212
16213 /* Follow reference attribute ATTR of SRC_DIE.
16214    On entry *REF_CU is the CU of SRC_DIE.
16215    On exit *REF_CU is the CU of the result.  */
16216
16217 static struct die_info *
16218 follow_die_ref (struct die_info *src_die, struct attribute *attr,
16219                 struct dwarf2_cu **ref_cu)
16220 {
16221   sect_offset offset = dwarf2_get_ref_die_offset (attr);
16222   struct dwarf2_cu *cu = *ref_cu;
16223   struct die_info *die;
16224
16225   die = follow_die_offset (offset, ref_cu);
16226   if (!die)
16227     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
16228            "at 0x%x [in module %s]"),
16229            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
16230
16231   return die;
16232 }
16233
16234 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
16235    Returned value is intended for DW_OP_call*.  Returned
16236    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
16237
16238 struct dwarf2_locexpr_baton
16239 dwarf2_fetch_die_location_block (cu_offset offset_in_cu,
16240                                  struct dwarf2_per_cu_data *per_cu,
16241                                  CORE_ADDR (*get_frame_pc) (void *baton),
16242                                  void *baton)
16243 {
16244   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
16245   struct dwarf2_cu *cu;
16246   struct die_info *die;
16247   struct attribute *attr;
16248   struct dwarf2_locexpr_baton retval;
16249
16250   dw2_setup (per_cu->objfile);
16251
16252   if (per_cu->cu == NULL)
16253     load_cu (per_cu);
16254   cu = per_cu->cu;
16255
16256   die = follow_die_offset (offset, &cu);
16257   if (!die)
16258     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
16259            offset.sect_off, per_cu->objfile->name);
16260
16261   attr = dwarf2_attr (die, DW_AT_location, cu);
16262   if (!attr)
16263     {
16264       /* DWARF: "If there is no such attribute, then there is no effect.".
16265          DATA is ignored if SIZE is 0.  */
16266
16267       retval.data = NULL;
16268       retval.size = 0;
16269     }
16270   else if (attr_form_is_section_offset (attr))
16271     {
16272       struct dwarf2_loclist_baton loclist_baton;
16273       CORE_ADDR pc = (*get_frame_pc) (baton);
16274       size_t size;
16275
16276       fill_in_loclist_baton (cu, &loclist_baton, attr);
16277
16278       retval.data = dwarf2_find_location_expression (&loclist_baton,
16279                                                      &size, pc);
16280       retval.size = size;
16281     }
16282   else
16283     {
16284       if (!attr_form_is_block (attr))
16285         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
16286                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
16287                offset.sect_off, per_cu->objfile->name);
16288
16289       retval.data = DW_BLOCK (attr)->data;
16290       retval.size = DW_BLOCK (attr)->size;
16291     }
16292   retval.per_cu = cu->per_cu;
16293
16294   age_cached_comp_units ();
16295
16296   return retval;
16297 }
16298
16299 /* Return the type of the DIE at DIE_OFFSET in the CU named by
16300    PER_CU.  */
16301
16302 struct type *
16303 dwarf2_get_die_type (cu_offset die_offset,
16304                      struct dwarf2_per_cu_data *per_cu)
16305 {
16306   sect_offset die_offset_sect;
16307
16308   dw2_setup (per_cu->objfile);
16309
16310   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
16311   return get_die_type_at_offset (die_offset_sect, per_cu);
16312 }
16313
16314 /* Follow the signature attribute ATTR in SRC_DIE.
16315    On entry *REF_CU is the CU of SRC_DIE.
16316    On exit *REF_CU is the CU of the result.  */
16317
16318 static struct die_info *
16319 follow_die_sig (struct die_info *src_die, struct attribute *attr,
16320                 struct dwarf2_cu **ref_cu)
16321 {
16322   struct objfile *objfile = (*ref_cu)->objfile;
16323   struct die_info temp_die;
16324   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16325   struct dwarf2_cu *sig_cu;
16326   struct die_info *die;
16327
16328   /* sig_type will be NULL if the signatured type is missing from
16329      the debug info.  */
16330   if (sig_type == NULL)
16331     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16332              "at 0x%x [in module %s]"),
16333            src_die->offset.sect_off, objfile->name);
16334
16335   /* If necessary, add it to the queue and load its DIEs.  */
16336
16337   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
16338     read_signatured_type (sig_type);
16339
16340   gdb_assert (sig_type->per_cu.cu != NULL);
16341
16342   sig_cu = sig_type->per_cu.cu;
16343   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
16344   temp_die.offset = sig_type->type_offset_in_section;
16345   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
16346                              temp_die.offset.sect_off);
16347   if (die)
16348     {
16349       *ref_cu = sig_cu;
16350       return die;
16351     }
16352
16353   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
16354          "from DIE at 0x%x [in module %s]"),
16355          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
16356 }
16357
16358 /* Given an offset of a signatured type, return its signatured_type.  */
16359
16360 static struct signatured_type *
16361 lookup_signatured_type_at_offset (struct objfile *objfile,
16362                                   struct dwarf2_section_info *section,
16363                                   sect_offset offset)
16364 {
16365   gdb_byte *info_ptr = section->buffer + offset.sect_off;
16366   unsigned int length, initial_length_size;
16367   unsigned int sig_offset;
16368   struct signatured_type find_entry, *sig_type;
16369
16370   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
16371   sig_offset = (initial_length_size
16372                 + 2 /*version*/
16373                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
16374                 + 1 /*address_size*/);
16375   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
16376   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
16377
16378   /* This is only used to lookup previously recorded types.
16379      If we didn't find it, it's our bug.  */
16380   gdb_assert (sig_type != NULL);
16381   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
16382
16383   return sig_type;
16384 }
16385
16386 /* Load the DIEs associated with type unit PER_CU into memory.  */
16387
16388 static void
16389 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
16390 {
16391   struct signatured_type *sig_type;
16392
16393   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
16394   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
16395
16396   /* We have the per_cu, but we need the signatured_type.
16397      Fortunately this is an easy translation.  */
16398   gdb_assert (per_cu->is_debug_types);
16399   sig_type = (struct signatured_type *) per_cu;
16400
16401   gdb_assert (per_cu->cu == NULL);
16402
16403   read_signatured_type (sig_type);
16404
16405   gdb_assert (per_cu->cu != NULL);
16406 }
16407
16408 /* die_reader_func for read_signatured_type.
16409    This is identical to load_full_comp_unit_reader,
16410    but is kept separate for now.  */
16411
16412 static void
16413 read_signatured_type_reader (const struct die_reader_specs *reader,
16414                              gdb_byte *info_ptr,
16415                              struct die_info *comp_unit_die,
16416                              int has_children,
16417                              void *data)
16418 {
16419   struct dwarf2_cu *cu = reader->cu;
16420
16421   gdb_assert (cu->die_hash == NULL);
16422   cu->die_hash =
16423     htab_create_alloc_ex (cu->header.length / 12,
16424                           die_hash,
16425                           die_eq,
16426                           NULL,
16427                           &cu->comp_unit_obstack,
16428                           hashtab_obstack_allocate,
16429                           dummy_obstack_deallocate);
16430
16431   if (has_children)
16432     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
16433                                                   &info_ptr, comp_unit_die);
16434   cu->dies = comp_unit_die;
16435   /* comp_unit_die is not stored in die_hash, no need.  */
16436
16437   /* We try not to read any attributes in this function, because not
16438      all CUs needed for references have been loaded yet, and symbol
16439      table processing isn't initialized.  But we have to set the CU language,
16440      or we won't be able to build types correctly.
16441      Similarly, if we do not read the producer, we can not apply
16442      producer-specific interpretation.  */
16443   prepare_one_comp_unit (cu, cu->dies, language_minimal);
16444 }
16445
16446 /* Read in a signatured type and build its CU and DIEs.
16447    If the type is a stub for the real type in a DWO file,
16448    read in the real type from the DWO file as well.  */
16449
16450 static void
16451 read_signatured_type (struct signatured_type *sig_type)
16452 {
16453   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
16454
16455   gdb_assert (per_cu->is_debug_types);
16456   gdb_assert (per_cu->cu == NULL);
16457
16458   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
16459                            read_signatured_type_reader, NULL);
16460 }
16461
16462 /* Decode simple location descriptions.
16463    Given a pointer to a dwarf block that defines a location, compute
16464    the location and return the value.
16465
16466    NOTE drow/2003-11-18: This function is called in two situations
16467    now: for the address of static or global variables (partial symbols
16468    only) and for offsets into structures which are expected to be
16469    (more or less) constant.  The partial symbol case should go away,
16470    and only the constant case should remain.  That will let this
16471    function complain more accurately.  A few special modes are allowed
16472    without complaint for global variables (for instance, global
16473    register values and thread-local values).
16474
16475    A location description containing no operations indicates that the
16476    object is optimized out.  The return value is 0 for that case.
16477    FIXME drow/2003-11-16: No callers check for this case any more; soon all
16478    callers will only want a very basic result and this can become a
16479    complaint.
16480
16481    Note that stack[0] is unused except as a default error return.  */
16482
16483 static CORE_ADDR
16484 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
16485 {
16486   struct objfile *objfile = cu->objfile;
16487   int i;
16488   int size = blk->size;
16489   gdb_byte *data = blk->data;
16490   CORE_ADDR stack[64];
16491   int stacki;
16492   unsigned int bytes_read, unsnd;
16493   gdb_byte op;
16494
16495   i = 0;
16496   stacki = 0;
16497   stack[stacki] = 0;
16498   stack[++stacki] = 0;
16499
16500   while (i < size)
16501     {
16502       op = data[i++];
16503       switch (op)
16504         {
16505         case DW_OP_lit0:
16506         case DW_OP_lit1:
16507         case DW_OP_lit2:
16508         case DW_OP_lit3:
16509         case DW_OP_lit4:
16510         case DW_OP_lit5:
16511         case DW_OP_lit6:
16512         case DW_OP_lit7:
16513         case DW_OP_lit8:
16514         case DW_OP_lit9:
16515         case DW_OP_lit10:
16516         case DW_OP_lit11:
16517         case DW_OP_lit12:
16518         case DW_OP_lit13:
16519         case DW_OP_lit14:
16520         case DW_OP_lit15:
16521         case DW_OP_lit16:
16522         case DW_OP_lit17:
16523         case DW_OP_lit18:
16524         case DW_OP_lit19:
16525         case DW_OP_lit20:
16526         case DW_OP_lit21:
16527         case DW_OP_lit22:
16528         case DW_OP_lit23:
16529         case DW_OP_lit24:
16530         case DW_OP_lit25:
16531         case DW_OP_lit26:
16532         case DW_OP_lit27:
16533         case DW_OP_lit28:
16534         case DW_OP_lit29:
16535         case DW_OP_lit30:
16536         case DW_OP_lit31:
16537           stack[++stacki] = op - DW_OP_lit0;
16538           break;
16539
16540         case DW_OP_reg0:
16541         case DW_OP_reg1:
16542         case DW_OP_reg2:
16543         case DW_OP_reg3:
16544         case DW_OP_reg4:
16545         case DW_OP_reg5:
16546         case DW_OP_reg6:
16547         case DW_OP_reg7:
16548         case DW_OP_reg8:
16549         case DW_OP_reg9:
16550         case DW_OP_reg10:
16551         case DW_OP_reg11:
16552         case DW_OP_reg12:
16553         case DW_OP_reg13:
16554         case DW_OP_reg14:
16555         case DW_OP_reg15:
16556         case DW_OP_reg16:
16557         case DW_OP_reg17:
16558         case DW_OP_reg18:
16559         case DW_OP_reg19:
16560         case DW_OP_reg20:
16561         case DW_OP_reg21:
16562         case DW_OP_reg22:
16563         case DW_OP_reg23:
16564         case DW_OP_reg24:
16565         case DW_OP_reg25:
16566         case DW_OP_reg26:
16567         case DW_OP_reg27:
16568         case DW_OP_reg28:
16569         case DW_OP_reg29:
16570         case DW_OP_reg30:
16571         case DW_OP_reg31:
16572           stack[++stacki] = op - DW_OP_reg0;
16573           if (i < size)
16574             dwarf2_complex_location_expr_complaint ();
16575           break;
16576
16577         case DW_OP_regx:
16578           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
16579           i += bytes_read;
16580           stack[++stacki] = unsnd;
16581           if (i < size)
16582             dwarf2_complex_location_expr_complaint ();
16583           break;
16584
16585         case DW_OP_addr:
16586           stack[++stacki] = read_address (objfile->obfd, &data[i],
16587                                           cu, &bytes_read);
16588           i += bytes_read;
16589           break;
16590
16591         case DW_OP_const1u:
16592           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
16593           i += 1;
16594           break;
16595
16596         case DW_OP_const1s:
16597           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
16598           i += 1;
16599           break;
16600
16601         case DW_OP_const2u:
16602           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
16603           i += 2;
16604           break;
16605
16606         case DW_OP_const2s:
16607           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
16608           i += 2;
16609           break;
16610
16611         case DW_OP_const4u:
16612           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
16613           i += 4;
16614           break;
16615
16616         case DW_OP_const4s:
16617           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
16618           i += 4;
16619           break;
16620
16621         case DW_OP_const8u:
16622           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
16623           i += 8;
16624           break;
16625
16626         case DW_OP_constu:
16627           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
16628                                                   &bytes_read);
16629           i += bytes_read;
16630           break;
16631
16632         case DW_OP_consts:
16633           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
16634           i += bytes_read;
16635           break;
16636
16637         case DW_OP_dup:
16638           stack[stacki + 1] = stack[stacki];
16639           stacki++;
16640           break;
16641
16642         case DW_OP_plus:
16643           stack[stacki - 1] += stack[stacki];
16644           stacki--;
16645           break;
16646
16647         case DW_OP_plus_uconst:
16648           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
16649                                                  &bytes_read);
16650           i += bytes_read;
16651           break;
16652
16653         case DW_OP_minus:
16654           stack[stacki - 1] -= stack[stacki];
16655           stacki--;
16656           break;
16657
16658         case DW_OP_deref:
16659           /* If we're not the last op, then we definitely can't encode
16660              this using GDB's address_class enum.  This is valid for partial
16661              global symbols, although the variable's address will be bogus
16662              in the psymtab.  */
16663           if (i < size)
16664             dwarf2_complex_location_expr_complaint ();
16665           break;
16666
16667         case DW_OP_GNU_push_tls_address:
16668           /* The top of the stack has the offset from the beginning
16669              of the thread control block at which the variable is located.  */
16670           /* Nothing should follow this operator, so the top of stack would
16671              be returned.  */
16672           /* This is valid for partial global symbols, but the variable's
16673              address will be bogus in the psymtab.  Make it always at least
16674              non-zero to not look as a variable garbage collected by linker
16675              which have DW_OP_addr 0.  */
16676           if (i < size)
16677             dwarf2_complex_location_expr_complaint ();
16678           stack[stacki]++;
16679           break;
16680
16681         case DW_OP_GNU_uninit:
16682           break;
16683
16684         case DW_OP_GNU_addr_index:
16685         case DW_OP_GNU_const_index:
16686           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
16687                                                          &bytes_read);
16688           i += bytes_read;
16689           break;
16690
16691         default:
16692           {
16693             const char *name = get_DW_OP_name (op);
16694
16695             if (name)
16696               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
16697                          name);
16698             else
16699               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
16700                          op);
16701           }
16702
16703           return (stack[stacki]);
16704         }
16705
16706       /* Enforce maximum stack depth of SIZE-1 to avoid writing
16707          outside of the allocated space.  Also enforce minimum>0.  */
16708       if (stacki >= ARRAY_SIZE (stack) - 1)
16709         {
16710           complaint (&symfile_complaints,
16711                      _("location description stack overflow"));
16712           return 0;
16713         }
16714
16715       if (stacki <= 0)
16716         {
16717           complaint (&symfile_complaints,
16718                      _("location description stack underflow"));
16719           return 0;
16720         }
16721     }
16722   return (stack[stacki]);
16723 }
16724
16725 /* memory allocation interface */
16726
16727 static struct dwarf_block *
16728 dwarf_alloc_block (struct dwarf2_cu *cu)
16729 {
16730   struct dwarf_block *blk;
16731
16732   blk = (struct dwarf_block *)
16733     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
16734   return (blk);
16735 }
16736
16737 static struct die_info *
16738 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
16739 {
16740   struct die_info *die;
16741   size_t size = sizeof (struct die_info);
16742
16743   if (num_attrs > 1)
16744     size += (num_attrs - 1) * sizeof (struct attribute);
16745
16746   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
16747   memset (die, 0, sizeof (struct die_info));
16748   return (die);
16749 }
16750
16751 \f
16752 /* Macro support.  */
16753
16754 /* Return the full name of file number I in *LH's file name table.
16755    Use COMP_DIR as the name of the current directory of the
16756    compilation.  The result is allocated using xmalloc; the caller is
16757    responsible for freeing it.  */
16758 static char *
16759 file_full_name (int file, struct line_header *lh, const char *comp_dir)
16760 {
16761   /* Is the file number a valid index into the line header's file name
16762      table?  Remember that file numbers start with one, not zero.  */
16763   if (1 <= file && file <= lh->num_file_names)
16764     {
16765       struct file_entry *fe = &lh->file_names[file - 1];
16766
16767       if (IS_ABSOLUTE_PATH (fe->name))
16768         return xstrdup (fe->name);
16769       else
16770         {
16771           const char *dir;
16772           int dir_len;
16773           char *full_name;
16774
16775           if (fe->dir_index)
16776             dir = lh->include_dirs[fe->dir_index - 1];
16777           else
16778             dir = comp_dir;
16779
16780           if (dir)
16781             {
16782               dir_len = strlen (dir);
16783               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
16784               strcpy (full_name, dir);
16785               full_name[dir_len] = '/';
16786               strcpy (full_name + dir_len + 1, fe->name);
16787               return full_name;
16788             }
16789           else
16790             return xstrdup (fe->name);
16791         }
16792     }
16793   else
16794     {
16795       /* The compiler produced a bogus file number.  We can at least
16796          record the macro definitions made in the file, even if we
16797          won't be able to find the file by name.  */
16798       char fake_name[80];
16799
16800       sprintf (fake_name, "<bad macro file number %d>", file);
16801
16802       complaint (&symfile_complaints,
16803                  _("bad file number in macro information (%d)"),
16804                  file);
16805
16806       return xstrdup (fake_name);
16807     }
16808 }
16809
16810
16811 static struct macro_source_file *
16812 macro_start_file (int file, int line,
16813                   struct macro_source_file *current_file,
16814                   const char *comp_dir,
16815                   struct line_header *lh, struct objfile *objfile)
16816 {
16817   /* The full name of this source file.  */
16818   char *full_name = file_full_name (file, lh, comp_dir);
16819
16820   /* We don't create a macro table for this compilation unit
16821      at all until we actually get a filename.  */
16822   if (! pending_macros)
16823     pending_macros = new_macro_table (&objfile->objfile_obstack,
16824                                       objfile->macro_cache);
16825
16826   if (! current_file)
16827     {
16828       /* If we have no current file, then this must be the start_file
16829          directive for the compilation unit's main source file.  */
16830       current_file = macro_set_main (pending_macros, full_name);
16831       macro_define_special (pending_macros);
16832     }
16833   else
16834     current_file = macro_include (current_file, line, full_name);
16835
16836   xfree (full_name);
16837
16838   return current_file;
16839 }
16840
16841
16842 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
16843    followed by a null byte.  */
16844 static char *
16845 copy_string (const char *buf, int len)
16846 {
16847   char *s = xmalloc (len + 1);
16848
16849   memcpy (s, buf, len);
16850   s[len] = '\0';
16851   return s;
16852 }
16853
16854
16855 static const char *
16856 consume_improper_spaces (const char *p, const char *body)
16857 {
16858   if (*p == ' ')
16859     {
16860       complaint (&symfile_complaints,
16861                  _("macro definition contains spaces "
16862                    "in formal argument list:\n`%s'"),
16863                  body);
16864
16865       while (*p == ' ')
16866         p++;
16867     }
16868
16869   return p;
16870 }
16871
16872
16873 static void
16874 parse_macro_definition (struct macro_source_file *file, int line,
16875                         const char *body)
16876 {
16877   const char *p;
16878
16879   /* The body string takes one of two forms.  For object-like macro
16880      definitions, it should be:
16881
16882         <macro name> " " <definition>
16883
16884      For function-like macro definitions, it should be:
16885
16886         <macro name> "() " <definition>
16887      or
16888         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
16889
16890      Spaces may appear only where explicitly indicated, and in the
16891      <definition>.
16892
16893      The Dwarf 2 spec says that an object-like macro's name is always
16894      followed by a space, but versions of GCC around March 2002 omit
16895      the space when the macro's definition is the empty string.
16896
16897      The Dwarf 2 spec says that there should be no spaces between the
16898      formal arguments in a function-like macro's formal argument list,
16899      but versions of GCC around March 2002 include spaces after the
16900      commas.  */
16901
16902
16903   /* Find the extent of the macro name.  The macro name is terminated
16904      by either a space or null character (for an object-like macro) or
16905      an opening paren (for a function-like macro).  */
16906   for (p = body; *p; p++)
16907     if (*p == ' ' || *p == '(')
16908       break;
16909
16910   if (*p == ' ' || *p == '\0')
16911     {
16912       /* It's an object-like macro.  */
16913       int name_len = p - body;
16914       char *name = copy_string (body, name_len);
16915       const char *replacement;
16916
16917       if (*p == ' ')
16918         replacement = body + name_len + 1;
16919       else
16920         {
16921           dwarf2_macro_malformed_definition_complaint (body);
16922           replacement = body + name_len;
16923         }
16924
16925       macro_define_object (file, line, name, replacement);
16926
16927       xfree (name);
16928     }
16929   else if (*p == '(')
16930     {
16931       /* It's a function-like macro.  */
16932       char *name = copy_string (body, p - body);
16933       int argc = 0;
16934       int argv_size = 1;
16935       char **argv = xmalloc (argv_size * sizeof (*argv));
16936
16937       p++;
16938
16939       p = consume_improper_spaces (p, body);
16940
16941       /* Parse the formal argument list.  */
16942       while (*p && *p != ')')
16943         {
16944           /* Find the extent of the current argument name.  */
16945           const char *arg_start = p;
16946
16947           while (*p && *p != ',' && *p != ')' && *p != ' ')
16948             p++;
16949
16950           if (! *p || p == arg_start)
16951             dwarf2_macro_malformed_definition_complaint (body);
16952           else
16953             {
16954               /* Make sure argv has room for the new argument.  */
16955               if (argc >= argv_size)
16956                 {
16957                   argv_size *= 2;
16958                   argv = xrealloc (argv, argv_size * sizeof (*argv));
16959                 }
16960
16961               argv[argc++] = copy_string (arg_start, p - arg_start);
16962             }
16963
16964           p = consume_improper_spaces (p, body);
16965
16966           /* Consume the comma, if present.  */
16967           if (*p == ',')
16968             {
16969               p++;
16970
16971               p = consume_improper_spaces (p, body);
16972             }
16973         }
16974
16975       if (*p == ')')
16976         {
16977           p++;
16978
16979           if (*p == ' ')
16980             /* Perfectly formed definition, no complaints.  */
16981             macro_define_function (file, line, name,
16982                                    argc, (const char **) argv,
16983                                    p + 1);
16984           else if (*p == '\0')
16985             {
16986               /* Complain, but do define it.  */
16987               dwarf2_macro_malformed_definition_complaint (body);
16988               macro_define_function (file, line, name,
16989                                      argc, (const char **) argv,
16990                                      p);
16991             }
16992           else
16993             /* Just complain.  */
16994             dwarf2_macro_malformed_definition_complaint (body);
16995         }
16996       else
16997         /* Just complain.  */
16998         dwarf2_macro_malformed_definition_complaint (body);
16999
17000       xfree (name);
17001       {
17002         int i;
17003
17004         for (i = 0; i < argc; i++)
17005           xfree (argv[i]);
17006       }
17007       xfree (argv);
17008     }
17009   else
17010     dwarf2_macro_malformed_definition_complaint (body);
17011 }
17012
17013 /* Skip some bytes from BYTES according to the form given in FORM.
17014    Returns the new pointer.  */
17015
17016 static gdb_byte *
17017 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
17018                  enum dwarf_form form,
17019                  unsigned int offset_size,
17020                  struct dwarf2_section_info *section)
17021 {
17022   unsigned int bytes_read;
17023
17024   switch (form)
17025     {
17026     case DW_FORM_data1:
17027     case DW_FORM_flag:
17028       ++bytes;
17029       break;
17030
17031     case DW_FORM_data2:
17032       bytes += 2;
17033       break;
17034
17035     case DW_FORM_data4:
17036       bytes += 4;
17037       break;
17038
17039     case DW_FORM_data8:
17040       bytes += 8;
17041       break;
17042
17043     case DW_FORM_string:
17044       read_direct_string (abfd, bytes, &bytes_read);
17045       bytes += bytes_read;
17046       break;
17047
17048     case DW_FORM_sec_offset:
17049     case DW_FORM_strp:
17050       bytes += offset_size;
17051       break;
17052
17053     case DW_FORM_block:
17054       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
17055       bytes += bytes_read;
17056       break;
17057
17058     case DW_FORM_block1:
17059       bytes += 1 + read_1_byte (abfd, bytes);
17060       break;
17061     case DW_FORM_block2:
17062       bytes += 2 + read_2_bytes (abfd, bytes);
17063       break;
17064     case DW_FORM_block4:
17065       bytes += 4 + read_4_bytes (abfd, bytes);
17066       break;
17067
17068     case DW_FORM_sdata:
17069     case DW_FORM_udata:
17070     case DW_FORM_GNU_addr_index:
17071     case DW_FORM_GNU_str_index:
17072       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
17073       if (bytes == NULL)
17074         {
17075           dwarf2_section_buffer_overflow_complaint (section);
17076           return NULL;
17077         }
17078       break;
17079
17080     default:
17081       {
17082       complain:
17083         complaint (&symfile_complaints,
17084                    _("invalid form 0x%x in `%s'"),
17085                    form,
17086                    section->asection->name);
17087         return NULL;
17088       }
17089     }
17090
17091   return bytes;
17092 }
17093
17094 /* A helper for dwarf_decode_macros that handles skipping an unknown
17095    opcode.  Returns an updated pointer to the macro data buffer; or,
17096    on error, issues a complaint and returns NULL.  */
17097
17098 static gdb_byte *
17099 skip_unknown_opcode (unsigned int opcode,
17100                      gdb_byte **opcode_definitions,
17101                      gdb_byte *mac_ptr, gdb_byte *mac_end,
17102                      bfd *abfd,
17103                      unsigned int offset_size,
17104                      struct dwarf2_section_info *section)
17105 {
17106   unsigned int bytes_read, i;
17107   unsigned long arg;
17108   gdb_byte *defn;
17109
17110   if (opcode_definitions[opcode] == NULL)
17111     {
17112       complaint (&symfile_complaints,
17113                  _("unrecognized DW_MACFINO opcode 0x%x"),
17114                  opcode);
17115       return NULL;
17116     }
17117
17118   defn = opcode_definitions[opcode];
17119   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
17120   defn += bytes_read;
17121
17122   for (i = 0; i < arg; ++i)
17123     {
17124       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
17125                                  section);
17126       if (mac_ptr == NULL)
17127         {
17128           /* skip_form_bytes already issued the complaint.  */
17129           return NULL;
17130         }
17131     }
17132
17133   return mac_ptr;
17134 }
17135
17136 /* A helper function which parses the header of a macro section.
17137    If the macro section is the extended (for now called "GNU") type,
17138    then this updates *OFFSET_SIZE.  Returns a pointer to just after
17139    the header, or issues a complaint and returns NULL on error.  */
17140
17141 static gdb_byte *
17142 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
17143                           bfd *abfd,
17144                           gdb_byte *mac_ptr,
17145                           unsigned int *offset_size,
17146                           int section_is_gnu)
17147 {
17148   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
17149
17150   if (section_is_gnu)
17151     {
17152       unsigned int version, flags;
17153
17154       version = read_2_bytes (abfd, mac_ptr);
17155       if (version != 4)
17156         {
17157           complaint (&symfile_complaints,
17158                      _("unrecognized version `%d' in .debug_macro section"),
17159                      version);
17160           return NULL;
17161         }
17162       mac_ptr += 2;
17163
17164       flags = read_1_byte (abfd, mac_ptr);
17165       ++mac_ptr;
17166       *offset_size = (flags & 1) ? 8 : 4;
17167
17168       if ((flags & 2) != 0)
17169         /* We don't need the line table offset.  */
17170         mac_ptr += *offset_size;
17171
17172       /* Vendor opcode descriptions.  */
17173       if ((flags & 4) != 0)
17174         {
17175           unsigned int i, count;
17176
17177           count = read_1_byte (abfd, mac_ptr);
17178           ++mac_ptr;
17179           for (i = 0; i < count; ++i)
17180             {
17181               unsigned int opcode, bytes_read;
17182               unsigned long arg;
17183
17184               opcode = read_1_byte (abfd, mac_ptr);
17185               ++mac_ptr;
17186               opcode_definitions[opcode] = mac_ptr;
17187               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17188               mac_ptr += bytes_read;
17189               mac_ptr += arg;
17190             }
17191         }
17192     }
17193
17194   return mac_ptr;
17195 }
17196
17197 /* A helper for dwarf_decode_macros that handles the GNU extensions,
17198    including DW_MACRO_GNU_transparent_include.  */
17199
17200 static void
17201 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
17202                           struct macro_source_file *current_file,
17203                           struct line_header *lh, char *comp_dir,
17204                           struct dwarf2_section_info *section,
17205                           int section_is_gnu,
17206                           unsigned int offset_size,
17207                           struct objfile *objfile,
17208                           htab_t include_hash)
17209 {
17210   enum dwarf_macro_record_type macinfo_type;
17211   int at_commandline;
17212   gdb_byte *opcode_definitions[256];
17213
17214   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
17215                                       &offset_size, section_is_gnu);
17216   if (mac_ptr == NULL)
17217     {
17218       /* We already issued a complaint.  */
17219       return;
17220     }
17221
17222   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
17223      GDB is still reading the definitions from command line.  First
17224      DW_MACINFO_start_file will need to be ignored as it was already executed
17225      to create CURRENT_FILE for the main source holding also the command line
17226      definitions.  On first met DW_MACINFO_start_file this flag is reset to
17227      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
17228
17229   at_commandline = 1;
17230
17231   do
17232     {
17233       /* Do we at least have room for a macinfo type byte?  */
17234       if (mac_ptr >= mac_end)
17235         {
17236           dwarf2_section_buffer_overflow_complaint (section);
17237           break;
17238         }
17239
17240       macinfo_type = read_1_byte (abfd, mac_ptr);
17241       mac_ptr++;
17242
17243       /* Note that we rely on the fact that the corresponding GNU and
17244          DWARF constants are the same.  */
17245       switch (macinfo_type)
17246         {
17247           /* A zero macinfo type indicates the end of the macro
17248              information.  */
17249         case 0:
17250           break;
17251
17252         case DW_MACRO_GNU_define:
17253         case DW_MACRO_GNU_undef:
17254         case DW_MACRO_GNU_define_indirect:
17255         case DW_MACRO_GNU_undef_indirect:
17256           {
17257             unsigned int bytes_read;
17258             int line;
17259             char *body;
17260             int is_define;
17261
17262             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17263             mac_ptr += bytes_read;
17264
17265             if (macinfo_type == DW_MACRO_GNU_define
17266                 || macinfo_type == DW_MACRO_GNU_undef)
17267               {
17268                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
17269                 mac_ptr += bytes_read;
17270               }
17271             else
17272               {
17273                 LONGEST str_offset;
17274
17275                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
17276                 mac_ptr += offset_size;
17277
17278                 body = read_indirect_string_at_offset (abfd, str_offset);
17279               }
17280
17281             is_define = (macinfo_type == DW_MACRO_GNU_define
17282                          || macinfo_type == DW_MACRO_GNU_define_indirect);
17283             if (! current_file)
17284               {
17285                 /* DWARF violation as no main source is present.  */
17286                 complaint (&symfile_complaints,
17287                            _("debug info with no main source gives macro %s "
17288                              "on line %d: %s"),
17289                            is_define ? _("definition") : _("undefinition"),
17290                            line, body);
17291                 break;
17292               }
17293             if ((line == 0 && !at_commandline)
17294                 || (line != 0 && at_commandline))
17295               complaint (&symfile_complaints,
17296                          _("debug info gives %s macro %s with %s line %d: %s"),
17297                          at_commandline ? _("command-line") : _("in-file"),
17298                          is_define ? _("definition") : _("undefinition"),
17299                          line == 0 ? _("zero") : _("non-zero"), line, body);
17300
17301             if (is_define)
17302               parse_macro_definition (current_file, line, body);
17303             else
17304               {
17305                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
17306                             || macinfo_type == DW_MACRO_GNU_undef_indirect);
17307                 macro_undef (current_file, line, body);
17308               }
17309           }
17310           break;
17311
17312         case DW_MACRO_GNU_start_file:
17313           {
17314             unsigned int bytes_read;
17315             int line, file;
17316
17317             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17318             mac_ptr += bytes_read;
17319             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17320             mac_ptr += bytes_read;
17321
17322             if ((line == 0 && !at_commandline)
17323                 || (line != 0 && at_commandline))
17324               complaint (&symfile_complaints,
17325                          _("debug info gives source %d included "
17326                            "from %s at %s line %d"),
17327                          file, at_commandline ? _("command-line") : _("file"),
17328                          line == 0 ? _("zero") : _("non-zero"), line);
17329
17330             if (at_commandline)
17331               {
17332                 /* This DW_MACRO_GNU_start_file was executed in the
17333                    pass one.  */
17334                 at_commandline = 0;
17335               }
17336             else
17337               current_file = macro_start_file (file, line,
17338                                                current_file, comp_dir,
17339                                                lh, objfile);
17340           }
17341           break;
17342
17343         case DW_MACRO_GNU_end_file:
17344           if (! current_file)
17345             complaint (&symfile_complaints,
17346                        _("macro debug info has an unmatched "
17347                          "`close_file' directive"));
17348           else
17349             {
17350               current_file = current_file->included_by;
17351               if (! current_file)
17352                 {
17353                   enum dwarf_macro_record_type next_type;
17354
17355                   /* GCC circa March 2002 doesn't produce the zero
17356                      type byte marking the end of the compilation
17357                      unit.  Complain if it's not there, but exit no
17358                      matter what.  */
17359
17360                   /* Do we at least have room for a macinfo type byte?  */
17361                   if (mac_ptr >= mac_end)
17362                     {
17363                       dwarf2_section_buffer_overflow_complaint (section);
17364                       return;
17365                     }
17366
17367                   /* We don't increment mac_ptr here, so this is just
17368                      a look-ahead.  */
17369                   next_type = read_1_byte (abfd, mac_ptr);
17370                   if (next_type != 0)
17371                     complaint (&symfile_complaints,
17372                                _("no terminating 0-type entry for "
17373                                  "macros in `.debug_macinfo' section"));
17374
17375                   return;
17376                 }
17377             }
17378           break;
17379
17380         case DW_MACRO_GNU_transparent_include:
17381           {
17382             LONGEST offset;
17383             void **slot;
17384
17385             offset = read_offset_1 (abfd, mac_ptr, offset_size);
17386             mac_ptr += offset_size;
17387
17388             slot = htab_find_slot (include_hash, mac_ptr, INSERT);
17389             if (*slot != NULL)
17390               {
17391                 /* This has actually happened; see
17392                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
17393                 complaint (&symfile_complaints,
17394                            _("recursive DW_MACRO_GNU_transparent_include in "
17395                              ".debug_macro section"));
17396               }
17397             else
17398               {
17399                 *slot = mac_ptr;
17400
17401                 dwarf_decode_macro_bytes (abfd,
17402                                           section->buffer + offset,
17403                                           mac_end, current_file,
17404                                           lh, comp_dir,
17405                                           section, section_is_gnu,
17406                                           offset_size, objfile, include_hash);
17407
17408                 htab_remove_elt (include_hash, mac_ptr);
17409               }
17410           }
17411           break;
17412
17413         case DW_MACINFO_vendor_ext:
17414           if (!section_is_gnu)
17415             {
17416               unsigned int bytes_read;
17417               int constant;
17418
17419               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17420               mac_ptr += bytes_read;
17421               read_direct_string (abfd, mac_ptr, &bytes_read);
17422               mac_ptr += bytes_read;
17423
17424               /* We don't recognize any vendor extensions.  */
17425               break;
17426             }
17427           /* FALLTHROUGH */
17428
17429         default:
17430           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
17431                                          mac_ptr, mac_end, abfd, offset_size,
17432                                          section);
17433           if (mac_ptr == NULL)
17434             return;
17435           break;
17436         }
17437     } while (macinfo_type != 0);
17438 }
17439
17440 static void
17441 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
17442                      char *comp_dir, int section_is_gnu)
17443 {
17444   struct objfile *objfile = dwarf2_per_objfile->objfile;
17445   struct line_header *lh = cu->line_header;
17446   bfd *abfd;
17447   gdb_byte *mac_ptr, *mac_end;
17448   struct macro_source_file *current_file = 0;
17449   enum dwarf_macro_record_type macinfo_type;
17450   unsigned int offset_size = cu->header.offset_size;
17451   gdb_byte *opcode_definitions[256];
17452   struct cleanup *cleanup;
17453   htab_t include_hash;
17454   void **slot;
17455   struct dwarf2_section_info *section;
17456   const char *section_name;
17457
17458   if (cu->dwo_unit != NULL)
17459     {
17460       if (section_is_gnu)
17461         {
17462           section = &cu->dwo_unit->dwo_file->sections.macro;
17463           section_name = ".debug_macro.dwo";
17464         }
17465       else
17466         {
17467           section = &cu->dwo_unit->dwo_file->sections.macinfo;
17468           section_name = ".debug_macinfo.dwo";
17469         }
17470     }
17471   else
17472     {
17473       if (section_is_gnu)
17474         {
17475           section = &dwarf2_per_objfile->macro;
17476           section_name = ".debug_macro";
17477         }
17478       else
17479         {
17480           section = &dwarf2_per_objfile->macinfo;
17481           section_name = ".debug_macinfo";
17482         }
17483     }
17484
17485   dwarf2_read_section (objfile, section);
17486   if (section->buffer == NULL)
17487     {
17488       complaint (&symfile_complaints, _("missing %s section"), section_name);
17489       return;
17490     }
17491   abfd = section->asection->owner;
17492
17493   /* First pass: Find the name of the base filename.
17494      This filename is needed in order to process all macros whose definition
17495      (or undefinition) comes from the command line.  These macros are defined
17496      before the first DW_MACINFO_start_file entry, and yet still need to be
17497      associated to the base file.
17498
17499      To determine the base file name, we scan the macro definitions until we
17500      reach the first DW_MACINFO_start_file entry.  We then initialize
17501      CURRENT_FILE accordingly so that any macro definition found before the
17502      first DW_MACINFO_start_file can still be associated to the base file.  */
17503
17504   mac_ptr = section->buffer + offset;
17505   mac_end = section->buffer + section->size;
17506
17507   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
17508                                       &offset_size, section_is_gnu);
17509   if (mac_ptr == NULL)
17510     {
17511       /* We already issued a complaint.  */
17512       return;
17513     }
17514
17515   do
17516     {
17517       /* Do we at least have room for a macinfo type byte?  */
17518       if (mac_ptr >= mac_end)
17519         {
17520           /* Complaint is printed during the second pass as GDB will probably
17521              stop the first pass earlier upon finding
17522              DW_MACINFO_start_file.  */
17523           break;
17524         }
17525
17526       macinfo_type = read_1_byte (abfd, mac_ptr);
17527       mac_ptr++;
17528
17529       /* Note that we rely on the fact that the corresponding GNU and
17530          DWARF constants are the same.  */
17531       switch (macinfo_type)
17532         {
17533           /* A zero macinfo type indicates the end of the macro
17534              information.  */
17535         case 0:
17536           break;
17537
17538         case DW_MACRO_GNU_define:
17539         case DW_MACRO_GNU_undef:
17540           /* Only skip the data by MAC_PTR.  */
17541           {
17542             unsigned int bytes_read;
17543
17544             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17545             mac_ptr += bytes_read;
17546             read_direct_string (abfd, mac_ptr, &bytes_read);
17547             mac_ptr += bytes_read;
17548           }
17549           break;
17550
17551         case DW_MACRO_GNU_start_file:
17552           {
17553             unsigned int bytes_read;
17554             int line, file;
17555
17556             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17557             mac_ptr += bytes_read;
17558             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17559             mac_ptr += bytes_read;
17560
17561             current_file = macro_start_file (file, line, current_file,
17562                                              comp_dir, lh, objfile);
17563           }
17564           break;
17565
17566         case DW_MACRO_GNU_end_file:
17567           /* No data to skip by MAC_PTR.  */
17568           break;
17569
17570         case DW_MACRO_GNU_define_indirect:
17571         case DW_MACRO_GNU_undef_indirect:
17572           {
17573             unsigned int bytes_read;
17574
17575             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17576             mac_ptr += bytes_read;
17577             mac_ptr += offset_size;
17578           }
17579           break;
17580
17581         case DW_MACRO_GNU_transparent_include:
17582           /* Note that, according to the spec, a transparent include
17583              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
17584              skip this opcode.  */
17585           mac_ptr += offset_size;
17586           break;
17587
17588         case DW_MACINFO_vendor_ext:
17589           /* Only skip the data by MAC_PTR.  */
17590           if (!section_is_gnu)
17591             {
17592               unsigned int bytes_read;
17593
17594               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17595               mac_ptr += bytes_read;
17596               read_direct_string (abfd, mac_ptr, &bytes_read);
17597               mac_ptr += bytes_read;
17598             }
17599           /* FALLTHROUGH */
17600
17601         default:
17602           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
17603                                          mac_ptr, mac_end, abfd, offset_size,
17604                                          section);
17605           if (mac_ptr == NULL)
17606             return;
17607           break;
17608         }
17609     } while (macinfo_type != 0 && current_file == NULL);
17610
17611   /* Second pass: Process all entries.
17612
17613      Use the AT_COMMAND_LINE flag to determine whether we are still processing
17614      command-line macro definitions/undefinitions.  This flag is unset when we
17615      reach the first DW_MACINFO_start_file entry.  */
17616
17617   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
17618                                     NULL, xcalloc, xfree);
17619   cleanup = make_cleanup_htab_delete (include_hash);
17620   mac_ptr = section->buffer + offset;
17621   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
17622   *slot = mac_ptr;
17623   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
17624                             current_file, lh, comp_dir, section, section_is_gnu,
17625                             offset_size, objfile, include_hash);
17626   do_cleanups (cleanup);
17627 }
17628
17629 /* Check if the attribute's form is a DW_FORM_block*
17630    if so return true else false.  */
17631
17632 static int
17633 attr_form_is_block (struct attribute *attr)
17634 {
17635   return (attr == NULL ? 0 :
17636       attr->form == DW_FORM_block1
17637       || attr->form == DW_FORM_block2
17638       || attr->form == DW_FORM_block4
17639       || attr->form == DW_FORM_block
17640       || attr->form == DW_FORM_exprloc);
17641 }
17642
17643 /* Return non-zero if ATTR's value is a section offset --- classes
17644    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
17645    You may use DW_UNSND (attr) to retrieve such offsets.
17646
17647    Section 7.5.4, "Attribute Encodings", explains that no attribute
17648    may have a value that belongs to more than one of these classes; it
17649    would be ambiguous if we did, because we use the same forms for all
17650    of them.  */
17651
17652 static int
17653 attr_form_is_section_offset (struct attribute *attr)
17654 {
17655   return (attr->form == DW_FORM_data4
17656           || attr->form == DW_FORM_data8
17657           || attr->form == DW_FORM_sec_offset);
17658 }
17659
17660 /* Return non-zero if ATTR's value falls in the 'constant' class, or
17661    zero otherwise.  When this function returns true, you can apply
17662    dwarf2_get_attr_constant_value to it.
17663
17664    However, note that for some attributes you must check
17665    attr_form_is_section_offset before using this test.  DW_FORM_data4
17666    and DW_FORM_data8 are members of both the constant class, and of
17667    the classes that contain offsets into other debug sections
17668    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
17669    that, if an attribute's can be either a constant or one of the
17670    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
17671    taken as section offsets, not constants.  */
17672
17673 static int
17674 attr_form_is_constant (struct attribute *attr)
17675 {
17676   switch (attr->form)
17677     {
17678     case DW_FORM_sdata:
17679     case DW_FORM_udata:
17680     case DW_FORM_data1:
17681     case DW_FORM_data2:
17682     case DW_FORM_data4:
17683     case DW_FORM_data8:
17684       return 1;
17685     default:
17686       return 0;
17687     }
17688 }
17689
17690 /* Return the .debug_loc section to use for CU.
17691    For DWO files use .debug_loc.dwo.  */
17692
17693 static struct dwarf2_section_info *
17694 cu_debug_loc_section (struct dwarf2_cu *cu)
17695 {
17696   if (cu->dwo_unit)
17697     return &cu->dwo_unit->dwo_file->sections.loc;
17698   return &dwarf2_per_objfile->loc;
17699 }
17700
17701 /* A helper function that fills in a dwarf2_loclist_baton.  */
17702
17703 static void
17704 fill_in_loclist_baton (struct dwarf2_cu *cu,
17705                        struct dwarf2_loclist_baton *baton,
17706                        struct attribute *attr)
17707 {
17708   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
17709
17710   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17711
17712   baton->per_cu = cu->per_cu;
17713   gdb_assert (baton->per_cu);
17714   /* We don't know how long the location list is, but make sure we
17715      don't run off the edge of the section.  */
17716   baton->size = section->size - DW_UNSND (attr);
17717   baton->data = section->buffer + DW_UNSND (attr);
17718   baton->base_address = cu->base_address;
17719   baton->from_dwo = cu->dwo_unit != NULL;
17720 }
17721
17722 static void
17723 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
17724                              struct dwarf2_cu *cu)
17725 {
17726   struct objfile *objfile = dwarf2_per_objfile->objfile;
17727   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
17728
17729   if (attr_form_is_section_offset (attr)
17730       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
17731          the section.  If so, fall through to the complaint in the
17732          other branch.  */
17733       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
17734     {
17735       struct dwarf2_loclist_baton *baton;
17736
17737       baton = obstack_alloc (&objfile->objfile_obstack,
17738                              sizeof (struct dwarf2_loclist_baton));
17739
17740       fill_in_loclist_baton (cu, baton, attr);
17741
17742       if (cu->base_known == 0)
17743         complaint (&symfile_complaints,
17744                    _("Location list used without "
17745                      "specifying the CU base address."));
17746
17747       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
17748       SYMBOL_LOCATION_BATON (sym) = baton;
17749     }
17750   else
17751     {
17752       struct dwarf2_locexpr_baton *baton;
17753
17754       baton = obstack_alloc (&objfile->objfile_obstack,
17755                              sizeof (struct dwarf2_locexpr_baton));
17756       baton->per_cu = cu->per_cu;
17757       gdb_assert (baton->per_cu);
17758
17759       if (attr_form_is_block (attr))
17760         {
17761           /* Note that we're just copying the block's data pointer
17762              here, not the actual data.  We're still pointing into the
17763              info_buffer for SYM's objfile; right now we never release
17764              that buffer, but when we do clean up properly this may
17765              need to change.  */
17766           baton->size = DW_BLOCK (attr)->size;
17767           baton->data = DW_BLOCK (attr)->data;
17768         }
17769       else
17770         {
17771           dwarf2_invalid_attrib_class_complaint ("location description",
17772                                                  SYMBOL_NATURAL_NAME (sym));
17773           baton->size = 0;
17774         }
17775
17776       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
17777       SYMBOL_LOCATION_BATON (sym) = baton;
17778     }
17779 }
17780
17781 /* Return the OBJFILE associated with the compilation unit CU.  If CU
17782    came from a separate debuginfo file, then the master objfile is
17783    returned.  */
17784
17785 struct objfile *
17786 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
17787 {
17788   struct objfile *objfile = per_cu->objfile;
17789
17790   /* Return the master objfile, so that we can report and look up the
17791      correct file containing this variable.  */
17792   if (objfile->separate_debug_objfile_backlink)
17793     objfile = objfile->separate_debug_objfile_backlink;
17794
17795   return objfile;
17796 }
17797
17798 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
17799    (CU_HEADERP is unused in such case) or prepare a temporary copy at
17800    CU_HEADERP first.  */
17801
17802 static const struct comp_unit_head *
17803 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
17804                        struct dwarf2_per_cu_data *per_cu)
17805 {
17806   gdb_byte *info_ptr;
17807
17808   if (per_cu->cu)
17809     return &per_cu->cu->header;
17810
17811   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
17812
17813   memset (cu_headerp, 0, sizeof (*cu_headerp));
17814   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
17815
17816   return cu_headerp;
17817 }
17818
17819 /* Return the address size given in the compilation unit header for CU.  */
17820
17821 int
17822 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
17823 {
17824   struct comp_unit_head cu_header_local;
17825   const struct comp_unit_head *cu_headerp;
17826
17827   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
17828
17829   return cu_headerp->addr_size;
17830 }
17831
17832 /* Return the offset size given in the compilation unit header for CU.  */
17833
17834 int
17835 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
17836 {
17837   struct comp_unit_head cu_header_local;
17838   const struct comp_unit_head *cu_headerp;
17839
17840   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
17841
17842   return cu_headerp->offset_size;
17843 }
17844
17845 /* See its dwarf2loc.h declaration.  */
17846
17847 int
17848 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
17849 {
17850   struct comp_unit_head cu_header_local;
17851   const struct comp_unit_head *cu_headerp;
17852
17853   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
17854
17855   if (cu_headerp->version == 2)
17856     return cu_headerp->addr_size;
17857   else
17858     return cu_headerp->offset_size;
17859 }
17860
17861 /* Return the text offset of the CU.  The returned offset comes from
17862    this CU's objfile.  If this objfile came from a separate debuginfo
17863    file, then the offset may be different from the corresponding
17864    offset in the parent objfile.  */
17865
17866 CORE_ADDR
17867 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
17868 {
17869   struct objfile *objfile = per_cu->objfile;
17870
17871   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17872 }
17873
17874 /* Locate the .debug_info compilation unit from CU's objfile which contains
17875    the DIE at OFFSET.  Raises an error on failure.  */
17876
17877 static struct dwarf2_per_cu_data *
17878 dwarf2_find_containing_comp_unit (sect_offset offset,
17879                                   struct objfile *objfile)
17880 {
17881   struct dwarf2_per_cu_data *this_cu;
17882   int low, high;
17883
17884   low = 0;
17885   high = dwarf2_per_objfile->n_comp_units - 1;
17886   while (high > low)
17887     {
17888       int mid = low + (high - low) / 2;
17889
17890       if (dwarf2_per_objfile->all_comp_units[mid]->offset.sect_off
17891           >= offset.sect_off)
17892         high = mid;
17893       else
17894         low = mid + 1;
17895     }
17896   gdb_assert (low == high);
17897   if (dwarf2_per_objfile->all_comp_units[low]->offset.sect_off
17898       > offset.sect_off)
17899     {
17900       if (low == 0)
17901         error (_("Dwarf Error: could not find partial DIE containing "
17902                "offset 0x%lx [in module %s]"),
17903                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
17904
17905       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
17906                   <= offset.sect_off);
17907       return dwarf2_per_objfile->all_comp_units[low-1];
17908     }
17909   else
17910     {
17911       this_cu = dwarf2_per_objfile->all_comp_units[low];
17912       if (low == dwarf2_per_objfile->n_comp_units - 1
17913           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
17914         error (_("invalid dwarf2 offset %u"), offset.sect_off);
17915       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
17916       return this_cu;
17917     }
17918 }
17919
17920 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
17921
17922 static void
17923 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
17924 {
17925   memset (cu, 0, sizeof (*cu));
17926   per_cu->cu = cu;
17927   cu->per_cu = per_cu;
17928   cu->objfile = per_cu->objfile;
17929   obstack_init (&cu->comp_unit_obstack);
17930 }
17931
17932 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
17933
17934 static void
17935 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
17936                        enum language pretend_language)
17937 {
17938   struct attribute *attr;
17939
17940   /* Set the language we're debugging.  */
17941   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
17942   if (attr)
17943     set_cu_language (DW_UNSND (attr), cu);
17944   else
17945     {
17946       cu->language = pretend_language;
17947       cu->language_defn = language_def (cu->language);
17948     }
17949
17950   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
17951   if (attr)
17952     cu->producer = DW_STRING (attr);
17953 }
17954
17955 /* Release one cached compilation unit, CU.  We unlink it from the tree
17956    of compilation units, but we don't remove it from the read_in_chain;
17957    the caller is responsible for that.
17958    NOTE: DATA is a void * because this function is also used as a
17959    cleanup routine.  */
17960
17961 static void
17962 free_heap_comp_unit (void *data)
17963 {
17964   struct dwarf2_cu *cu = data;
17965
17966   gdb_assert (cu->per_cu != NULL);
17967   cu->per_cu->cu = NULL;
17968   cu->per_cu = NULL;
17969
17970   obstack_free (&cu->comp_unit_obstack, NULL);
17971
17972   xfree (cu);
17973 }
17974
17975 /* This cleanup function is passed the address of a dwarf2_cu on the stack
17976    when we're finished with it.  We can't free the pointer itself, but be
17977    sure to unlink it from the cache.  Also release any associated storage.  */
17978
17979 static void
17980 free_stack_comp_unit (void *data)
17981 {
17982   struct dwarf2_cu *cu = data;
17983
17984   gdb_assert (cu->per_cu != NULL);
17985   cu->per_cu->cu = NULL;
17986   cu->per_cu = NULL;
17987
17988   obstack_free (&cu->comp_unit_obstack, NULL);
17989   cu->partial_dies = NULL;
17990 }
17991
17992 /* Free all cached compilation units.  */
17993
17994 static void
17995 free_cached_comp_units (void *data)
17996 {
17997   struct dwarf2_per_cu_data *per_cu, **last_chain;
17998
17999   per_cu = dwarf2_per_objfile->read_in_chain;
18000   last_chain = &dwarf2_per_objfile->read_in_chain;
18001   while (per_cu != NULL)
18002     {
18003       struct dwarf2_per_cu_data *next_cu;
18004
18005       next_cu = per_cu->cu->read_in_chain;
18006
18007       free_heap_comp_unit (per_cu->cu);
18008       *last_chain = next_cu;
18009
18010       per_cu = next_cu;
18011     }
18012 }
18013
18014 /* Increase the age counter on each cached compilation unit, and free
18015    any that are too old.  */
18016
18017 static void
18018 age_cached_comp_units (void)
18019 {
18020   struct dwarf2_per_cu_data *per_cu, **last_chain;
18021
18022   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
18023   per_cu = dwarf2_per_objfile->read_in_chain;
18024   while (per_cu != NULL)
18025     {
18026       per_cu->cu->last_used ++;
18027       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
18028         dwarf2_mark (per_cu->cu);
18029       per_cu = per_cu->cu->read_in_chain;
18030     }
18031
18032   per_cu = dwarf2_per_objfile->read_in_chain;
18033   last_chain = &dwarf2_per_objfile->read_in_chain;
18034   while (per_cu != NULL)
18035     {
18036       struct dwarf2_per_cu_data *next_cu;
18037
18038       next_cu = per_cu->cu->read_in_chain;
18039
18040       if (!per_cu->cu->mark)
18041         {
18042           free_heap_comp_unit (per_cu->cu);
18043           *last_chain = next_cu;
18044         }
18045       else
18046         last_chain = &per_cu->cu->read_in_chain;
18047
18048       per_cu = next_cu;
18049     }
18050 }
18051
18052 /* Remove a single compilation unit from the cache.  */
18053
18054 static void
18055 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
18056 {
18057   struct dwarf2_per_cu_data *per_cu, **last_chain;
18058
18059   per_cu = dwarf2_per_objfile->read_in_chain;
18060   last_chain = &dwarf2_per_objfile->read_in_chain;
18061   while (per_cu != NULL)
18062     {
18063       struct dwarf2_per_cu_data *next_cu;
18064
18065       next_cu = per_cu->cu->read_in_chain;
18066
18067       if (per_cu == target_per_cu)
18068         {
18069           free_heap_comp_unit (per_cu->cu);
18070           per_cu->cu = NULL;
18071           *last_chain = next_cu;
18072           break;
18073         }
18074       else
18075         last_chain = &per_cu->cu->read_in_chain;
18076
18077       per_cu = next_cu;
18078     }
18079 }
18080
18081 /* Release all extra memory associated with OBJFILE.  */
18082
18083 void
18084 dwarf2_free_objfile (struct objfile *objfile)
18085 {
18086   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
18087
18088   if (dwarf2_per_objfile == NULL)
18089     return;
18090
18091   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
18092   free_cached_comp_units (NULL);
18093
18094   if (dwarf2_per_objfile->quick_file_names_table)
18095     htab_delete (dwarf2_per_objfile->quick_file_names_table);
18096
18097   /* Everything else should be on the objfile obstack.  */
18098 }
18099
18100 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
18101    We store these in a hash table separate from the DIEs, and preserve them
18102    when the DIEs are flushed out of cache.
18103
18104    The CU "per_cu" pointer is needed because offset alone is not enough to
18105    uniquely identify the type.  A file may have multiple .debug_types sections,
18106    or the type may come from a DWO file.  We have to use something in
18107    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
18108    routine, get_die_type_at_offset, from outside this file, and thus won't
18109    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
18110    of the objfile.  */
18111
18112 struct dwarf2_per_cu_offset_and_type
18113 {
18114   const struct dwarf2_per_cu_data *per_cu;
18115   sect_offset offset;
18116   struct type *type;
18117 };
18118
18119 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
18120
18121 static hashval_t
18122 per_cu_offset_and_type_hash (const void *item)
18123 {
18124   const struct dwarf2_per_cu_offset_and_type *ofs = item;
18125
18126   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
18127 }
18128
18129 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
18130
18131 static int
18132 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
18133 {
18134   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
18135   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
18136
18137   return (ofs_lhs->per_cu == ofs_rhs->per_cu
18138           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
18139 }
18140
18141 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
18142    table if necessary.  For convenience, return TYPE.
18143
18144    The DIEs reading must have careful ordering to:
18145     * Not cause infite loops trying to read in DIEs as a prerequisite for
18146       reading current DIE.
18147     * Not trying to dereference contents of still incompletely read in types
18148       while reading in other DIEs.
18149     * Enable referencing still incompletely read in types just by a pointer to
18150       the type without accessing its fields.
18151
18152    Therefore caller should follow these rules:
18153      * Try to fetch any prerequisite types we may need to build this DIE type
18154        before building the type and calling set_die_type.
18155      * After building type call set_die_type for current DIE as soon as
18156        possible before fetching more types to complete the current type.
18157      * Make the type as complete as possible before fetching more types.  */
18158
18159 static struct type *
18160 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
18161 {
18162   struct dwarf2_per_cu_offset_and_type **slot, ofs;
18163   struct objfile *objfile = cu->objfile;
18164
18165   /* For Ada types, make sure that the gnat-specific data is always
18166      initialized (if not already set).  There are a few types where
18167      we should not be doing so, because the type-specific area is
18168      already used to hold some other piece of info (eg: TYPE_CODE_FLT
18169      where the type-specific area is used to store the floatformat).
18170      But this is not a problem, because the gnat-specific information
18171      is actually not needed for these types.  */
18172   if (need_gnat_info (cu)
18173       && TYPE_CODE (type) != TYPE_CODE_FUNC
18174       && TYPE_CODE (type) != TYPE_CODE_FLT
18175       && !HAVE_GNAT_AUX_INFO (type))
18176     INIT_GNAT_SPECIFIC (type);
18177
18178   if (dwarf2_per_objfile->die_type_hash == NULL)
18179     {
18180       dwarf2_per_objfile->die_type_hash =
18181         htab_create_alloc_ex (127,
18182                               per_cu_offset_and_type_hash,
18183                               per_cu_offset_and_type_eq,
18184                               NULL,
18185                               &objfile->objfile_obstack,
18186                               hashtab_obstack_allocate,
18187                               dummy_obstack_deallocate);
18188     }
18189
18190   ofs.per_cu = cu->per_cu;
18191   ofs.offset = die->offset;
18192   ofs.type = type;
18193   slot = (struct dwarf2_per_cu_offset_and_type **)
18194     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
18195   if (*slot)
18196     complaint (&symfile_complaints,
18197                _("A problem internal to GDB: DIE 0x%x has type already set"),
18198                die->offset.sect_off);
18199   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
18200   **slot = ofs;
18201   return type;
18202 }
18203
18204 /* Look up the type for the die at OFFSET in the appropriate type_hash
18205    table, or return NULL if the die does not have a saved type.  */
18206
18207 static struct type *
18208 get_die_type_at_offset (sect_offset offset,
18209                         struct dwarf2_per_cu_data *per_cu)
18210 {
18211   struct dwarf2_per_cu_offset_and_type *slot, ofs;
18212
18213   if (dwarf2_per_objfile->die_type_hash == NULL)
18214     return NULL;
18215
18216   ofs.per_cu = per_cu;
18217   ofs.offset = offset;
18218   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
18219   if (slot)
18220     return slot->type;
18221   else
18222     return NULL;
18223 }
18224
18225 /* Look up the type for DIE in the appropriate type_hash table,
18226    or return NULL if DIE does not have a saved type.  */
18227
18228 static struct type *
18229 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
18230 {
18231   return get_die_type_at_offset (die->offset, cu->per_cu);
18232 }
18233
18234 /* Add a dependence relationship from CU to REF_PER_CU.  */
18235
18236 static void
18237 dwarf2_add_dependence (struct dwarf2_cu *cu,
18238                        struct dwarf2_per_cu_data *ref_per_cu)
18239 {
18240   void **slot;
18241
18242   if (cu->dependencies == NULL)
18243     cu->dependencies
18244       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
18245                               NULL, &cu->comp_unit_obstack,
18246                               hashtab_obstack_allocate,
18247                               dummy_obstack_deallocate);
18248
18249   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
18250   if (*slot == NULL)
18251     *slot = ref_per_cu;
18252 }
18253
18254 /* Subroutine of dwarf2_mark to pass to htab_traverse.
18255    Set the mark field in every compilation unit in the
18256    cache that we must keep because we are keeping CU.  */
18257
18258 static int
18259 dwarf2_mark_helper (void **slot, void *data)
18260 {
18261   struct dwarf2_per_cu_data *per_cu;
18262
18263   per_cu = (struct dwarf2_per_cu_data *) *slot;
18264
18265   /* cu->dependencies references may not yet have been ever read if QUIT aborts
18266      reading of the chain.  As such dependencies remain valid it is not much
18267      useful to track and undo them during QUIT cleanups.  */
18268   if (per_cu->cu == NULL)
18269     return 1;
18270
18271   if (per_cu->cu->mark)
18272     return 1;
18273   per_cu->cu->mark = 1;
18274
18275   if (per_cu->cu->dependencies != NULL)
18276     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
18277
18278   return 1;
18279 }
18280
18281 /* Set the mark field in CU and in every other compilation unit in the
18282    cache that we must keep because we are keeping CU.  */
18283
18284 static void
18285 dwarf2_mark (struct dwarf2_cu *cu)
18286 {
18287   if (cu->mark)
18288     return;
18289   cu->mark = 1;
18290   if (cu->dependencies != NULL)
18291     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
18292 }
18293
18294 static void
18295 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
18296 {
18297   while (per_cu)
18298     {
18299       per_cu->cu->mark = 0;
18300       per_cu = per_cu->cu->read_in_chain;
18301     }
18302 }
18303
18304 /* Trivial hash function for partial_die_info: the hash value of a DIE
18305    is its offset in .debug_info for this objfile.  */
18306
18307 static hashval_t
18308 partial_die_hash (const void *item)
18309 {
18310   const struct partial_die_info *part_die = item;
18311
18312   return part_die->offset.sect_off;
18313 }
18314
18315 /* Trivial comparison function for partial_die_info structures: two DIEs
18316    are equal if they have the same offset.  */
18317
18318 static int
18319 partial_die_eq (const void *item_lhs, const void *item_rhs)
18320 {
18321   const struct partial_die_info *part_die_lhs = item_lhs;
18322   const struct partial_die_info *part_die_rhs = item_rhs;
18323
18324   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
18325 }
18326
18327 static struct cmd_list_element *set_dwarf2_cmdlist;
18328 static struct cmd_list_element *show_dwarf2_cmdlist;
18329
18330 static void
18331 set_dwarf2_cmd (char *args, int from_tty)
18332 {
18333   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
18334 }
18335
18336 static void
18337 show_dwarf2_cmd (char *args, int from_tty)
18338 {
18339   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
18340 }
18341
18342 /* If section described by INFO was mmapped, munmap it now.  */
18343
18344 static void
18345 munmap_section_buffer (struct dwarf2_section_info *info)
18346 {
18347   if (info->map_addr != NULL)
18348     {
18349 #ifdef HAVE_MMAP
18350       int res;
18351
18352       res = munmap (info->map_addr, info->map_len);
18353       gdb_assert (res == 0);
18354 #else
18355       /* Without HAVE_MMAP, we should never be here to begin with.  */
18356       gdb_assert_not_reached ("no mmap support");
18357 #endif
18358     }
18359 }
18360
18361 /* munmap debug sections for OBJFILE, if necessary.  */
18362
18363 static void
18364 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
18365 {
18366   struct dwarf2_per_objfile *data = d;
18367   int ix;
18368   struct dwarf2_section_info *section;
18369
18370   /* This is sorted according to the order they're defined in to make it easier
18371      to keep in sync.  */
18372   munmap_section_buffer (&data->info);
18373   munmap_section_buffer (&data->abbrev);
18374   munmap_section_buffer (&data->line);
18375   munmap_section_buffer (&data->loc);
18376   munmap_section_buffer (&data->macinfo);
18377   munmap_section_buffer (&data->macro);
18378   munmap_section_buffer (&data->str);
18379   munmap_section_buffer (&data->ranges);
18380   munmap_section_buffer (&data->addr);
18381   munmap_section_buffer (&data->frame);
18382   munmap_section_buffer (&data->eh_frame);
18383   munmap_section_buffer (&data->gdb_index);
18384
18385   for (ix = 0;
18386        VEC_iterate (dwarf2_section_info_def, data->types, ix, section);
18387        ++ix)
18388     munmap_section_buffer (section);
18389
18390   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
18391     VEC_free (dwarf2_per_cu_ptr,
18392               dwarf2_per_objfile->all_comp_units[ix]->s.imported_symtabs);
18393
18394   VEC_free (dwarf2_section_info_def, data->types);
18395
18396   if (data->dwo_files)
18397     free_dwo_files (data->dwo_files, objfile);
18398 }
18399
18400 \f
18401 /* The "save gdb-index" command.  */
18402
18403 /* The contents of the hash table we create when building the string
18404    table.  */
18405 struct strtab_entry
18406 {
18407   offset_type offset;
18408   const char *str;
18409 };
18410
18411 /* Hash function for a strtab_entry.
18412
18413    Function is used only during write_hash_table so no index format backward
18414    compatibility is needed.  */
18415
18416 static hashval_t
18417 hash_strtab_entry (const void *e)
18418 {
18419   const struct strtab_entry *entry = e;
18420   return mapped_index_string_hash (INT_MAX, entry->str);
18421 }
18422
18423 /* Equality function for a strtab_entry.  */
18424
18425 static int
18426 eq_strtab_entry (const void *a, const void *b)
18427 {
18428   const struct strtab_entry *ea = a;
18429   const struct strtab_entry *eb = b;
18430   return !strcmp (ea->str, eb->str);
18431 }
18432
18433 /* Create a strtab_entry hash table.  */
18434
18435 static htab_t
18436 create_strtab (void)
18437 {
18438   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
18439                             xfree, xcalloc, xfree);
18440 }
18441
18442 /* Add a string to the constant pool.  Return the string's offset in
18443    host order.  */
18444
18445 static offset_type
18446 add_string (htab_t table, struct obstack *cpool, const char *str)
18447 {
18448   void **slot;
18449   struct strtab_entry entry;
18450   struct strtab_entry *result;
18451
18452   entry.str = str;
18453   slot = htab_find_slot (table, &entry, INSERT);
18454   if (*slot)
18455     result = *slot;
18456   else
18457     {
18458       result = XNEW (struct strtab_entry);
18459       result->offset = obstack_object_size (cpool);
18460       result->str = str;
18461       obstack_grow_str0 (cpool, str);
18462       *slot = result;
18463     }
18464   return result->offset;
18465 }
18466
18467 /* An entry in the symbol table.  */
18468 struct symtab_index_entry
18469 {
18470   /* The name of the symbol.  */
18471   const char *name;
18472   /* The offset of the name in the constant pool.  */
18473   offset_type index_offset;
18474   /* A sorted vector of the indices of all the CUs that hold an object
18475      of this name.  */
18476   VEC (offset_type) *cu_indices;
18477 };
18478
18479 /* The symbol table.  This is a power-of-2-sized hash table.  */
18480 struct mapped_symtab
18481 {
18482   offset_type n_elements;
18483   offset_type size;
18484   struct symtab_index_entry **data;
18485 };
18486
18487 /* Hash function for a symtab_index_entry.  */
18488
18489 static hashval_t
18490 hash_symtab_entry (const void *e)
18491 {
18492   const struct symtab_index_entry *entry = e;
18493   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
18494                          sizeof (offset_type) * VEC_length (offset_type,
18495                                                             entry->cu_indices),
18496                          0);
18497 }
18498
18499 /* Equality function for a symtab_index_entry.  */
18500
18501 static int
18502 eq_symtab_entry (const void *a, const void *b)
18503 {
18504   const struct symtab_index_entry *ea = a;
18505   const struct symtab_index_entry *eb = b;
18506   int len = VEC_length (offset_type, ea->cu_indices);
18507   if (len != VEC_length (offset_type, eb->cu_indices))
18508     return 0;
18509   return !memcmp (VEC_address (offset_type, ea->cu_indices),
18510                   VEC_address (offset_type, eb->cu_indices),
18511                   sizeof (offset_type) * len);
18512 }
18513
18514 /* Destroy a symtab_index_entry.  */
18515
18516 static void
18517 delete_symtab_entry (void *p)
18518 {
18519   struct symtab_index_entry *entry = p;
18520   VEC_free (offset_type, entry->cu_indices);
18521   xfree (entry);
18522 }
18523
18524 /* Create a hash table holding symtab_index_entry objects.  */
18525
18526 static htab_t
18527 create_symbol_hash_table (void)
18528 {
18529   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
18530                             delete_symtab_entry, xcalloc, xfree);
18531 }
18532
18533 /* Create a new mapped symtab object.  */
18534
18535 static struct mapped_symtab *
18536 create_mapped_symtab (void)
18537 {
18538   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
18539   symtab->n_elements = 0;
18540   symtab->size = 1024;
18541   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
18542   return symtab;
18543 }
18544
18545 /* Destroy a mapped_symtab.  */
18546
18547 static void
18548 cleanup_mapped_symtab (void *p)
18549 {
18550   struct mapped_symtab *symtab = p;
18551   /* The contents of the array are freed when the other hash table is
18552      destroyed.  */
18553   xfree (symtab->data);
18554   xfree (symtab);
18555 }
18556
18557 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
18558    the slot.
18559    
18560    Function is used only during write_hash_table so no index format backward
18561    compatibility is needed.  */
18562
18563 static struct symtab_index_entry **
18564 find_slot (struct mapped_symtab *symtab, const char *name)
18565 {
18566   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
18567
18568   index = hash & (symtab->size - 1);
18569   step = ((hash * 17) & (symtab->size - 1)) | 1;
18570
18571   for (;;)
18572     {
18573       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
18574         return &symtab->data[index];
18575       index = (index + step) & (symtab->size - 1);
18576     }
18577 }
18578
18579 /* Expand SYMTAB's hash table.  */
18580
18581 static void
18582 hash_expand (struct mapped_symtab *symtab)
18583 {
18584   offset_type old_size = symtab->size;
18585   offset_type i;
18586   struct symtab_index_entry **old_entries = symtab->data;
18587
18588   symtab->size *= 2;
18589   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
18590
18591   for (i = 0; i < old_size; ++i)
18592     {
18593       if (old_entries[i])
18594         {
18595           struct symtab_index_entry **slot = find_slot (symtab,
18596                                                         old_entries[i]->name);
18597           *slot = old_entries[i];
18598         }
18599     }
18600
18601   xfree (old_entries);
18602 }
18603
18604 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
18605    CU_INDEX is the index of the CU in which the symbol appears.
18606    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
18607
18608 static void
18609 add_index_entry (struct mapped_symtab *symtab, const char *name,
18610                  int is_static, gdb_index_symbol_kind kind,
18611                  offset_type cu_index)
18612 {
18613   struct symtab_index_entry **slot;
18614   offset_type cu_index_and_attrs;
18615
18616   ++symtab->n_elements;
18617   if (4 * symtab->n_elements / 3 >= symtab->size)
18618     hash_expand (symtab);
18619
18620   slot = find_slot (symtab, name);
18621   if (!*slot)
18622     {
18623       *slot = XNEW (struct symtab_index_entry);
18624       (*slot)->name = name;
18625       /* index_offset is set later.  */
18626       (*slot)->cu_indices = NULL;
18627     }
18628
18629   cu_index_and_attrs = 0;
18630   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
18631   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
18632   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
18633
18634   /* We don't want to record an index value twice as we want to avoid the
18635      duplication.
18636      We process all global symbols and then all static symbols
18637      (which would allow us to avoid the duplication by only having to check
18638      the last entry pushed), but a symbol could have multiple kinds in one CU.
18639      To keep things simple we don't worry about the duplication here and
18640      sort and uniqufy the list after we've processed all symbols.  */
18641   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
18642 }
18643
18644 /* qsort helper routine for uniquify_cu_indices.  */
18645
18646 static int
18647 offset_type_compare (const void *ap, const void *bp)
18648 {
18649   offset_type a = *(offset_type *) ap;
18650   offset_type b = *(offset_type *) bp;
18651
18652   return (a > b) - (b > a);
18653 }
18654
18655 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
18656
18657 static void
18658 uniquify_cu_indices (struct mapped_symtab *symtab)
18659 {
18660   int i;
18661
18662   for (i = 0; i < symtab->size; ++i)
18663     {
18664       struct symtab_index_entry *entry = symtab->data[i];
18665
18666       if (entry
18667           && entry->cu_indices != NULL)
18668         {
18669           unsigned int next_to_insert, next_to_check;
18670           offset_type last_value;
18671
18672           qsort (VEC_address (offset_type, entry->cu_indices),
18673                  VEC_length (offset_type, entry->cu_indices),
18674                  sizeof (offset_type), offset_type_compare);
18675
18676           last_value = VEC_index (offset_type, entry->cu_indices, 0);
18677           next_to_insert = 1;
18678           for (next_to_check = 1;
18679                next_to_check < VEC_length (offset_type, entry->cu_indices);
18680                ++next_to_check)
18681             {
18682               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
18683                   != last_value)
18684                 {
18685                   last_value = VEC_index (offset_type, entry->cu_indices,
18686                                           next_to_check);
18687                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
18688                                last_value);
18689                   ++next_to_insert;
18690                 }
18691             }
18692           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
18693         }
18694     }
18695 }
18696
18697 /* Add a vector of indices to the constant pool.  */
18698
18699 static offset_type
18700 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
18701                       struct symtab_index_entry *entry)
18702 {
18703   void **slot;
18704
18705   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
18706   if (!*slot)
18707     {
18708       offset_type len = VEC_length (offset_type, entry->cu_indices);
18709       offset_type val = MAYBE_SWAP (len);
18710       offset_type iter;
18711       int i;
18712
18713       *slot = entry;
18714       entry->index_offset = obstack_object_size (cpool);
18715
18716       obstack_grow (cpool, &val, sizeof (val));
18717       for (i = 0;
18718            VEC_iterate (offset_type, entry->cu_indices, i, iter);
18719            ++i)
18720         {
18721           val = MAYBE_SWAP (iter);
18722           obstack_grow (cpool, &val, sizeof (val));
18723         }
18724     }
18725   else
18726     {
18727       struct symtab_index_entry *old_entry = *slot;
18728       entry->index_offset = old_entry->index_offset;
18729       entry = old_entry;
18730     }
18731   return entry->index_offset;
18732 }
18733
18734 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
18735    constant pool entries going into the obstack CPOOL.  */
18736
18737 static void
18738 write_hash_table (struct mapped_symtab *symtab,
18739                   struct obstack *output, struct obstack *cpool)
18740 {
18741   offset_type i;
18742   htab_t symbol_hash_table;
18743   htab_t str_table;
18744
18745   symbol_hash_table = create_symbol_hash_table ();
18746   str_table = create_strtab ();
18747
18748   /* We add all the index vectors to the constant pool first, to
18749      ensure alignment is ok.  */
18750   for (i = 0; i < symtab->size; ++i)
18751     {
18752       if (symtab->data[i])
18753         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
18754     }
18755
18756   /* Now write out the hash table.  */
18757   for (i = 0; i < symtab->size; ++i)
18758     {
18759       offset_type str_off, vec_off;
18760
18761       if (symtab->data[i])
18762         {
18763           str_off = add_string (str_table, cpool, symtab->data[i]->name);
18764           vec_off = symtab->data[i]->index_offset;
18765         }
18766       else
18767         {
18768           /* While 0 is a valid constant pool index, it is not valid
18769              to have 0 for both offsets.  */
18770           str_off = 0;
18771           vec_off = 0;
18772         }
18773
18774       str_off = MAYBE_SWAP (str_off);
18775       vec_off = MAYBE_SWAP (vec_off);
18776
18777       obstack_grow (output, &str_off, sizeof (str_off));
18778       obstack_grow (output, &vec_off, sizeof (vec_off));
18779     }
18780
18781   htab_delete (str_table);
18782   htab_delete (symbol_hash_table);
18783 }
18784
18785 /* Struct to map psymtab to CU index in the index file.  */
18786 struct psymtab_cu_index_map
18787 {
18788   struct partial_symtab *psymtab;
18789   unsigned int cu_index;
18790 };
18791
18792 static hashval_t
18793 hash_psymtab_cu_index (const void *item)
18794 {
18795   const struct psymtab_cu_index_map *map = item;
18796
18797   return htab_hash_pointer (map->psymtab);
18798 }
18799
18800 static int
18801 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
18802 {
18803   const struct psymtab_cu_index_map *lhs = item_lhs;
18804   const struct psymtab_cu_index_map *rhs = item_rhs;
18805
18806   return lhs->psymtab == rhs->psymtab;
18807 }
18808
18809 /* Helper struct for building the address table.  */
18810 struct addrmap_index_data
18811 {
18812   struct objfile *objfile;
18813   struct obstack *addr_obstack;
18814   htab_t cu_index_htab;
18815
18816   /* Non-zero if the previous_* fields are valid.
18817      We can't write an entry until we see the next entry (since it is only then
18818      that we know the end of the entry).  */
18819   int previous_valid;
18820   /* Index of the CU in the table of all CUs in the index file.  */
18821   unsigned int previous_cu_index;
18822   /* Start address of the CU.  */
18823   CORE_ADDR previous_cu_start;
18824 };
18825
18826 /* Write an address entry to OBSTACK.  */
18827
18828 static void
18829 add_address_entry (struct objfile *objfile, struct obstack *obstack,
18830                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
18831 {
18832   offset_type cu_index_to_write;
18833   char addr[8];
18834   CORE_ADDR baseaddr;
18835
18836   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18837
18838   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
18839   obstack_grow (obstack, addr, 8);
18840   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
18841   obstack_grow (obstack, addr, 8);
18842   cu_index_to_write = MAYBE_SWAP (cu_index);
18843   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
18844 }
18845
18846 /* Worker function for traversing an addrmap to build the address table.  */
18847
18848 static int
18849 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
18850 {
18851   struct addrmap_index_data *data = datap;
18852   struct partial_symtab *pst = obj;
18853
18854   if (data->previous_valid)
18855     add_address_entry (data->objfile, data->addr_obstack,
18856                        data->previous_cu_start, start_addr,
18857                        data->previous_cu_index);
18858
18859   data->previous_cu_start = start_addr;
18860   if (pst != NULL)
18861     {
18862       struct psymtab_cu_index_map find_map, *map;
18863       find_map.psymtab = pst;
18864       map = htab_find (data->cu_index_htab, &find_map);
18865       gdb_assert (map != NULL);
18866       data->previous_cu_index = map->cu_index;
18867       data->previous_valid = 1;
18868     }
18869   else
18870       data->previous_valid = 0;
18871
18872   return 0;
18873 }
18874
18875 /* Write OBJFILE's address map to OBSTACK.
18876    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
18877    in the index file.  */
18878
18879 static void
18880 write_address_map (struct objfile *objfile, struct obstack *obstack,
18881                    htab_t cu_index_htab)
18882 {
18883   struct addrmap_index_data addrmap_index_data;
18884
18885   /* When writing the address table, we have to cope with the fact that
18886      the addrmap iterator only provides the start of a region; we have to
18887      wait until the next invocation to get the start of the next region.  */
18888
18889   addrmap_index_data.objfile = objfile;
18890   addrmap_index_data.addr_obstack = obstack;
18891   addrmap_index_data.cu_index_htab = cu_index_htab;
18892   addrmap_index_data.previous_valid = 0;
18893
18894   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
18895                    &addrmap_index_data);
18896
18897   /* It's highly unlikely the last entry (end address = 0xff...ff)
18898      is valid, but we should still handle it.
18899      The end address is recorded as the start of the next region, but that
18900      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
18901      anyway.  */
18902   if (addrmap_index_data.previous_valid)
18903     add_address_entry (objfile, obstack,
18904                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
18905                        addrmap_index_data.previous_cu_index);
18906 }
18907
18908 /* Return the symbol kind of PSYM.  */
18909
18910 static gdb_index_symbol_kind
18911 symbol_kind (struct partial_symbol *psym)
18912 {
18913   domain_enum domain = PSYMBOL_DOMAIN (psym);
18914   enum address_class aclass = PSYMBOL_CLASS (psym);
18915
18916   switch (domain)
18917     {
18918     case VAR_DOMAIN:
18919       switch (aclass)
18920         {
18921         case LOC_BLOCK:
18922           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
18923         case LOC_TYPEDEF:
18924           return GDB_INDEX_SYMBOL_KIND_TYPE;
18925         case LOC_COMPUTED:
18926         case LOC_CONST_BYTES:
18927         case LOC_OPTIMIZED_OUT:
18928         case LOC_STATIC:
18929           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
18930         case LOC_CONST:
18931           /* Note: It's currently impossible to recognize psyms as enum values
18932              short of reading the type info.  For now punt.  */
18933           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
18934         default:
18935           /* There are other LOC_FOO values that one might want to classify
18936              as variables, but dwarf2read.c doesn't currently use them.  */
18937           return GDB_INDEX_SYMBOL_KIND_OTHER;
18938         }
18939     case STRUCT_DOMAIN:
18940       return GDB_INDEX_SYMBOL_KIND_TYPE;
18941     default:
18942       return GDB_INDEX_SYMBOL_KIND_OTHER;
18943     }
18944 }
18945
18946 /* Add a list of partial symbols to SYMTAB.  */
18947
18948 static void
18949 write_psymbols (struct mapped_symtab *symtab,
18950                 htab_t psyms_seen,
18951                 struct partial_symbol **psymp,
18952                 int count,
18953                 offset_type cu_index,
18954                 int is_static)
18955 {
18956   for (; count-- > 0; ++psymp)
18957     {
18958       struct partial_symbol *psym = *psymp;
18959       void **slot;
18960
18961       if (SYMBOL_LANGUAGE (psym) == language_ada)
18962         error (_("Ada is not currently supported by the index"));
18963
18964       /* Only add a given psymbol once.  */
18965       slot = htab_find_slot (psyms_seen, psym, INSERT);
18966       if (!*slot)
18967         {
18968           gdb_index_symbol_kind kind = symbol_kind (psym);
18969
18970           *slot = psym;
18971           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
18972                            is_static, kind, cu_index);
18973         }
18974     }
18975 }
18976
18977 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
18978    exception if there is an error.  */
18979
18980 static void
18981 write_obstack (FILE *file, struct obstack *obstack)
18982 {
18983   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
18984               file)
18985       != obstack_object_size (obstack))
18986     error (_("couldn't data write to file"));
18987 }
18988
18989 /* Unlink a file if the argument is not NULL.  */
18990
18991 static void
18992 unlink_if_set (void *p)
18993 {
18994   char **filename = p;
18995   if (*filename)
18996     unlink (*filename);
18997 }
18998
18999 /* A helper struct used when iterating over debug_types.  */
19000 struct signatured_type_index_data
19001 {
19002   struct objfile *objfile;
19003   struct mapped_symtab *symtab;
19004   struct obstack *types_list;
19005   htab_t psyms_seen;
19006   int cu_index;
19007 };
19008
19009 /* A helper function that writes a single signatured_type to an
19010    obstack.  */
19011
19012 static int
19013 write_one_signatured_type (void **slot, void *d)
19014 {
19015   struct signatured_type_index_data *info = d;
19016   struct signatured_type *entry = (struct signatured_type *) *slot;
19017   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
19018   struct partial_symtab *psymtab = per_cu->v.psymtab;
19019   gdb_byte val[8];
19020
19021   write_psymbols (info->symtab,
19022                   info->psyms_seen,
19023                   info->objfile->global_psymbols.list
19024                   + psymtab->globals_offset,
19025                   psymtab->n_global_syms, info->cu_index,
19026                   0);
19027   write_psymbols (info->symtab,
19028                   info->psyms_seen,
19029                   info->objfile->static_psymbols.list
19030                   + psymtab->statics_offset,
19031                   psymtab->n_static_syms, info->cu_index,
19032                   1);
19033
19034   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
19035                           entry->per_cu.offset.sect_off);
19036   obstack_grow (info->types_list, val, 8);
19037   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
19038                           entry->type_offset_in_tu.cu_off);
19039   obstack_grow (info->types_list, val, 8);
19040   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
19041   obstack_grow (info->types_list, val, 8);
19042
19043   ++info->cu_index;
19044
19045   return 1;
19046 }
19047
19048 /* Recurse into all "included" dependencies and write their symbols as
19049    if they appeared in this psymtab.  */
19050
19051 static void
19052 recursively_write_psymbols (struct objfile *objfile,
19053                             struct partial_symtab *psymtab,
19054                             struct mapped_symtab *symtab,
19055                             htab_t psyms_seen,
19056                             offset_type cu_index)
19057 {
19058   int i;
19059
19060   for (i = 0; i < psymtab->number_of_dependencies; ++i)
19061     if (psymtab->dependencies[i]->user != NULL)
19062       recursively_write_psymbols (objfile, psymtab->dependencies[i],
19063                                   symtab, psyms_seen, cu_index);
19064
19065   write_psymbols (symtab,
19066                   psyms_seen,
19067                   objfile->global_psymbols.list + psymtab->globals_offset,
19068                   psymtab->n_global_syms, cu_index,
19069                   0);
19070   write_psymbols (symtab,
19071                   psyms_seen,
19072                   objfile->static_psymbols.list + psymtab->statics_offset,
19073                   psymtab->n_static_syms, cu_index,
19074                   1);
19075 }
19076
19077 /* Create an index file for OBJFILE in the directory DIR.  */
19078
19079 static void
19080 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
19081 {
19082   struct cleanup *cleanup;
19083   char *filename, *cleanup_filename;
19084   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
19085   struct obstack cu_list, types_cu_list;
19086   int i;
19087   FILE *out_file;
19088   struct mapped_symtab *symtab;
19089   offset_type val, size_of_contents, total_len;
19090   struct stat st;
19091   htab_t psyms_seen;
19092   htab_t cu_index_htab;
19093   struct psymtab_cu_index_map *psymtab_cu_index_map;
19094
19095   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
19096     return;
19097
19098   if (dwarf2_per_objfile->using_index)
19099     error (_("Cannot use an index to create the index"));
19100
19101   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
19102     error (_("Cannot make an index when the file has multiple .debug_types sections"));
19103
19104   if (stat (objfile->name, &st) < 0)
19105     perror_with_name (objfile->name);
19106
19107   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
19108                      INDEX_SUFFIX, (char *) NULL);
19109   cleanup = make_cleanup (xfree, filename);
19110
19111   out_file = fopen (filename, "wb");
19112   if (!out_file)
19113     error (_("Can't open `%s' for writing"), filename);
19114
19115   cleanup_filename = filename;
19116   make_cleanup (unlink_if_set, &cleanup_filename);
19117
19118   symtab = create_mapped_symtab ();
19119   make_cleanup (cleanup_mapped_symtab, symtab);
19120
19121   obstack_init (&addr_obstack);
19122   make_cleanup_obstack_free (&addr_obstack);
19123
19124   obstack_init (&cu_list);
19125   make_cleanup_obstack_free (&cu_list);
19126
19127   obstack_init (&types_cu_list);
19128   make_cleanup_obstack_free (&types_cu_list);
19129
19130   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
19131                                   NULL, xcalloc, xfree);
19132   make_cleanup_htab_delete (psyms_seen);
19133
19134   /* While we're scanning CU's create a table that maps a psymtab pointer
19135      (which is what addrmap records) to its index (which is what is recorded
19136      in the index file).  This will later be needed to write the address
19137      table.  */
19138   cu_index_htab = htab_create_alloc (100,
19139                                      hash_psymtab_cu_index,
19140                                      eq_psymtab_cu_index,
19141                                      NULL, xcalloc, xfree);
19142   make_cleanup_htab_delete (cu_index_htab);
19143   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
19144     xmalloc (sizeof (struct psymtab_cu_index_map)
19145              * dwarf2_per_objfile->n_comp_units);
19146   make_cleanup (xfree, psymtab_cu_index_map);
19147
19148   /* The CU list is already sorted, so we don't need to do additional
19149      work here.  Also, the debug_types entries do not appear in
19150      all_comp_units, but only in their own hash table.  */
19151   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
19152     {
19153       struct dwarf2_per_cu_data *per_cu
19154         = dwarf2_per_objfile->all_comp_units[i];
19155       struct partial_symtab *psymtab = per_cu->v.psymtab;
19156       gdb_byte val[8];
19157       struct psymtab_cu_index_map *map;
19158       void **slot;
19159
19160       if (psymtab->user == NULL)
19161         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
19162
19163       map = &psymtab_cu_index_map[i];
19164       map->psymtab = psymtab;
19165       map->cu_index = i;
19166       slot = htab_find_slot (cu_index_htab, map, INSERT);
19167       gdb_assert (slot != NULL);
19168       gdb_assert (*slot == NULL);
19169       *slot = map;
19170
19171       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
19172                               per_cu->offset.sect_off);
19173       obstack_grow (&cu_list, val, 8);
19174       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
19175       obstack_grow (&cu_list, val, 8);
19176     }
19177
19178   /* Dump the address map.  */
19179   write_address_map (objfile, &addr_obstack, cu_index_htab);
19180
19181   /* Write out the .debug_type entries, if any.  */
19182   if (dwarf2_per_objfile->signatured_types)
19183     {
19184       struct signatured_type_index_data sig_data;
19185
19186       sig_data.objfile = objfile;
19187       sig_data.symtab = symtab;
19188       sig_data.types_list = &types_cu_list;
19189       sig_data.psyms_seen = psyms_seen;
19190       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
19191       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
19192                               write_one_signatured_type, &sig_data);
19193     }
19194
19195   /* Now that we've processed all symbols we can shrink their cu_indices
19196      lists.  */
19197   uniquify_cu_indices (symtab);
19198
19199   obstack_init (&constant_pool);
19200   make_cleanup_obstack_free (&constant_pool);
19201   obstack_init (&symtab_obstack);
19202   make_cleanup_obstack_free (&symtab_obstack);
19203   write_hash_table (symtab, &symtab_obstack, &constant_pool);
19204
19205   obstack_init (&contents);
19206   make_cleanup_obstack_free (&contents);
19207   size_of_contents = 6 * sizeof (offset_type);
19208   total_len = size_of_contents;
19209
19210   /* The version number.  */
19211   val = MAYBE_SWAP (7);
19212   obstack_grow (&contents, &val, sizeof (val));
19213
19214   /* The offset of the CU list from the start of the file.  */
19215   val = MAYBE_SWAP (total_len);
19216   obstack_grow (&contents, &val, sizeof (val));
19217   total_len += obstack_object_size (&cu_list);
19218
19219   /* The offset of the types CU list from the start of the file.  */
19220   val = MAYBE_SWAP (total_len);
19221   obstack_grow (&contents, &val, sizeof (val));
19222   total_len += obstack_object_size (&types_cu_list);
19223
19224   /* The offset of the address table from the start of the file.  */
19225   val = MAYBE_SWAP (total_len);
19226   obstack_grow (&contents, &val, sizeof (val));
19227   total_len += obstack_object_size (&addr_obstack);
19228
19229   /* The offset of the symbol table from the start of the file.  */
19230   val = MAYBE_SWAP (total_len);
19231   obstack_grow (&contents, &val, sizeof (val));
19232   total_len += obstack_object_size (&symtab_obstack);
19233
19234   /* The offset of the constant pool from the start of the file.  */
19235   val = MAYBE_SWAP (total_len);
19236   obstack_grow (&contents, &val, sizeof (val));
19237   total_len += obstack_object_size (&constant_pool);
19238
19239   gdb_assert (obstack_object_size (&contents) == size_of_contents);
19240
19241   write_obstack (out_file, &contents);
19242   write_obstack (out_file, &cu_list);
19243   write_obstack (out_file, &types_cu_list);
19244   write_obstack (out_file, &addr_obstack);
19245   write_obstack (out_file, &symtab_obstack);
19246   write_obstack (out_file, &constant_pool);
19247
19248   fclose (out_file);
19249
19250   /* We want to keep the file, so we set cleanup_filename to NULL
19251      here.  See unlink_if_set.  */
19252   cleanup_filename = NULL;
19253
19254   do_cleanups (cleanup);
19255 }
19256
19257 /* Implementation of the `save gdb-index' command.
19258    
19259    Note that the file format used by this command is documented in the
19260    GDB manual.  Any changes here must be documented there.  */
19261
19262 static void
19263 save_gdb_index_command (char *arg, int from_tty)
19264 {
19265   struct objfile *objfile;
19266
19267   if (!arg || !*arg)
19268     error (_("usage: save gdb-index DIRECTORY"));
19269
19270   ALL_OBJFILES (objfile)
19271   {
19272     struct stat st;
19273
19274     /* If the objfile does not correspond to an actual file, skip it.  */
19275     if (stat (objfile->name, &st) < 0)
19276       continue;
19277
19278     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19279     if (dwarf2_per_objfile)
19280       {
19281         volatile struct gdb_exception except;
19282
19283         TRY_CATCH (except, RETURN_MASK_ERROR)
19284           {
19285             write_psymtabs_to_index (objfile, arg);
19286           }
19287         if (except.reason < 0)
19288           exception_fprintf (gdb_stderr, except,
19289                              _("Error while writing index for `%s': "),
19290                              objfile->name);
19291       }
19292   }
19293 }
19294
19295 \f
19296
19297 int dwarf2_always_disassemble;
19298
19299 static void
19300 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
19301                                 struct cmd_list_element *c, const char *value)
19302 {
19303   fprintf_filtered (file,
19304                     _("Whether to always disassemble "
19305                       "DWARF expressions is %s.\n"),
19306                     value);
19307 }
19308
19309 static void
19310 show_check_physname (struct ui_file *file, int from_tty,
19311                      struct cmd_list_element *c, const char *value)
19312 {
19313   fprintf_filtered (file,
19314                     _("Whether to check \"physname\" is %s.\n"),
19315                     value);
19316 }
19317
19318 void _initialize_dwarf2_read (void);
19319
19320 void
19321 _initialize_dwarf2_read (void)
19322 {
19323   struct cmd_list_element *c;
19324
19325   dwarf2_objfile_data_key
19326     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
19327
19328   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
19329 Set DWARF 2 specific variables.\n\
19330 Configure DWARF 2 variables such as the cache size"),
19331                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
19332                   0/*allow-unknown*/, &maintenance_set_cmdlist);
19333
19334   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
19335 Show DWARF 2 specific variables\n\
19336 Show DWARF 2 variables such as the cache size"),
19337                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
19338                   0/*allow-unknown*/, &maintenance_show_cmdlist);
19339
19340   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
19341                             &dwarf2_max_cache_age, _("\
19342 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
19343 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
19344 A higher limit means that cached compilation units will be stored\n\
19345 in memory longer, and more total memory will be used.  Zero disables\n\
19346 caching, which can slow down startup."),
19347                             NULL,
19348                             show_dwarf2_max_cache_age,
19349                             &set_dwarf2_cmdlist,
19350                             &show_dwarf2_cmdlist);
19351
19352   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
19353                            &dwarf2_always_disassemble, _("\
19354 Set whether `info address' always disassembles DWARF expressions."), _("\
19355 Show whether `info address' always disassembles DWARF expressions."), _("\
19356 When enabled, DWARF expressions are always printed in an assembly-like\n\
19357 syntax.  When disabled, expressions will be printed in a more\n\
19358 conversational style, when possible."),
19359                            NULL,
19360                            show_dwarf2_always_disassemble,
19361                            &set_dwarf2_cmdlist,
19362                            &show_dwarf2_cmdlist);
19363
19364   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
19365 Set debugging of the dwarf2 reader."), _("\
19366 Show debugging of the dwarf2 reader."), _("\
19367 When enabled, debugging messages are printed during dwarf2 reading\n\
19368 and symtab expansion."),
19369                             NULL,
19370                             NULL,
19371                             &setdebuglist, &showdebuglist);
19372
19373   add_setshow_zinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
19374 Set debugging of the dwarf2 DIE reader."), _("\
19375 Show debugging of the dwarf2 DIE reader."), _("\
19376 When enabled (non-zero), DIEs are dumped after they are read in.\n\
19377 The value is the maximum depth to print."),
19378                             NULL,
19379                             NULL,
19380                             &setdebuglist, &showdebuglist);
19381
19382   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
19383 Set cross-checking of \"physname\" code against demangler."), _("\
19384 Show cross-checking of \"physname\" code against demangler."), _("\
19385 When enabled, GDB's internal \"physname\" code is checked against\n\
19386 the demangler."),
19387                            NULL, show_check_physname,
19388                            &setdebuglist, &showdebuglist);
19389
19390   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
19391                _("\
19392 Save a gdb-index file.\n\
19393 Usage: save gdb-index DIRECTORY"),
19394                &save_cmdlist);
19395   set_cmd_completer (c, filename_completer);
19396 }