9e3be9f4c61f478980c307beaa6a71386908280b
[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 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
597    an object of this type.  */
598
599 struct type_unit_group
600 {
601   /* dwarf2read.c's main "handle" on the symtab.
602      To simplify things we create an artificial CU that "includes" all the
603      type units using this stmt_list so that the rest of the code still has
604      a "per_cu" handle on the symtab.
605      This PER_CU is recognized by having no section.  */
606 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->info_or_types_section == NULL)
607   struct dwarf2_per_cu_data *per_cu;
608
609   /* The TUs that share this DW_AT_stmt_list entry.
610      This is added to while parsing type units to build partial symtabs,
611      and is deleted afterwards and not used again.  */
612   VEC (dwarf2_per_cu_ptr) *tus;
613
614   /* The primary symtab.
615      Type units don't have DW_AT_name so we create an essentially
616      anonymous symtab as the primary symtab.  */
617   struct symtab *primary_symtab;
618
619   /* Offset in .debug_line.  This is the hash key.  */
620   sect_offset line_offset;
621
622   /* The number of symtabs from the line header.
623      The value here must match line_header.num_file_names.  */
624   unsigned int num_symtabs;
625
626   /* The symbol tables for this TU (obtained from the files listed in
627      DW_AT_stmt_list).
628      WARNING: The order of entries here must match the order of entries
629      in the line header.  After the first TU using this type_unit_group, the
630      line header for the subsequent TUs is recreated from this.  This is done
631      because we need to use the same symtabs for each TU using the same
632      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
633      there's no guarantee the line header doesn't have duplicate entries.  */
634   struct symtab **symtabs;
635 };
636
637 /* These sections are what may appear in a "dwo" file.  */
638
639 struct dwo_sections
640 {
641   struct dwarf2_section_info abbrev;
642   struct dwarf2_section_info info;
643   struct dwarf2_section_info line;
644   struct dwarf2_section_info loc;
645   struct dwarf2_section_info macinfo;
646   struct dwarf2_section_info macro;
647   struct dwarf2_section_info str;
648   struct dwarf2_section_info str_offsets;
649   VEC (dwarf2_section_info_def) *types;
650 };
651
652 /* Common bits of DWO CUs/TUs.  */
653
654 struct dwo_unit
655 {
656   /* Backlink to the containing struct dwo_file.  */
657   struct dwo_file *dwo_file;
658
659   /* The "id" that distinguishes this CU/TU.
660      .debug_info calls this "dwo_id", .debug_types calls this "signature".
661      Since signatures came first, we stick with it for consistency.  */
662   ULONGEST signature;
663
664   /* The section this CU/TU lives in, in the DWO file.  */
665   struct dwarf2_section_info *info_or_types_section;
666
667   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
668   sect_offset offset;
669   unsigned int length;
670
671   /* For types, offset in the type's DIE of the type defined by this TU.  */
672   cu_offset type_offset_in_tu;
673 };
674
675 /* Data for one DWO file.  */
676
677 struct dwo_file
678 {
679   /* The DW_AT_GNU_dwo_name attribute.
680      We don't manage space for this, it's an attribute.  */
681   const char *dwo_name;
682
683   /* The bfd, when the file is open.  Otherwise this is NULL.  */
684   bfd *dwo_bfd;
685
686   /* Section info for this file.  */
687   struct dwo_sections sections;
688
689   /* Table of CUs in the file.
690      Each element is a struct dwo_unit.  */
691   htab_t cus;
692
693   /* Table of TUs in the file.
694      Each element is a struct dwo_unit.  */
695   htab_t tus;
696 };
697
698 /* Struct used to pass misc. parameters to read_die_and_children, et
699    al.  which are used for both .debug_info and .debug_types dies.
700    All parameters here are unchanging for the life of the call.  This
701    struct exists to abstract away the constant parameters of die reading.  */
702
703 struct die_reader_specs
704 {
705   /* die_section->asection->owner.  */
706   bfd* abfd;
707
708   /* The CU of the DIE we are parsing.  */
709   struct dwarf2_cu *cu;
710
711   /* Non-NULL if reading a DWO file.  */
712   struct dwo_file *dwo_file;
713
714   /* The section the die comes from.
715      This is either .debug_info or .debug_types, or the .dwo variants.  */
716   struct dwarf2_section_info *die_section;
717
718   /* die_section->buffer.  */
719   gdb_byte *buffer;
720
721   /* The end of the buffer.  */
722   const gdb_byte *buffer_end;
723 };
724
725 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
726 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
727                                       gdb_byte *info_ptr,
728                                       struct die_info *comp_unit_die,
729                                       int has_children,
730                                       void *data);
731
732 /* The line number information for a compilation unit (found in the
733    .debug_line section) begins with a "statement program header",
734    which contains the following information.  */
735 struct line_header
736 {
737   unsigned int total_length;
738   unsigned short version;
739   unsigned int header_length;
740   unsigned char minimum_instruction_length;
741   unsigned char maximum_ops_per_instruction;
742   unsigned char default_is_stmt;
743   int line_base;
744   unsigned char line_range;
745   unsigned char opcode_base;
746
747   /* standard_opcode_lengths[i] is the number of operands for the
748      standard opcode whose value is i.  This means that
749      standard_opcode_lengths[0] is unused, and the last meaningful
750      element is standard_opcode_lengths[opcode_base - 1].  */
751   unsigned char *standard_opcode_lengths;
752
753   /* The include_directories table.  NOTE!  These strings are not
754      allocated with xmalloc; instead, they are pointers into
755      debug_line_buffer.  If you try to free them, `free' will get
756      indigestion.  */
757   unsigned int num_include_dirs, include_dirs_size;
758   char **include_dirs;
759
760   /* The file_names table.  NOTE!  These strings are not allocated
761      with xmalloc; instead, they are pointers into debug_line_buffer.
762      Don't try to free them directly.  */
763   unsigned int num_file_names, file_names_size;
764   struct file_entry
765   {
766     char *name;
767     unsigned int dir_index;
768     unsigned int mod_time;
769     unsigned int length;
770     int included_p; /* Non-zero if referenced by the Line Number Program.  */
771     struct symtab *symtab; /* The associated symbol table, if any.  */
772   } *file_names;
773
774   /* The start and end of the statement program following this
775      header.  These point into dwarf2_per_objfile->line_buffer.  */
776   gdb_byte *statement_program_start, *statement_program_end;
777 };
778
779 /* When we construct a partial symbol table entry we only
780    need this much information.  */
781 struct partial_die_info
782   {
783     /* Offset of this DIE.  */
784     sect_offset offset;
785
786     /* DWARF-2 tag for this DIE.  */
787     ENUM_BITFIELD(dwarf_tag) tag : 16;
788
789     /* Assorted flags describing the data found in this DIE.  */
790     unsigned int has_children : 1;
791     unsigned int is_external : 1;
792     unsigned int is_declaration : 1;
793     unsigned int has_type : 1;
794     unsigned int has_specification : 1;
795     unsigned int has_pc_info : 1;
796     unsigned int may_be_inlined : 1;
797
798     /* Flag set if the SCOPE field of this structure has been
799        computed.  */
800     unsigned int scope_set : 1;
801
802     /* Flag set if the DIE has a byte_size attribute.  */
803     unsigned int has_byte_size : 1;
804
805     /* Flag set if any of the DIE's children are template arguments.  */
806     unsigned int has_template_arguments : 1;
807
808     /* Flag set if fixup_partial_die has been called on this die.  */
809     unsigned int fixup_called : 1;
810
811     /* The name of this DIE.  Normally the value of DW_AT_name, but
812        sometimes a default name for unnamed DIEs.  */
813     char *name;
814
815     /* The linkage name, if present.  */
816     const char *linkage_name;
817
818     /* The scope to prepend to our children.  This is generally
819        allocated on the comp_unit_obstack, so will disappear
820        when this compilation unit leaves the cache.  */
821     char *scope;
822
823     /* Some data associated with the partial DIE.  The tag determines
824        which field is live.  */
825     union
826     {
827       /* The location description associated with this DIE, if any.  */
828       struct dwarf_block *locdesc;
829       /* The offset of an import, for DW_TAG_imported_unit.  */
830       sect_offset offset;
831     } d;
832
833     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
834     CORE_ADDR lowpc;
835     CORE_ADDR highpc;
836
837     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
838        DW_AT_sibling, if any.  */
839     /* NOTE: This member isn't strictly necessary, read_partial_die could
840        return DW_AT_sibling values to its caller load_partial_dies.  */
841     gdb_byte *sibling;
842
843     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
844        DW_AT_specification (or DW_AT_abstract_origin or
845        DW_AT_extension).  */
846     sect_offset spec_offset;
847
848     /* Pointers to this DIE's parent, first child, and next sibling,
849        if any.  */
850     struct partial_die_info *die_parent, *die_child, *die_sibling;
851   };
852
853 /* This data structure holds the information of an abbrev.  */
854 struct abbrev_info
855   {
856     unsigned int number;        /* number identifying abbrev */
857     enum dwarf_tag tag;         /* dwarf tag */
858     unsigned short has_children;                /* boolean */
859     unsigned short num_attrs;   /* number of attributes */
860     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
861     struct abbrev_info *next;   /* next in chain */
862   };
863
864 struct attr_abbrev
865   {
866     ENUM_BITFIELD(dwarf_attribute) name : 16;
867     ENUM_BITFIELD(dwarf_form) form : 16;
868   };
869
870 /* Size of abbrev_table.abbrev_hash_table.  */
871 #define ABBREV_HASH_SIZE 121
872
873 /* Top level data structure to contain an abbreviation table.  */
874
875 struct abbrev_table
876 {
877   /* Where the abbrev table came from.
878      This is used as a sanity check when the table is used.  */
879   sect_offset offset;
880
881   /* Storage for the abbrev table.  */
882   struct obstack abbrev_obstack;
883
884   /* Hash table of abbrevs.
885      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
886      It could be statically allocated, but the previous code didn't so we
887      don't either.  */
888   struct abbrev_info **abbrevs;
889 };
890
891 /* Attributes have a name and a value.  */
892 struct attribute
893   {
894     ENUM_BITFIELD(dwarf_attribute) name : 16;
895     ENUM_BITFIELD(dwarf_form) form : 15;
896
897     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
898        field should be in u.str (existing only for DW_STRING) but it is kept
899        here for better struct attribute alignment.  */
900     unsigned int string_is_canonical : 1;
901
902     union
903       {
904         char *str;
905         struct dwarf_block *blk;
906         ULONGEST unsnd;
907         LONGEST snd;
908         CORE_ADDR addr;
909         struct signatured_type *signatured_type;
910       }
911     u;
912   };
913
914 /* This data structure holds a complete die structure.  */
915 struct die_info
916   {
917     /* DWARF-2 tag for this DIE.  */
918     ENUM_BITFIELD(dwarf_tag) tag : 16;
919
920     /* Number of attributes */
921     unsigned char num_attrs;
922
923     /* True if we're presently building the full type name for the
924        type derived from this DIE.  */
925     unsigned char building_fullname : 1;
926
927     /* Abbrev number */
928     unsigned int abbrev;
929
930     /* Offset in .debug_info or .debug_types section.  */
931     sect_offset offset;
932
933     /* The dies in a compilation unit form an n-ary tree.  PARENT
934        points to this die's parent; CHILD points to the first child of
935        this node; and all the children of a given node are chained
936        together via their SIBLING fields.  */
937     struct die_info *child;     /* Its first child, if any.  */
938     struct die_info *sibling;   /* Its next sibling, if any.  */
939     struct die_info *parent;    /* Its parent, if any.  */
940
941     /* An array of attributes, with NUM_ATTRS elements.  There may be
942        zero, but it's not common and zero-sized arrays are not
943        sufficiently portable C.  */
944     struct attribute attrs[1];
945   };
946
947 /* Get at parts of an attribute structure.  */
948
949 #define DW_STRING(attr)    ((attr)->u.str)
950 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
951 #define DW_UNSND(attr)     ((attr)->u.unsnd)
952 #define DW_BLOCK(attr)     ((attr)->u.blk)
953 #define DW_SND(attr)       ((attr)->u.snd)
954 #define DW_ADDR(attr)      ((attr)->u.addr)
955 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
956
957 /* Blocks are a bunch of untyped bytes.  */
958 struct dwarf_block
959   {
960     unsigned int size;
961
962     /* Valid only if SIZE is not zero.  */
963     gdb_byte *data;
964   };
965
966 #ifndef ATTR_ALLOC_CHUNK
967 #define ATTR_ALLOC_CHUNK 4
968 #endif
969
970 /* Allocate fields for structs, unions and enums in this size.  */
971 #ifndef DW_FIELD_ALLOC_CHUNK
972 #define DW_FIELD_ALLOC_CHUNK 4
973 #endif
974
975 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
976    but this would require a corresponding change in unpack_field_as_long
977    and friends.  */
978 static int bits_per_byte = 8;
979
980 /* The routines that read and process dies for a C struct or C++ class
981    pass lists of data member fields and lists of member function fields
982    in an instance of a field_info structure, as defined below.  */
983 struct field_info
984   {
985     /* List of data member and baseclasses fields.  */
986     struct nextfield
987       {
988         struct nextfield *next;
989         int accessibility;
990         int virtuality;
991         struct field field;
992       }
993      *fields, *baseclasses;
994
995     /* Number of fields (including baseclasses).  */
996     int nfields;
997
998     /* Number of baseclasses.  */
999     int nbaseclasses;
1000
1001     /* Set if the accesibility of one of the fields is not public.  */
1002     int non_public_fields;
1003
1004     /* Member function fields array, entries are allocated in the order they
1005        are encountered in the object file.  */
1006     struct nextfnfield
1007       {
1008         struct nextfnfield *next;
1009         struct fn_field fnfield;
1010       }
1011      *fnfields;
1012
1013     /* Member function fieldlist array, contains name of possibly overloaded
1014        member function, number of overloaded member functions and a pointer
1015        to the head of the member function field chain.  */
1016     struct fnfieldlist
1017       {
1018         char *name;
1019         int length;
1020         struct nextfnfield *head;
1021       }
1022      *fnfieldlists;
1023
1024     /* Number of entries in the fnfieldlists array.  */
1025     int nfnfields;
1026
1027     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1028        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1029     struct typedef_field_list
1030       {
1031         struct typedef_field field;
1032         struct typedef_field_list *next;
1033       }
1034     *typedef_field_list;
1035     unsigned typedef_field_list_count;
1036   };
1037
1038 /* One item on the queue of compilation units to read in full symbols
1039    for.  */
1040 struct dwarf2_queue_item
1041 {
1042   struct dwarf2_per_cu_data *per_cu;
1043   enum language pretend_language;
1044   struct dwarf2_queue_item *next;
1045 };
1046
1047 /* The current queue.  */
1048 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1049
1050 /* Loaded secondary compilation units are kept in memory until they
1051    have not been referenced for the processing of this many
1052    compilation units.  Set this to zero to disable caching.  Cache
1053    sizes of up to at least twenty will improve startup time for
1054    typical inter-CU-reference binaries, at an obvious memory cost.  */
1055 static int dwarf2_max_cache_age = 5;
1056 static void
1057 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1058                            struct cmd_list_element *c, const char *value)
1059 {
1060   fprintf_filtered (file, _("The upper bound on the age of cached "
1061                             "dwarf2 compilation units is %s.\n"),
1062                     value);
1063 }
1064
1065
1066 /* Various complaints about symbol reading that don't abort the process.  */
1067
1068 static void
1069 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1070 {
1071   complaint (&symfile_complaints,
1072              _("statement list doesn't fit in .debug_line section"));
1073 }
1074
1075 static void
1076 dwarf2_debug_line_missing_file_complaint (void)
1077 {
1078   complaint (&symfile_complaints,
1079              _(".debug_line section has line data without a file"));
1080 }
1081
1082 static void
1083 dwarf2_debug_line_missing_end_sequence_complaint (void)
1084 {
1085   complaint (&symfile_complaints,
1086              _(".debug_line section has line "
1087                "program sequence without an end"));
1088 }
1089
1090 static void
1091 dwarf2_complex_location_expr_complaint (void)
1092 {
1093   complaint (&symfile_complaints, _("location expression too complex"));
1094 }
1095
1096 static void
1097 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1098                                               int arg3)
1099 {
1100   complaint (&symfile_complaints,
1101              _("const value length mismatch for '%s', got %d, expected %d"),
1102              arg1, arg2, arg3);
1103 }
1104
1105 static void
1106 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1107 {
1108   complaint (&symfile_complaints,
1109              _("debug info runs off end of %s section"
1110                " [in module %s]"),
1111              section->asection->name,
1112              bfd_get_filename (section->asection->owner));
1113 }
1114
1115 static void
1116 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1117 {
1118   complaint (&symfile_complaints,
1119              _("macro debug info contains a "
1120                "malformed macro definition:\n`%s'"),
1121              arg1);
1122 }
1123
1124 static void
1125 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1126 {
1127   complaint (&symfile_complaints,
1128              _("invalid attribute class or form for '%s' in '%s'"),
1129              arg1, arg2);
1130 }
1131
1132 /* local function prototypes */
1133
1134 static void dwarf2_locate_sections (bfd *, asection *, void *);
1135
1136 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1137                                            struct objfile *);
1138
1139 static void dwarf2_find_base_address (struct die_info *die,
1140                                       struct dwarf2_cu *cu);
1141
1142 static void dwarf2_build_psymtabs_hard (struct objfile *);
1143
1144 static void scan_partial_symbols (struct partial_die_info *,
1145                                   CORE_ADDR *, CORE_ADDR *,
1146                                   int, struct dwarf2_cu *);
1147
1148 static void add_partial_symbol (struct partial_die_info *,
1149                                 struct dwarf2_cu *);
1150
1151 static void add_partial_namespace (struct partial_die_info *pdi,
1152                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1153                                    int need_pc, struct dwarf2_cu *cu);
1154
1155 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1156                                 CORE_ADDR *highpc, int need_pc,
1157                                 struct dwarf2_cu *cu);
1158
1159 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1160                                      struct dwarf2_cu *cu);
1161
1162 static void add_partial_subprogram (struct partial_die_info *pdi,
1163                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1164                                     int need_pc, struct dwarf2_cu *cu);
1165
1166 static void dwarf2_psymtab_to_symtab (struct partial_symtab *);
1167
1168 static void psymtab_to_symtab_1 (struct partial_symtab *);
1169
1170 static struct abbrev_info *abbrev_table_lookup_abbrev
1171   (const struct abbrev_table *, unsigned int);
1172
1173 static struct abbrev_table *abbrev_table_read_table
1174   (struct dwarf2_section_info *, sect_offset);
1175
1176 static void abbrev_table_free (struct abbrev_table *);
1177
1178 static void abbrev_table_free_cleanup (void *);
1179
1180 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1181                                  struct dwarf2_section_info *);
1182
1183 static void dwarf2_free_abbrev_table (void *);
1184
1185 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1186
1187 static struct partial_die_info *load_partial_dies
1188   (const struct die_reader_specs *, gdb_byte *, int);
1189
1190 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1191                                    struct partial_die_info *,
1192                                    struct abbrev_info *,
1193                                    unsigned int,
1194                                    gdb_byte *);
1195
1196 static struct partial_die_info *find_partial_die (sect_offset,
1197                                                   struct dwarf2_cu *);
1198
1199 static void fixup_partial_die (struct partial_die_info *,
1200                                struct dwarf2_cu *);
1201
1202 static gdb_byte *read_attribute (const struct die_reader_specs *,
1203                                  struct attribute *, struct attr_abbrev *,
1204                                  gdb_byte *);
1205
1206 static unsigned int read_1_byte (bfd *, gdb_byte *);
1207
1208 static int read_1_signed_byte (bfd *, gdb_byte *);
1209
1210 static unsigned int read_2_bytes (bfd *, gdb_byte *);
1211
1212 static unsigned int read_4_bytes (bfd *, gdb_byte *);
1213
1214 static ULONGEST read_8_bytes (bfd *, gdb_byte *);
1215
1216 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1217                                unsigned int *);
1218
1219 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1220
1221 static LONGEST read_checked_initial_length_and_offset
1222   (bfd *, gdb_byte *, const struct comp_unit_head *,
1223    unsigned int *, unsigned int *);
1224
1225 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1226                             unsigned int *);
1227
1228 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1229
1230 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1231                                        sect_offset);
1232
1233 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1234
1235 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1236
1237 static char *read_indirect_string (bfd *, gdb_byte *,
1238                                    const struct comp_unit_head *,
1239                                    unsigned int *);
1240
1241 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1242
1243 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1244
1245 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1246                                               unsigned int *);
1247
1248 static char *read_str_index (const struct die_reader_specs *reader,
1249                              struct dwarf2_cu *cu, ULONGEST str_index);
1250
1251 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1252
1253 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1254                                       struct dwarf2_cu *);
1255
1256 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1257                                                 unsigned int);
1258
1259 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1260                                struct dwarf2_cu *cu);
1261
1262 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1263
1264 static struct die_info *die_specification (struct die_info *die,
1265                                            struct dwarf2_cu **);
1266
1267 static void free_line_header (struct line_header *lh);
1268
1269 static void add_file_name (struct line_header *, char *, unsigned int,
1270                            unsigned int, unsigned int);
1271
1272 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1273                                                      struct dwarf2_cu *cu);
1274
1275 static void dwarf_decode_lines (struct line_header *, const char *,
1276                                 struct dwarf2_cu *, struct partial_symtab *,
1277                                 int);
1278
1279 static void dwarf2_start_subfile (char *, const char *, const char *);
1280
1281 static void dwarf2_start_symtab (struct dwarf2_cu *,
1282                                  char *, char *, CORE_ADDR);
1283
1284 static struct symbol *new_symbol (struct die_info *, struct type *,
1285                                   struct dwarf2_cu *);
1286
1287 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1288                                        struct dwarf2_cu *, struct symbol *);
1289
1290 static void dwarf2_const_value (struct attribute *, struct symbol *,
1291                                 struct dwarf2_cu *);
1292
1293 static void dwarf2_const_value_attr (struct attribute *attr,
1294                                      struct type *type,
1295                                      const char *name,
1296                                      struct obstack *obstack,
1297                                      struct dwarf2_cu *cu, LONGEST *value,
1298                                      gdb_byte **bytes,
1299                                      struct dwarf2_locexpr_baton **baton);
1300
1301 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1302
1303 static int need_gnat_info (struct dwarf2_cu *);
1304
1305 static struct type *die_descriptive_type (struct die_info *,
1306                                           struct dwarf2_cu *);
1307
1308 static void set_descriptive_type (struct type *, struct die_info *,
1309                                   struct dwarf2_cu *);
1310
1311 static struct type *die_containing_type (struct die_info *,
1312                                          struct dwarf2_cu *);
1313
1314 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1315                                      struct dwarf2_cu *);
1316
1317 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1318
1319 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1320
1321 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1322
1323 static char *typename_concat (struct obstack *obs, const char *prefix,
1324                               const char *suffix, int physname,
1325                               struct dwarf2_cu *cu);
1326
1327 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1328
1329 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1330
1331 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1332
1333 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1334
1335 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1336
1337 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1338                                struct dwarf2_cu *, struct partial_symtab *);
1339
1340 static int dwarf2_get_pc_bounds (struct die_info *,
1341                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1342                                  struct partial_symtab *);
1343
1344 static void get_scope_pc_bounds (struct die_info *,
1345                                  CORE_ADDR *, CORE_ADDR *,
1346                                  struct dwarf2_cu *);
1347
1348 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1349                                         CORE_ADDR, struct dwarf2_cu *);
1350
1351 static void dwarf2_add_field (struct field_info *, struct die_info *,
1352                               struct dwarf2_cu *);
1353
1354 static void dwarf2_attach_fields_to_type (struct field_info *,
1355                                           struct type *, struct dwarf2_cu *);
1356
1357 static void dwarf2_add_member_fn (struct field_info *,
1358                                   struct die_info *, struct type *,
1359                                   struct dwarf2_cu *);
1360
1361 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1362                                              struct type *,
1363                                              struct dwarf2_cu *);
1364
1365 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1366
1367 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1368
1369 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1370
1371 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1372
1373 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1374
1375 static struct type *read_module_type (struct die_info *die,
1376                                       struct dwarf2_cu *cu);
1377
1378 static const char *namespace_name (struct die_info *die,
1379                                    int *is_anonymous, struct dwarf2_cu *);
1380
1381 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1382
1383 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1384
1385 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1386                                                        struct dwarf2_cu *);
1387
1388 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1389                                                gdb_byte *info_ptr,
1390                                                gdb_byte **new_info_ptr,
1391                                                struct die_info *parent);
1392
1393 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1394                                                gdb_byte *info_ptr,
1395                                                gdb_byte **new_info_ptr,
1396                                                struct die_info *parent);
1397
1398 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1399                                   struct die_info **, gdb_byte *, int *, int);
1400
1401 static gdb_byte *read_full_die (const struct die_reader_specs *,
1402                                 struct die_info **, gdb_byte *, int *);
1403
1404 static void process_die (struct die_info *, struct dwarf2_cu *);
1405
1406 static char *dwarf2_canonicalize_name (char *, struct dwarf2_cu *,
1407                                        struct obstack *);
1408
1409 static char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1410
1411 static const char *dwarf2_full_name (char *name,
1412                                      struct die_info *die,
1413                                      struct dwarf2_cu *cu);
1414
1415 static struct die_info *dwarf2_extension (struct die_info *die,
1416                                           struct dwarf2_cu **);
1417
1418 static const char *dwarf_tag_name (unsigned int);
1419
1420 static const char *dwarf_attr_name (unsigned int);
1421
1422 static const char *dwarf_form_name (unsigned int);
1423
1424 static char *dwarf_bool_name (unsigned int);
1425
1426 static const char *dwarf_type_encoding_name (unsigned int);
1427
1428 static struct die_info *sibling_die (struct die_info *);
1429
1430 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1431
1432 static void dump_die_for_error (struct die_info *);
1433
1434 static void dump_die_1 (struct ui_file *, int level, int max_level,
1435                         struct die_info *);
1436
1437 /*static*/ void dump_die (struct die_info *, int max_level);
1438
1439 static void store_in_ref_table (struct die_info *,
1440                                 struct dwarf2_cu *);
1441
1442 static int is_ref_attr (struct attribute *);
1443
1444 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1445
1446 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1447
1448 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1449                                                struct attribute *,
1450                                                struct dwarf2_cu **);
1451
1452 static struct die_info *follow_die_ref (struct die_info *,
1453                                         struct attribute *,
1454                                         struct dwarf2_cu **);
1455
1456 static struct die_info *follow_die_sig (struct die_info *,
1457                                         struct attribute *,
1458                                         struct dwarf2_cu **);
1459
1460 static struct signatured_type *lookup_signatured_type_at_offset
1461     (struct objfile *objfile,
1462      struct dwarf2_section_info *section, sect_offset offset);
1463
1464 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1465
1466 static void read_signatured_type (struct signatured_type *);
1467
1468 static struct type_unit_group *get_type_unit_group
1469     (struct dwarf2_per_cu_data *, struct attribute *);
1470
1471 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1472
1473 /* memory allocation interface */
1474
1475 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1476
1477 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1478
1479 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1480                                  char *, int);
1481
1482 static int attr_form_is_block (struct attribute *);
1483
1484 static int attr_form_is_section_offset (struct attribute *);
1485
1486 static int attr_form_is_constant (struct attribute *);
1487
1488 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1489                                    struct dwarf2_loclist_baton *baton,
1490                                    struct attribute *attr);
1491
1492 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1493                                          struct symbol *sym,
1494                                          struct dwarf2_cu *cu);
1495
1496 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1497                                gdb_byte *info_ptr,
1498                                struct abbrev_info *abbrev);
1499
1500 static void free_stack_comp_unit (void *);
1501
1502 static hashval_t partial_die_hash (const void *item);
1503
1504 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1505
1506 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1507   (sect_offset offset, struct objfile *objfile);
1508
1509 static void init_one_comp_unit (struct dwarf2_cu *cu,
1510                                 struct dwarf2_per_cu_data *per_cu);
1511
1512 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1513                                    struct die_info *comp_unit_die,
1514                                    enum language pretend_language);
1515
1516 static void free_heap_comp_unit (void *);
1517
1518 static void free_cached_comp_units (void *);
1519
1520 static void age_cached_comp_units (void);
1521
1522 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1523
1524 static struct type *set_die_type (struct die_info *, struct type *,
1525                                   struct dwarf2_cu *);
1526
1527 static void create_all_comp_units (struct objfile *);
1528
1529 static int create_all_type_units (struct objfile *);
1530
1531 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1532                                  enum language);
1533
1534 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1535                                     enum language);
1536
1537 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1538                                     enum language);
1539
1540 static void dwarf2_add_dependence (struct dwarf2_cu *,
1541                                    struct dwarf2_per_cu_data *);
1542
1543 static void dwarf2_mark (struct dwarf2_cu *);
1544
1545 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1546
1547 static struct type *get_die_type_at_offset (sect_offset,
1548                                             struct dwarf2_per_cu_data *per_cu);
1549
1550 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1551
1552 static void dwarf2_release_queue (void *dummy);
1553
1554 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1555                              enum language pretend_language);
1556
1557 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1558                                   struct dwarf2_per_cu_data *per_cu,
1559                                   enum language pretend_language);
1560
1561 static void process_queue (void);
1562
1563 static void find_file_and_directory (struct die_info *die,
1564                                      struct dwarf2_cu *cu,
1565                                      char **name, char **comp_dir);
1566
1567 static char *file_full_name (int file, struct line_header *lh,
1568                              const char *comp_dir);
1569
1570 static void init_cutu_and_read_dies
1571   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1572    int use_existing_cu, int keep,
1573    die_reader_func_ftype *die_reader_func, void *data);
1574
1575 static void init_cutu_and_read_dies_simple
1576   (struct dwarf2_per_cu_data *this_cu,
1577    die_reader_func_ftype *die_reader_func, void *data);
1578
1579 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1580
1581 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1582
1583 static struct dwo_unit *lookup_dwo_comp_unit
1584   (struct dwarf2_per_cu_data *, char *, const char *, ULONGEST);
1585
1586 static struct dwo_unit *lookup_dwo_type_unit
1587   (struct signatured_type *, char *, const char *);
1588
1589 static void free_dwo_file_cleanup (void *);
1590
1591 static void munmap_section_buffer (struct dwarf2_section_info *);
1592
1593 static void process_cu_includes (void);
1594
1595 #if WORDS_BIGENDIAN
1596
1597 /* Convert VALUE between big- and little-endian.  */
1598 static offset_type
1599 byte_swap (offset_type value)
1600 {
1601   offset_type result;
1602
1603   result = (value & 0xff) << 24;
1604   result |= (value & 0xff00) << 8;
1605   result |= (value & 0xff0000) >> 8;
1606   result |= (value & 0xff000000) >> 24;
1607   return result;
1608 }
1609
1610 #define MAYBE_SWAP(V)  byte_swap (V)
1611
1612 #else
1613 #define MAYBE_SWAP(V) (V)
1614 #endif /* WORDS_BIGENDIAN */
1615
1616 /* The suffix for an index file.  */
1617 #define INDEX_SUFFIX ".gdb-index"
1618
1619 static const char *dwarf2_physname (char *name, struct die_info *die,
1620                                     struct dwarf2_cu *cu);
1621
1622 /* Try to locate the sections we need for DWARF 2 debugging
1623    information and return true if we have enough to do something.
1624    NAMES points to the dwarf2 section names, or is NULL if the standard
1625    ELF names are used.  */
1626
1627 int
1628 dwarf2_has_info (struct objfile *objfile,
1629                  const struct dwarf2_debug_sections *names)
1630 {
1631   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1632   if (!dwarf2_per_objfile)
1633     {
1634       /* Initialize per-objfile state.  */
1635       struct dwarf2_per_objfile *data
1636         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1637
1638       memset (data, 0, sizeof (*data));
1639       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1640       dwarf2_per_objfile = data;
1641
1642       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1643                              (void *) names);
1644       dwarf2_per_objfile->objfile = objfile;
1645     }
1646   return (dwarf2_per_objfile->info.asection != NULL
1647           && dwarf2_per_objfile->abbrev.asection != NULL);
1648 }
1649
1650 /* When loading sections, we look either for uncompressed section or for
1651    compressed section names.  */
1652
1653 static int
1654 section_is_p (const char *section_name,
1655               const struct dwarf2_section_names *names)
1656 {
1657   if (names->normal != NULL
1658       && strcmp (section_name, names->normal) == 0)
1659     return 1;
1660   if (names->compressed != NULL
1661       && strcmp (section_name, names->compressed) == 0)
1662     return 1;
1663   return 0;
1664 }
1665
1666 /* This function is mapped across the sections and remembers the
1667    offset and size of each of the debugging sections we are interested
1668    in.  */
1669
1670 static void
1671 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1672 {
1673   const struct dwarf2_debug_sections *names;
1674
1675   if (vnames == NULL)
1676     names = &dwarf2_elf_names;
1677   else
1678     names = (const struct dwarf2_debug_sections *) vnames;
1679
1680   if (section_is_p (sectp->name, &names->info))
1681     {
1682       dwarf2_per_objfile->info.asection = sectp;
1683       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1684     }
1685   else if (section_is_p (sectp->name, &names->abbrev))
1686     {
1687       dwarf2_per_objfile->abbrev.asection = sectp;
1688       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1689     }
1690   else if (section_is_p (sectp->name, &names->line))
1691     {
1692       dwarf2_per_objfile->line.asection = sectp;
1693       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1694     }
1695   else if (section_is_p (sectp->name, &names->loc))
1696     {
1697       dwarf2_per_objfile->loc.asection = sectp;
1698       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1699     }
1700   else if (section_is_p (sectp->name, &names->macinfo))
1701     {
1702       dwarf2_per_objfile->macinfo.asection = sectp;
1703       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1704     }
1705   else if (section_is_p (sectp->name, &names->macro))
1706     {
1707       dwarf2_per_objfile->macro.asection = sectp;
1708       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1709     }
1710   else if (section_is_p (sectp->name, &names->str))
1711     {
1712       dwarf2_per_objfile->str.asection = sectp;
1713       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1714     }
1715   else if (section_is_p (sectp->name, &names->addr))
1716     {
1717       dwarf2_per_objfile->addr.asection = sectp;
1718       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1719     }
1720   else if (section_is_p (sectp->name, &names->frame))
1721     {
1722       dwarf2_per_objfile->frame.asection = sectp;
1723       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1724     }
1725   else if (section_is_p (sectp->name, &names->eh_frame))
1726     {
1727       flagword aflag = bfd_get_section_flags (abfd, sectp);
1728
1729       if (aflag & SEC_HAS_CONTENTS)
1730         {
1731           dwarf2_per_objfile->eh_frame.asection = sectp;
1732           dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1733         }
1734     }
1735   else if (section_is_p (sectp->name, &names->ranges))
1736     {
1737       dwarf2_per_objfile->ranges.asection = sectp;
1738       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1739     }
1740   else if (section_is_p (sectp->name, &names->types))
1741     {
1742       struct dwarf2_section_info type_section;
1743
1744       memset (&type_section, 0, sizeof (type_section));
1745       type_section.asection = sectp;
1746       type_section.size = bfd_get_section_size (sectp);
1747
1748       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1749                      &type_section);
1750     }
1751   else if (section_is_p (sectp->name, &names->gdb_index))
1752     {
1753       dwarf2_per_objfile->gdb_index.asection = sectp;
1754       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1755     }
1756
1757   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1758       && bfd_section_vma (abfd, sectp) == 0)
1759     dwarf2_per_objfile->has_section_at_zero = 1;
1760 }
1761
1762 /* Decompress a section that was compressed using zlib.  Store the
1763    decompressed buffer, and its size, in OUTBUF and OUTSIZE.  */
1764
1765 static void
1766 zlib_decompress_section (struct objfile *objfile, asection *sectp,
1767                          gdb_byte **outbuf, bfd_size_type *outsize)
1768 {
1769   bfd *abfd = sectp->owner;
1770 #ifndef HAVE_ZLIB_H
1771   error (_("Support for zlib-compressed DWARF data (from '%s') "
1772            "is disabled in this copy of GDB"),
1773          bfd_get_filename (abfd));
1774 #else
1775   bfd_size_type compressed_size = bfd_get_section_size (sectp);
1776   gdb_byte *compressed_buffer = xmalloc (compressed_size);
1777   struct cleanup *cleanup = make_cleanup (xfree, compressed_buffer);
1778   bfd_size_type uncompressed_size;
1779   gdb_byte *uncompressed_buffer;
1780   z_stream strm;
1781   int rc;
1782   int header_size = 12;
1783
1784   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1785       || bfd_bread (compressed_buffer,
1786                     compressed_size, abfd) != compressed_size)
1787     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1788            bfd_get_filename (abfd));
1789
1790   /* Read the zlib header.  In this case, it should be "ZLIB" followed
1791      by the uncompressed section size, 8 bytes in big-endian order.  */
1792   if (compressed_size < header_size
1793       || strncmp (compressed_buffer, "ZLIB", 4) != 0)
1794     error (_("Dwarf Error: Corrupt DWARF ZLIB header from '%s'"),
1795            bfd_get_filename (abfd));
1796   uncompressed_size = compressed_buffer[4]; uncompressed_size <<= 8;
1797   uncompressed_size += compressed_buffer[5]; uncompressed_size <<= 8;
1798   uncompressed_size += compressed_buffer[6]; uncompressed_size <<= 8;
1799   uncompressed_size += compressed_buffer[7]; uncompressed_size <<= 8;
1800   uncompressed_size += compressed_buffer[8]; uncompressed_size <<= 8;
1801   uncompressed_size += compressed_buffer[9]; uncompressed_size <<= 8;
1802   uncompressed_size += compressed_buffer[10]; uncompressed_size <<= 8;
1803   uncompressed_size += compressed_buffer[11];
1804
1805   /* It is possible the section consists of several compressed
1806      buffers concatenated together, so we uncompress in a loop.  */
1807   strm.zalloc = NULL;
1808   strm.zfree = NULL;
1809   strm.opaque = NULL;
1810   strm.avail_in = compressed_size - header_size;
1811   strm.next_in = (Bytef*) compressed_buffer + header_size;
1812   strm.avail_out = uncompressed_size;
1813   uncompressed_buffer = obstack_alloc (&objfile->objfile_obstack,
1814                                        uncompressed_size);
1815   rc = inflateInit (&strm);
1816   while (strm.avail_in > 0)
1817     {
1818       if (rc != Z_OK)
1819         error (_("Dwarf Error: setting up DWARF uncompression in '%s': %d"),
1820                bfd_get_filename (abfd), rc);
1821       strm.next_out = ((Bytef*) uncompressed_buffer
1822                        + (uncompressed_size - strm.avail_out));
1823       rc = inflate (&strm, Z_FINISH);
1824       if (rc != Z_STREAM_END)
1825         error (_("Dwarf Error: zlib error uncompressing from '%s': %d"),
1826                bfd_get_filename (abfd), rc);
1827       rc = inflateReset (&strm);
1828     }
1829   rc = inflateEnd (&strm);
1830   if (rc != Z_OK
1831       || strm.avail_out != 0)
1832     error (_("Dwarf Error: concluding DWARF uncompression in '%s': %d"),
1833            bfd_get_filename (abfd), rc);
1834
1835   do_cleanups (cleanup);
1836   *outbuf = uncompressed_buffer;
1837   *outsize = uncompressed_size;
1838 #endif
1839 }
1840
1841 /* A helper function that decides whether a section is empty,
1842    or not present.  */
1843
1844 static int
1845 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1846 {
1847   return info->asection == NULL || info->size == 0;
1848 }
1849
1850 /* Read the contents of the section INFO.
1851    OBJFILE is the main object file, but not necessarily the file where
1852    the section comes from.  E.g., for DWO files INFO->asection->owner
1853    is the bfd of the DWO file.
1854    If the section is compressed, uncompress it before returning.  */
1855
1856 static void
1857 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1858 {
1859   asection *sectp = info->asection;
1860   bfd *abfd;
1861   gdb_byte *buf, *retbuf;
1862   unsigned char header[4];
1863
1864   if (info->readin)
1865     return;
1866   info->buffer = NULL;
1867   info->map_addr = NULL;
1868   info->readin = 1;
1869
1870   if (dwarf2_section_empty_p (info))
1871     return;
1872
1873   /* Note that ABFD may not be from OBJFILE, e.g. a DWO section.  */
1874   abfd = sectp->owner;
1875
1876   /* Check if the file has a 4-byte header indicating compression.  */
1877   if (info->size > sizeof (header)
1878       && bfd_seek (abfd, sectp->filepos, SEEK_SET) == 0
1879       && bfd_bread (header, sizeof (header), abfd) == sizeof (header))
1880     {
1881       /* Upon decompression, update the buffer and its size.  */
1882       if (strncmp (header, "ZLIB", sizeof (header)) == 0)
1883         {
1884           zlib_decompress_section (objfile, sectp, &info->buffer,
1885                                    &info->size);
1886           return;
1887         }
1888     }
1889
1890 #ifdef HAVE_MMAP
1891   if (pagesize == 0)
1892     pagesize = getpagesize ();
1893
1894   /* Only try to mmap sections which are large enough: we don't want to
1895      waste space due to fragmentation.  Also, only try mmap for sections
1896      without relocations.  */
1897
1898   if (info->size > 4 * pagesize && (sectp->flags & SEC_RELOC) == 0)
1899     {
1900       info->buffer = bfd_mmap (abfd, 0, info->size, PROT_READ,
1901                          MAP_PRIVATE, sectp->filepos,
1902                          &info->map_addr, &info->map_len);
1903
1904       if ((caddr_t)info->buffer != MAP_FAILED)
1905         {
1906 #if HAVE_POSIX_MADVISE
1907           posix_madvise (info->map_addr, info->map_len, POSIX_MADV_WILLNEED);
1908 #endif
1909           return;
1910         }
1911     }
1912 #endif
1913
1914   /* If we get here, we are a normal, not-compressed section.  */
1915   info->buffer = buf
1916     = obstack_alloc (&objfile->objfile_obstack, info->size);
1917
1918   /* When debugging .o files, we may need to apply relocations; see
1919      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1920      We never compress sections in .o files, so we only need to
1921      try this when the section is not compressed.  */
1922   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1923   if (retbuf != NULL)
1924     {
1925       info->buffer = retbuf;
1926       return;
1927     }
1928
1929   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1930       || bfd_bread (buf, info->size, abfd) != info->size)
1931     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1932            bfd_get_filename (abfd));
1933 }
1934
1935 /* A helper function that returns the size of a section in a safe way.
1936    If you are positive that the section has been read before using the
1937    size, then it is safe to refer to the dwarf2_section_info object's
1938    "size" field directly.  In other cases, you must call this
1939    function, because for compressed sections the size field is not set
1940    correctly until the section has been read.  */
1941
1942 static bfd_size_type
1943 dwarf2_section_size (struct objfile *objfile,
1944                      struct dwarf2_section_info *info)
1945 {
1946   if (!info->readin)
1947     dwarf2_read_section (objfile, info);
1948   return info->size;
1949 }
1950
1951 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1952    SECTION_NAME.  */
1953
1954 void
1955 dwarf2_get_section_info (struct objfile *objfile,
1956                          enum dwarf2_section_enum sect,
1957                          asection **sectp, gdb_byte **bufp,
1958                          bfd_size_type *sizep)
1959 {
1960   struct dwarf2_per_objfile *data
1961     = objfile_data (objfile, dwarf2_objfile_data_key);
1962   struct dwarf2_section_info *info;
1963
1964   /* We may see an objfile without any DWARF, in which case we just
1965      return nothing.  */
1966   if (data == NULL)
1967     {
1968       *sectp = NULL;
1969       *bufp = NULL;
1970       *sizep = 0;
1971       return;
1972     }
1973   switch (sect)
1974     {
1975     case DWARF2_DEBUG_FRAME:
1976       info = &data->frame;
1977       break;
1978     case DWARF2_EH_FRAME:
1979       info = &data->eh_frame;
1980       break;
1981     default:
1982       gdb_assert_not_reached ("unexpected section");
1983     }
1984
1985   dwarf2_read_section (objfile, info);
1986
1987   *sectp = info->asection;
1988   *bufp = info->buffer;
1989   *sizep = info->size;
1990 }
1991
1992 \f
1993 /* DWARF quick_symbols_functions support.  */
1994
1995 /* TUs can share .debug_line entries, and there can be a lot more TUs than
1996    unique line tables, so we maintain a separate table of all .debug_line
1997    derived entries to support the sharing.
1998    All the quick functions need is the list of file names.  We discard the
1999    line_header when we're done and don't need to record it here.  */
2000 struct quick_file_names
2001 {
2002   /* The offset in .debug_line of the line table.  We hash on this.  */
2003   unsigned int offset;
2004
2005   /* The number of entries in file_names, real_names.  */
2006   unsigned int num_file_names;
2007
2008   /* The file names from the line table, after being run through
2009      file_full_name.  */
2010   const char **file_names;
2011
2012   /* The file names from the line table after being run through
2013      gdb_realpath.  These are computed lazily.  */
2014   const char **real_names;
2015 };
2016
2017 /* When using the index (and thus not using psymtabs), each CU has an
2018    object of this type.  This is used to hold information needed by
2019    the various "quick" methods.  */
2020 struct dwarf2_per_cu_quick_data
2021 {
2022   /* The file table.  This can be NULL if there was no file table
2023      or it's currently not read in.
2024      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2025   struct quick_file_names *file_names;
2026
2027   /* The corresponding symbol table.  This is NULL if symbols for this
2028      CU have not yet been read.  */
2029   struct symtab *symtab;
2030
2031   /* A temporary mark bit used when iterating over all CUs in
2032      expand_symtabs_matching.  */
2033   unsigned int mark : 1;
2034
2035   /* True if we've tried to read the file table and found there isn't one.
2036      There will be no point in trying to read it again next time.  */
2037   unsigned int no_file_data : 1;
2038 };
2039
2040 /* Hash function for a quick_file_names.  */
2041
2042 static hashval_t
2043 hash_file_name_entry (const void *e)
2044 {
2045   const struct quick_file_names *file_data = e;
2046
2047   return file_data->offset;
2048 }
2049
2050 /* Equality function for a quick_file_names.  */
2051
2052 static int
2053 eq_file_name_entry (const void *a, const void *b)
2054 {
2055   const struct quick_file_names *ea = a;
2056   const struct quick_file_names *eb = b;
2057
2058   return ea->offset == eb->offset;
2059 }
2060
2061 /* Delete function for a quick_file_names.  */
2062
2063 static void
2064 delete_file_name_entry (void *e)
2065 {
2066   struct quick_file_names *file_data = e;
2067   int i;
2068
2069   for (i = 0; i < file_data->num_file_names; ++i)
2070     {
2071       xfree ((void*) file_data->file_names[i]);
2072       if (file_data->real_names)
2073         xfree ((void*) file_data->real_names[i]);
2074     }
2075
2076   /* The space for the struct itself lives on objfile_obstack,
2077      so we don't free it here.  */
2078 }
2079
2080 /* Create a quick_file_names hash table.  */
2081
2082 static htab_t
2083 create_quick_file_names_table (unsigned int nr_initial_entries)
2084 {
2085   return htab_create_alloc (nr_initial_entries,
2086                             hash_file_name_entry, eq_file_name_entry,
2087                             delete_file_name_entry, xcalloc, xfree);
2088 }
2089
2090 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2091    have to be created afterwards.  You should call age_cached_comp_units after
2092    processing PER_CU->CU.  dw2_setup must have been already called.  */
2093
2094 static void
2095 load_cu (struct dwarf2_per_cu_data *per_cu)
2096 {
2097   if (per_cu->is_debug_types)
2098     load_full_type_unit (per_cu);
2099   else
2100     load_full_comp_unit (per_cu, language_minimal);
2101
2102   gdb_assert (per_cu->cu != NULL);
2103
2104   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2105 }
2106
2107 /* Read in the symbols for PER_CU.  */
2108
2109 static void
2110 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2111 {
2112   struct cleanup *back_to;
2113
2114   /* Skip type_unit_groups, reading the type units they contain
2115      is handled elsewhere.  */
2116   if (IS_TYPE_UNIT_GROUP (per_cu))
2117     return;
2118
2119   back_to = make_cleanup (dwarf2_release_queue, NULL);
2120
2121   if (dwarf2_per_objfile->using_index
2122       ? per_cu->v.quick->symtab == NULL
2123       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2124     {
2125       queue_comp_unit (per_cu, language_minimal);
2126       load_cu (per_cu);
2127     }
2128
2129   process_queue ();
2130
2131   /* Age the cache, releasing compilation units that have not
2132      been used recently.  */
2133   age_cached_comp_units ();
2134
2135   do_cleanups (back_to);
2136 }
2137
2138 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2139    the objfile from which this CU came.  Returns the resulting symbol
2140    table.  */
2141
2142 static struct symtab *
2143 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2144 {
2145   gdb_assert (dwarf2_per_objfile->using_index);
2146   if (!per_cu->v.quick->symtab)
2147     {
2148       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2149       increment_reading_symtab ();
2150       dw2_do_instantiate_symtab (per_cu);
2151       process_cu_includes ();
2152       do_cleanups (back_to);
2153     }
2154   return per_cu->v.quick->symtab;
2155 }
2156
2157 /* Return the CU given its index.
2158
2159    This is intended for loops like:
2160
2161    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2162                     + dwarf2_per_objfile->n_type_units); ++i)
2163      {
2164        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2165
2166        ...;
2167      }
2168 */
2169
2170 static struct dwarf2_per_cu_data *
2171 dw2_get_cu (int index)
2172 {
2173   if (index >= dwarf2_per_objfile->n_comp_units)
2174     {
2175       struct dwarf2_per_cu_data *per_cu;
2176
2177       index -= dwarf2_per_objfile->n_comp_units;
2178       per_cu = &dwarf2_per_objfile->all_type_units[index]->per_cu;
2179       gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
2180       return per_cu;
2181     }
2182
2183   return dwarf2_per_objfile->all_comp_units[index];
2184 }
2185
2186 /* Return the primary CU given its index.
2187    The difference between this function and dw2_get_cu is in the handling
2188    of type units (TUs).  Here we return the type_unit_group object.
2189
2190    This is intended for loops like:
2191
2192    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2193                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2194      {
2195        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2196
2197        ...;
2198      }
2199 */
2200
2201 static struct dwarf2_per_cu_data *
2202 dw2_get_primary_cu (int index)
2203 {
2204   if (index >= dwarf2_per_objfile->n_comp_units)
2205     {
2206       struct dwarf2_per_cu_data *per_cu;
2207
2208       index -= dwarf2_per_objfile->n_comp_units;
2209       per_cu = dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2210       gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
2211       return per_cu;
2212     }
2213
2214   return dwarf2_per_objfile->all_comp_units[index];
2215 }
2216
2217 /* A helper function that knows how to read a 64-bit value in a way
2218    that doesn't make gdb die.  Returns 1 if the conversion went ok, 0
2219    otherwise.  */
2220
2221 static int
2222 extract_cu_value (const char *bytes, ULONGEST *result)
2223 {
2224   if (sizeof (ULONGEST) < 8)
2225     {
2226       int i;
2227
2228       /* Ignore the upper 4 bytes if they are all zero.  */
2229       for (i = 0; i < 4; ++i)
2230         if (bytes[i + 4] != 0)
2231           return 0;
2232
2233       *result = extract_unsigned_integer (bytes, 4, BFD_ENDIAN_LITTLE);
2234     }
2235   else
2236     *result = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2237   return 1;
2238 }
2239
2240 /* Read the CU list from the mapped index, and use it to create all
2241    the CU objects for this objfile.  Return 0 if something went wrong,
2242    1 if everything went ok.  */
2243
2244 static int
2245 create_cus_from_index (struct objfile *objfile, const gdb_byte *cu_list,
2246                        offset_type cu_list_elements)
2247 {
2248   offset_type i;
2249
2250   dwarf2_per_objfile->n_comp_units = cu_list_elements / 2;
2251   dwarf2_per_objfile->all_comp_units
2252     = obstack_alloc (&objfile->objfile_obstack,
2253                      dwarf2_per_objfile->n_comp_units
2254                      * sizeof (struct dwarf2_per_cu_data *));
2255
2256   for (i = 0; i < cu_list_elements; i += 2)
2257     {
2258       struct dwarf2_per_cu_data *the_cu;
2259       ULONGEST offset, length;
2260
2261       if (!extract_cu_value (cu_list, &offset)
2262           || !extract_cu_value (cu_list + 8, &length))
2263         return 0;
2264       cu_list += 2 * 8;
2265
2266       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2267                                struct dwarf2_per_cu_data);
2268       the_cu->offset.sect_off = offset;
2269       the_cu->length = length;
2270       the_cu->objfile = objfile;
2271       the_cu->info_or_types_section = &dwarf2_per_objfile->info;
2272       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2273                                         struct dwarf2_per_cu_quick_data);
2274       dwarf2_per_objfile->all_comp_units[i / 2] = the_cu;
2275     }
2276
2277   return 1;
2278 }
2279
2280 /* Create the signatured type hash table from the index.  */
2281
2282 static int
2283 create_signatured_type_table_from_index (struct objfile *objfile,
2284                                          struct dwarf2_section_info *section,
2285                                          const gdb_byte *bytes,
2286                                          offset_type elements)
2287 {
2288   offset_type i;
2289   htab_t sig_types_hash;
2290
2291   dwarf2_per_objfile->n_type_units = elements / 3;
2292   dwarf2_per_objfile->all_type_units
2293     = obstack_alloc (&objfile->objfile_obstack,
2294                      dwarf2_per_objfile->n_type_units
2295                      * sizeof (struct signatured_type *));
2296
2297   sig_types_hash = allocate_signatured_type_table (objfile);
2298
2299   for (i = 0; i < elements; i += 3)
2300     {
2301       struct signatured_type *sig_type;
2302       ULONGEST offset, type_offset_in_tu, signature;
2303       void **slot;
2304
2305       if (!extract_cu_value (bytes, &offset)
2306           || !extract_cu_value (bytes + 8, &type_offset_in_tu))
2307         return 0;
2308       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2309       bytes += 3 * 8;
2310
2311       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2312                                  struct signatured_type);
2313       sig_type->signature = signature;
2314       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2315       sig_type->per_cu.is_debug_types = 1;
2316       sig_type->per_cu.info_or_types_section = section;
2317       sig_type->per_cu.offset.sect_off = offset;
2318       sig_type->per_cu.objfile = objfile;
2319       sig_type->per_cu.v.quick
2320         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2321                           struct dwarf2_per_cu_quick_data);
2322
2323       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2324       *slot = sig_type;
2325
2326       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2327     }
2328
2329   dwarf2_per_objfile->signatured_types = sig_types_hash;
2330
2331   return 1;
2332 }
2333
2334 /* Read the address map data from the mapped index, and use it to
2335    populate the objfile's psymtabs_addrmap.  */
2336
2337 static void
2338 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2339 {
2340   const gdb_byte *iter, *end;
2341   struct obstack temp_obstack;
2342   struct addrmap *mutable_map;
2343   struct cleanup *cleanup;
2344   CORE_ADDR baseaddr;
2345
2346   obstack_init (&temp_obstack);
2347   cleanup = make_cleanup_obstack_free (&temp_obstack);
2348   mutable_map = addrmap_create_mutable (&temp_obstack);
2349
2350   iter = index->address_table;
2351   end = iter + index->address_table_size;
2352
2353   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2354
2355   while (iter < end)
2356     {
2357       ULONGEST hi, lo, cu_index;
2358       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2359       iter += 8;
2360       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2361       iter += 8;
2362       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2363       iter += 4;
2364       
2365       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2366                          dw2_get_cu (cu_index));
2367     }
2368
2369   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2370                                                     &objfile->objfile_obstack);
2371   do_cleanups (cleanup);
2372 }
2373
2374 /* The hash function for strings in the mapped index.  This is the same as
2375    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2376    implementation.  This is necessary because the hash function is tied to the
2377    format of the mapped index file.  The hash values do not have to match with
2378    SYMBOL_HASH_NEXT.
2379    
2380    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2381
2382 static hashval_t
2383 mapped_index_string_hash (int index_version, const void *p)
2384 {
2385   const unsigned char *str = (const unsigned char *) p;
2386   hashval_t r = 0;
2387   unsigned char c;
2388
2389   while ((c = *str++) != 0)
2390     {
2391       if (index_version >= 5)
2392         c = tolower (c);
2393       r = r * 67 + c - 113;
2394     }
2395
2396   return r;
2397 }
2398
2399 /* Find a slot in the mapped index INDEX for the object named NAME.
2400    If NAME is found, set *VEC_OUT to point to the CU vector in the
2401    constant pool and return 1.  If NAME cannot be found, return 0.  */
2402
2403 static int
2404 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2405                           offset_type **vec_out)
2406 {
2407   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2408   offset_type hash;
2409   offset_type slot, step;
2410   int (*cmp) (const char *, const char *);
2411
2412   if (current_language->la_language == language_cplus
2413       || current_language->la_language == language_java
2414       || current_language->la_language == language_fortran)
2415     {
2416       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2417          not contain any.  */
2418       const char *paren = strchr (name, '(');
2419
2420       if (paren)
2421         {
2422           char *dup;
2423
2424           dup = xmalloc (paren - name + 1);
2425           memcpy (dup, name, paren - name);
2426           dup[paren - name] = 0;
2427
2428           make_cleanup (xfree, dup);
2429           name = dup;
2430         }
2431     }
2432
2433   /* Index version 4 did not support case insensitive searches.  But the
2434      indices for case insensitive languages are built in lowercase, therefore
2435      simulate our NAME being searched is also lowercased.  */
2436   hash = mapped_index_string_hash ((index->version == 4
2437                                     && case_sensitivity == case_sensitive_off
2438                                     ? 5 : index->version),
2439                                    name);
2440
2441   slot = hash & (index->symbol_table_slots - 1);
2442   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2443   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2444
2445   for (;;)
2446     {
2447       /* Convert a slot number to an offset into the table.  */
2448       offset_type i = 2 * slot;
2449       const char *str;
2450       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2451         {
2452           do_cleanups (back_to);
2453           return 0;
2454         }
2455
2456       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2457       if (!cmp (name, str))
2458         {
2459           *vec_out = (offset_type *) (index->constant_pool
2460                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2461           do_cleanups (back_to);
2462           return 1;
2463         }
2464
2465       slot = (slot + step) & (index->symbol_table_slots - 1);
2466     }
2467 }
2468
2469 /* Read the index file.  If everything went ok, initialize the "quick"
2470    elements of all the CUs and return 1.  Otherwise, return 0.  */
2471
2472 static int
2473 dwarf2_read_index (struct objfile *objfile)
2474 {
2475   char *addr;
2476   struct mapped_index *map;
2477   offset_type *metadata;
2478   const gdb_byte *cu_list;
2479   const gdb_byte *types_list = NULL;
2480   offset_type version, cu_list_elements;
2481   offset_type types_list_elements = 0;
2482   int i;
2483
2484   if (dwarf2_section_empty_p (&dwarf2_per_objfile->gdb_index))
2485     return 0;
2486
2487   /* Older elfutils strip versions could keep the section in the main
2488      executable while splitting it for the separate debug info file.  */
2489   if ((bfd_get_file_flags (dwarf2_per_objfile->gdb_index.asection)
2490        & SEC_HAS_CONTENTS) == 0)
2491     return 0;
2492
2493   dwarf2_read_section (objfile, &dwarf2_per_objfile->gdb_index);
2494
2495   addr = dwarf2_per_objfile->gdb_index.buffer;
2496   /* Version check.  */
2497   version = MAYBE_SWAP (*(offset_type *) addr);
2498   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2499      causes the index to behave very poorly for certain requests.  Version 3
2500      contained incomplete addrmap.  So, it seems better to just ignore such
2501      indices.  */
2502   if (version < 4)
2503     {
2504       static int warning_printed = 0;
2505       if (!warning_printed)
2506         {
2507           warning (_("Skipping obsolete .gdb_index section in %s."),
2508                    objfile->name);
2509           warning_printed = 1;
2510         }
2511       return 0;
2512     }
2513   /* Index version 4 uses a different hash function than index version
2514      5 and later.
2515
2516      Versions earlier than 6 did not emit psymbols for inlined
2517      functions.  Using these files will cause GDB not to be able to
2518      set breakpoints on inlined functions by name, so we ignore these
2519      indices unless the --use-deprecated-index-sections command line
2520      option was supplied.  */
2521   if (version < 6 && !use_deprecated_index_sections)
2522     {
2523       static int warning_printed = 0;
2524       if (!warning_printed)
2525         {
2526           warning (_("Skipping deprecated .gdb_index section in %s, pass "
2527                      "--use-deprecated-index-sections to use them anyway"),
2528                    objfile->name);
2529           warning_printed = 1;
2530         }
2531       return 0;
2532     }
2533   /* Indexes with higher version than the one supported by GDB may be no
2534      longer backward compatible.  */
2535   if (version > 7)
2536     return 0;
2537
2538   map = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct mapped_index);
2539   map->version = version;
2540   map->total_size = dwarf2_per_objfile->gdb_index.size;
2541
2542   metadata = (offset_type *) (addr + sizeof (offset_type));
2543
2544   i = 0;
2545   cu_list = addr + MAYBE_SWAP (metadata[i]);
2546   cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2547                       / 8);
2548   ++i;
2549
2550   types_list = addr + MAYBE_SWAP (metadata[i]);
2551   types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2552                           - MAYBE_SWAP (metadata[i]))
2553                          / 8);
2554   ++i;
2555
2556   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2557   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2558                              - MAYBE_SWAP (metadata[i]));
2559   ++i;
2560
2561   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2562   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2563                               - MAYBE_SWAP (metadata[i]))
2564                              / (2 * sizeof (offset_type)));
2565   ++i;
2566
2567   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2568
2569   /* Don't use the index if it's empty.  */
2570   if (map->symbol_table_slots == 0)
2571     return 0;
2572
2573   if (!create_cus_from_index (objfile, cu_list, cu_list_elements))
2574     return 0;
2575
2576   if (types_list_elements)
2577     {
2578       struct dwarf2_section_info *section;
2579
2580       /* We can only handle a single .debug_types when we have an
2581          index.  */
2582       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2583         return 0;
2584
2585       section = VEC_index (dwarf2_section_info_def,
2586                            dwarf2_per_objfile->types, 0);
2587
2588       if (!create_signatured_type_table_from_index (objfile, section,
2589                                                     types_list,
2590                                                     types_list_elements))
2591         return 0;
2592     }
2593
2594   create_addrmap_from_index (objfile, map);
2595
2596   dwarf2_per_objfile->index_table = map;
2597   dwarf2_per_objfile->using_index = 1;
2598   dwarf2_per_objfile->quick_file_names_table =
2599     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2600
2601   return 1;
2602 }
2603
2604 /* A helper for the "quick" functions which sets the global
2605    dwarf2_per_objfile according to OBJFILE.  */
2606
2607 static void
2608 dw2_setup (struct objfile *objfile)
2609 {
2610   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2611   gdb_assert (dwarf2_per_objfile);
2612 }
2613
2614 /* Reader function for dw2_build_type_unit_groups.  */
2615
2616 static void
2617 dw2_build_type_unit_groups_reader (const struct die_reader_specs *reader,
2618                                    gdb_byte *info_ptr,
2619                                    struct die_info *type_unit_die,
2620                                    int has_children,
2621                                    void *data)
2622 {
2623   struct dwarf2_cu *cu = reader->cu;
2624   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
2625   struct attribute *attr;
2626   struct type_unit_group *tu_group;
2627
2628   gdb_assert (data == NULL);
2629
2630   if (! has_children)
2631     return;
2632
2633   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
2634   /* Call this for its side-effect of creating the associated
2635      struct type_unit_group if it doesn't already exist.  */
2636   tu_group = get_type_unit_group (per_cu, attr);
2637 }
2638
2639 /* Build dwarf2_per_objfile->type_unit_groups.
2640    This function may be called multiple times.  */
2641
2642 static void
2643 dw2_build_type_unit_groups (void)
2644 {
2645   if (dwarf2_per_objfile->type_unit_groups == NULL)
2646     build_type_unit_groups (dw2_build_type_unit_groups_reader, NULL);
2647 }
2648
2649 /* die_reader_func for dw2_get_file_names.  */
2650
2651 static void
2652 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2653                            gdb_byte *info_ptr,
2654                            struct die_info *comp_unit_die,
2655                            int has_children,
2656                            void *data)
2657 {
2658   struct dwarf2_cu *cu = reader->cu;
2659   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2660   struct objfile *objfile = dwarf2_per_objfile->objfile;
2661   struct line_header *lh;
2662   struct attribute *attr;
2663   int i;
2664   char *name, *comp_dir;
2665   void **slot;
2666   struct quick_file_names *qfn;
2667   unsigned int line_offset;
2668
2669   /* Our callers never want to match partial units -- instead they
2670      will match the enclosing full CU.  */
2671   if (comp_unit_die->tag == DW_TAG_partial_unit)
2672     {
2673       this_cu->v.quick->no_file_data = 1;
2674       return;
2675     }
2676
2677   lh = NULL;
2678   slot = NULL;
2679   line_offset = 0;
2680
2681   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2682   if (attr)
2683     {
2684       struct quick_file_names find_entry;
2685
2686       line_offset = DW_UNSND (attr);
2687
2688       /* We may have already read in this line header (TU line header sharing).
2689          If we have we're done.  */
2690       find_entry.offset = line_offset;
2691       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2692                              &find_entry, INSERT);
2693       if (*slot != NULL)
2694         {
2695           this_cu->v.quick->file_names = *slot;
2696           return;
2697         }
2698
2699       lh = dwarf_decode_line_header (line_offset, cu);
2700     }
2701   if (lh == NULL)
2702     {
2703       this_cu->v.quick->no_file_data = 1;
2704       return;
2705     }
2706
2707   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2708   qfn->offset = line_offset;
2709   gdb_assert (slot != NULL);
2710   *slot = qfn;
2711
2712   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2713
2714   qfn->num_file_names = lh->num_file_names;
2715   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2716                                    lh->num_file_names * sizeof (char *));
2717   for (i = 0; i < lh->num_file_names; ++i)
2718     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2719   qfn->real_names = NULL;
2720
2721   free_line_header (lh);
2722
2723   this_cu->v.quick->file_names = qfn;
2724 }
2725
2726 /* A helper for the "quick" functions which attempts to read the line
2727    table for THIS_CU.  */
2728
2729 static struct quick_file_names *
2730 dw2_get_file_names (struct objfile *objfile,
2731                     struct dwarf2_per_cu_data *this_cu)
2732 {
2733   /* For TUs this should only be called on the parent group.  */
2734   if (this_cu->is_debug_types)
2735     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2736
2737   if (this_cu->v.quick->file_names != NULL)
2738     return this_cu->v.quick->file_names;
2739   /* If we know there is no line data, no point in looking again.  */
2740   if (this_cu->v.quick->no_file_data)
2741     return NULL;
2742
2743   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2744      in the stub for CUs, there's is no need to lookup the DWO file.
2745      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2746      DWO file.  */
2747   if (this_cu->is_debug_types)
2748     init_cutu_and_read_dies (this_cu, NULL, 0, 0,
2749                              dw2_get_file_names_reader, NULL);
2750   else
2751     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2752
2753   if (this_cu->v.quick->no_file_data)
2754     return NULL;
2755   return this_cu->v.quick->file_names;
2756 }
2757
2758 /* A helper for the "quick" functions which computes and caches the
2759    real path for a given file name from the line table.  */
2760
2761 static const char *
2762 dw2_get_real_path (struct objfile *objfile,
2763                    struct quick_file_names *qfn, int index)
2764 {
2765   if (qfn->real_names == NULL)
2766     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2767                                       qfn->num_file_names, sizeof (char *));
2768
2769   if (qfn->real_names[index] == NULL)
2770     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2771
2772   return qfn->real_names[index];
2773 }
2774
2775 static struct symtab *
2776 dw2_find_last_source_symtab (struct objfile *objfile)
2777 {
2778   int index;
2779
2780   dw2_setup (objfile);
2781   index = dwarf2_per_objfile->n_comp_units - 1;
2782   return dw2_instantiate_symtab (dw2_get_cu (index));
2783 }
2784
2785 /* Traversal function for dw2_forget_cached_source_info.  */
2786
2787 static int
2788 dw2_free_cached_file_names (void **slot, void *info)
2789 {
2790   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2791
2792   if (file_data->real_names)
2793     {
2794       int i;
2795
2796       for (i = 0; i < file_data->num_file_names; ++i)
2797         {
2798           xfree ((void*) file_data->real_names[i]);
2799           file_data->real_names[i] = NULL;
2800         }
2801     }
2802
2803   return 1;
2804 }
2805
2806 static void
2807 dw2_forget_cached_source_info (struct objfile *objfile)
2808 {
2809   dw2_setup (objfile);
2810
2811   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
2812                           dw2_free_cached_file_names, NULL);
2813 }
2814
2815 /* Helper function for dw2_map_symtabs_matching_filename that expands
2816    the symtabs and calls the iterator.  */
2817
2818 static int
2819 dw2_map_expand_apply (struct objfile *objfile,
2820                       struct dwarf2_per_cu_data *per_cu,
2821                       const char *name,
2822                       const char *full_path, const char *real_path,
2823                       int (*callback) (struct symtab *, void *),
2824                       void *data)
2825 {
2826   struct symtab *last_made = objfile->symtabs;
2827
2828   /* Don't visit already-expanded CUs.  */
2829   if (per_cu->v.quick->symtab)
2830     return 0;
2831
2832   /* This may expand more than one symtab, and we want to iterate over
2833      all of them.  */
2834   dw2_instantiate_symtab (per_cu);
2835
2836   return iterate_over_some_symtabs (name, full_path, real_path, callback, data,
2837                                     objfile->symtabs, last_made);
2838 }
2839
2840 /* Implementation of the map_symtabs_matching_filename method.  */
2841
2842 static int
2843 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
2844                                    const char *full_path, const char *real_path,
2845                                    int (*callback) (struct symtab *, void *),
2846                                    void *data)
2847 {
2848   int i;
2849   const char *name_basename = lbasename (name);
2850   int name_len = strlen (name);
2851   int is_abs = IS_ABSOLUTE_PATH (name);
2852
2853   dw2_setup (objfile);
2854
2855   dw2_build_type_unit_groups ();
2856
2857   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2858                    + dwarf2_per_objfile->n_type_unit_groups); ++i)
2859     {
2860       int j;
2861       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2862       struct quick_file_names *file_data;
2863
2864       /* We only need to look at symtabs not already expanded.  */
2865       if (per_cu->v.quick->symtab)
2866         continue;
2867
2868       file_data = dw2_get_file_names (objfile, per_cu);
2869       if (file_data == NULL)
2870         continue;
2871
2872       for (j = 0; j < file_data->num_file_names; ++j)
2873         {
2874           const char *this_name = file_data->file_names[j];
2875
2876           if (FILENAME_CMP (name, this_name) == 0
2877               || (!is_abs && compare_filenames_for_search (this_name,
2878                                                            name, name_len)))
2879             {
2880               if (dw2_map_expand_apply (objfile, per_cu,
2881                                         name, full_path, real_path,
2882                                         callback, data))
2883                 return 1;
2884             }
2885
2886           /* Before we invoke realpath, which can get expensive when many
2887              files are involved, do a quick comparison of the basenames.  */
2888           if (! basenames_may_differ
2889               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
2890             continue;
2891
2892           if (full_path != NULL)
2893             {
2894               const char *this_real_name = dw2_get_real_path (objfile,
2895                                                               file_data, j);
2896
2897               if (this_real_name != NULL
2898                   && (FILENAME_CMP (full_path, this_real_name) == 0
2899                       || (!is_abs
2900                           && compare_filenames_for_search (this_real_name,
2901                                                            name, name_len))))
2902                 {
2903                   if (dw2_map_expand_apply (objfile, per_cu,
2904                                             name, full_path, real_path,
2905                                             callback, data))
2906                     return 1;
2907                 }
2908             }
2909
2910           if (real_path != NULL)
2911             {
2912               const char *this_real_name = dw2_get_real_path (objfile,
2913                                                               file_data, j);
2914
2915               if (this_real_name != NULL
2916                   && (FILENAME_CMP (real_path, this_real_name) == 0
2917                       || (!is_abs
2918                           && compare_filenames_for_search (this_real_name,
2919                                                            name, name_len))))
2920                 {
2921                   if (dw2_map_expand_apply (objfile, per_cu,
2922                                             name, full_path, real_path,
2923                                             callback, data))
2924                     return 1;
2925                 }
2926             }
2927         }
2928     }
2929
2930   return 0;
2931 }
2932
2933 static struct symtab *
2934 dw2_lookup_symbol (struct objfile *objfile, int block_index,
2935                    const char *name, domain_enum domain)
2936 {
2937   /* We do all the work in the pre_expand_symtabs_matching hook
2938      instead.  */
2939   return NULL;
2940 }
2941
2942 /* A helper function that expands all symtabs that hold an object
2943    named NAME.  If WANT_SPECIFIC_BLOCK is non-zero, only look for
2944    symbols in block BLOCK_KIND.  */
2945
2946 static void
2947 dw2_do_expand_symtabs_matching (struct objfile *objfile,
2948                                 int want_specific_block,
2949                                 enum block_enum block_kind,
2950                                 const char *name, domain_enum domain)
2951 {
2952   struct mapped_index *index;
2953
2954   dw2_setup (objfile);
2955
2956   index = dwarf2_per_objfile->index_table;
2957
2958   /* index_table is NULL if OBJF_READNOW.  */
2959   if (index)
2960     {
2961       offset_type *vec;
2962
2963       if (find_slot_in_mapped_hash (index, name, &vec))
2964         {
2965           offset_type i, len = MAYBE_SWAP (*vec);
2966           for (i = 0; i < len; ++i)
2967             {
2968               offset_type cu_index_and_attrs = MAYBE_SWAP (vec[i + 1]);
2969               offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
2970               struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
2971               int want_static = block_kind != GLOBAL_BLOCK;
2972               /* This value is only valid for index versions >= 7.  */
2973               int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
2974               gdb_index_symbol_kind symbol_kind =
2975                 GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
2976
2977               if (want_specific_block
2978                   && index->version >= 7
2979                   && want_static != is_static)
2980                 continue;
2981
2982               /* Only check the symbol's kind if it has one.
2983                  Indices prior to version 7 don't record it.  */
2984               if (index->version >= 7)
2985                 {
2986                   switch (domain)
2987                     {
2988                     case VAR_DOMAIN:
2989                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
2990                           && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
2991                           /* Some types are also in VAR_DOMAIN.  */
2992                           && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
2993                         continue;
2994                       break;
2995                     case STRUCT_DOMAIN:
2996                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
2997                         continue;
2998                       break;
2999                     case LABEL_DOMAIN:
3000                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3001                         continue;
3002                       break;
3003                     default:
3004                       break;
3005                     }
3006                 }
3007
3008               dw2_instantiate_symtab (per_cu);
3009             }
3010         }
3011     }
3012 }
3013
3014 static void
3015 dw2_pre_expand_symtabs_matching (struct objfile *objfile,
3016                                  enum block_enum block_kind, const char *name,
3017                                  domain_enum domain)
3018 {
3019   dw2_do_expand_symtabs_matching (objfile, 1, block_kind, name, domain);
3020 }
3021
3022 static void
3023 dw2_print_stats (struct objfile *objfile)
3024 {
3025   int i, count;
3026
3027   dw2_setup (objfile);
3028   count = 0;
3029   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3030                    + dwarf2_per_objfile->n_type_units); ++i)
3031     {
3032       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3033
3034       if (!per_cu->v.quick->symtab)
3035         ++count;
3036     }
3037   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3038 }
3039
3040 static void
3041 dw2_dump (struct objfile *objfile)
3042 {
3043   /* Nothing worth printing.  */
3044 }
3045
3046 static void
3047 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3048               struct section_offsets *delta)
3049 {
3050   /* There's nothing to relocate here.  */
3051 }
3052
3053 static void
3054 dw2_expand_symtabs_for_function (struct objfile *objfile,
3055                                  const char *func_name)
3056 {
3057   /* Note: It doesn't matter what we pass for block_kind here.  */
3058   dw2_do_expand_symtabs_matching (objfile, 0, GLOBAL_BLOCK, func_name,
3059                                   VAR_DOMAIN);
3060 }
3061
3062 static void
3063 dw2_expand_all_symtabs (struct objfile *objfile)
3064 {
3065   int i;
3066
3067   dw2_setup (objfile);
3068
3069   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3070                    + dwarf2_per_objfile->n_type_units); ++i)
3071     {
3072       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3073
3074       dw2_instantiate_symtab (per_cu);
3075     }
3076 }
3077
3078 static void
3079 dw2_expand_symtabs_with_filename (struct objfile *objfile,
3080                                   const char *filename)
3081 {
3082   int i;
3083
3084   dw2_setup (objfile);
3085
3086   /* We don't need to consider type units here.
3087      This is only called for examining code, e.g. expand_line_sal.
3088      There can be an order of magnitude (or more) more type units
3089      than comp units, and we avoid them if we can.  */
3090
3091   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3092     {
3093       int j;
3094       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3095       struct quick_file_names *file_data;
3096
3097       /* We only need to look at symtabs not already expanded.  */
3098       if (per_cu->v.quick->symtab)
3099         continue;
3100
3101       file_data = dw2_get_file_names (objfile, per_cu);
3102       if (file_data == NULL)
3103         continue;
3104
3105       for (j = 0; j < file_data->num_file_names; ++j)
3106         {
3107           const char *this_name = file_data->file_names[j];
3108           if (FILENAME_CMP (this_name, filename) == 0)
3109             {
3110               dw2_instantiate_symtab (per_cu);
3111               break;
3112             }
3113         }
3114     }
3115 }
3116
3117 /* A helper function for dw2_find_symbol_file that finds the primary
3118    file name for a given CU.  This is a die_reader_func.  */
3119
3120 static void
3121 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3122                                  gdb_byte *info_ptr,
3123                                  struct die_info *comp_unit_die,
3124                                  int has_children,
3125                                  void *data)
3126 {
3127   const char **result_ptr = data;
3128   struct dwarf2_cu *cu = reader->cu;
3129   struct attribute *attr;
3130
3131   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3132   if (attr == NULL)
3133     *result_ptr = NULL;
3134   else
3135     *result_ptr = DW_STRING (attr);
3136 }
3137
3138 static const char *
3139 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3140 {
3141   struct dwarf2_per_cu_data *per_cu;
3142   offset_type *vec;
3143   struct quick_file_names *file_data;
3144   const char *filename;
3145
3146   dw2_setup (objfile);
3147
3148   /* index_table is NULL if OBJF_READNOW.  */
3149   if (!dwarf2_per_objfile->index_table)
3150     {
3151       struct symtab *s;
3152
3153       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3154         {
3155           struct blockvector *bv = BLOCKVECTOR (s);
3156           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3157           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3158
3159           if (sym)
3160             return sym->symtab->filename;
3161         }
3162       return NULL;
3163     }
3164
3165   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3166                                  name, &vec))
3167     return NULL;
3168
3169   /* Note that this just looks at the very first one named NAME -- but
3170      actually we are looking for a function.  find_main_filename
3171      should be rewritten so that it doesn't require a custom hook.  It
3172      could just use the ordinary symbol tables.  */
3173   /* vec[0] is the length, which must always be >0.  */
3174   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3175
3176   if (per_cu->v.quick->symtab != NULL)
3177     return per_cu->v.quick->symtab->filename;
3178
3179   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3180                            dw2_get_primary_filename_reader, &filename);
3181
3182   return filename;
3183 }
3184
3185 static void
3186 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3187                           struct objfile *objfile, int global,
3188                           int (*callback) (struct block *,
3189                                            struct symbol *, void *),
3190                           void *data, symbol_compare_ftype *match,
3191                           symbol_compare_ftype *ordered_compare)
3192 {
3193   /* Currently unimplemented; used for Ada.  The function can be called if the
3194      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3195      does not look for non-Ada symbols this function should just return.  */
3196 }
3197
3198 static void
3199 dw2_expand_symtabs_matching
3200   (struct objfile *objfile,
3201    int (*file_matcher) (const char *, void *),
3202    int (*name_matcher) (const char *, void *),
3203    enum search_domain kind,
3204    void *data)
3205 {
3206   int i;
3207   offset_type iter;
3208   struct mapped_index *index;
3209
3210   dw2_setup (objfile);
3211
3212   /* index_table is NULL if OBJF_READNOW.  */
3213   if (!dwarf2_per_objfile->index_table)
3214     return;
3215   index = dwarf2_per_objfile->index_table;
3216
3217   if (file_matcher != NULL)
3218     {
3219       struct cleanup *cleanup;
3220       htab_t visited_found, visited_not_found;
3221
3222       dw2_build_type_unit_groups ();
3223
3224       visited_found = htab_create_alloc (10,
3225                                          htab_hash_pointer, htab_eq_pointer,
3226                                          NULL, xcalloc, xfree);
3227       cleanup = make_cleanup_htab_delete (visited_found);
3228       visited_not_found = htab_create_alloc (10,
3229                                              htab_hash_pointer, htab_eq_pointer,
3230                                              NULL, xcalloc, xfree);
3231       make_cleanup_htab_delete (visited_not_found);
3232
3233       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3234                        + dwarf2_per_objfile->n_type_unit_groups); ++i)
3235         {
3236           int j;
3237           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3238           struct quick_file_names *file_data;
3239           void **slot;
3240
3241           per_cu->v.quick->mark = 0;
3242
3243           /* We only need to look at symtabs not already expanded.  */
3244           if (per_cu->v.quick->symtab)
3245             continue;
3246
3247           file_data = dw2_get_file_names (objfile, per_cu);
3248           if (file_data == NULL)
3249             continue;
3250
3251           if (htab_find (visited_not_found, file_data) != NULL)
3252             continue;
3253           else if (htab_find (visited_found, file_data) != NULL)
3254             {
3255               per_cu->v.quick->mark = 1;
3256               continue;
3257             }
3258
3259           for (j = 0; j < file_data->num_file_names; ++j)
3260             {
3261               if (file_matcher (file_data->file_names[j], data))
3262                 {
3263                   per_cu->v.quick->mark = 1;
3264                   break;
3265                 }
3266             }
3267
3268           slot = htab_find_slot (per_cu->v.quick->mark
3269                                  ? visited_found
3270                                  : visited_not_found,
3271                                  file_data, INSERT);
3272           *slot = file_data;
3273         }
3274
3275       do_cleanups (cleanup);
3276     }
3277
3278   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3279     {
3280       offset_type idx = 2 * iter;
3281       const char *name;
3282       offset_type *vec, vec_len, vec_idx;
3283
3284       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3285         continue;
3286
3287       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3288
3289       if (! (*name_matcher) (name, data))
3290         continue;
3291
3292       /* The name was matched, now expand corresponding CUs that were
3293          marked.  */
3294       vec = (offset_type *) (index->constant_pool
3295                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3296       vec_len = MAYBE_SWAP (vec[0]);
3297       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3298         {
3299           struct dwarf2_per_cu_data *per_cu;
3300           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3301           gdb_index_symbol_kind symbol_kind =
3302             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3303           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3304
3305           /* Don't crash on bad data.  */
3306           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3307                            + dwarf2_per_objfile->n_type_units))
3308             continue;
3309
3310           /* Only check the symbol's kind if it has one.
3311              Indices prior to version 7 don't record it.  */
3312           if (index->version >= 7)
3313             {
3314               switch (kind)
3315                 {
3316                 case VARIABLES_DOMAIN:
3317                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3318                     continue;
3319                   break;
3320                 case FUNCTIONS_DOMAIN:
3321                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3322                     continue;
3323                   break;
3324                 case TYPES_DOMAIN:
3325                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3326                     continue;
3327                   break;
3328                 default:
3329                   break;
3330                 }
3331             }
3332
3333           per_cu = dw2_get_cu (cu_index);
3334           if (file_matcher == NULL || per_cu->v.quick->mark)
3335             dw2_instantiate_symtab (per_cu);
3336         }
3337     }
3338 }
3339
3340 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3341    symtab.  */
3342
3343 static struct symtab *
3344 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3345 {
3346   int i;
3347
3348   if (BLOCKVECTOR (symtab) != NULL
3349       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3350     return symtab;
3351
3352   if (symtab->includes == NULL)
3353     return NULL;
3354
3355   for (i = 0; symtab->includes[i]; ++i)
3356     {
3357       struct symtab *s = symtab->includes[i];
3358
3359       s = recursively_find_pc_sect_symtab (s, pc);
3360       if (s != NULL)
3361         return s;
3362     }
3363
3364   return NULL;
3365 }
3366
3367 static struct symtab *
3368 dw2_find_pc_sect_symtab (struct objfile *objfile,
3369                          struct minimal_symbol *msymbol,
3370                          CORE_ADDR pc,
3371                          struct obj_section *section,
3372                          int warn_if_readin)
3373 {
3374   struct dwarf2_per_cu_data *data;
3375   struct symtab *result;
3376
3377   dw2_setup (objfile);
3378
3379   if (!objfile->psymtabs_addrmap)
3380     return NULL;
3381
3382   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3383   if (!data)
3384     return NULL;
3385
3386   if (warn_if_readin && data->v.quick->symtab)
3387     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3388              paddress (get_objfile_arch (objfile), pc));
3389
3390   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3391   gdb_assert (result != NULL);
3392   return result;
3393 }
3394
3395 static void
3396 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3397                           void *data, int need_fullname)
3398 {
3399   int i;
3400   struct cleanup *cleanup;
3401   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3402                                       NULL, xcalloc, xfree);
3403
3404   cleanup = make_cleanup_htab_delete (visited);
3405   dw2_setup (objfile);
3406
3407   dw2_build_type_unit_groups ();
3408
3409   /* We can ignore file names coming from already-expanded CUs.  */
3410   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3411                    + dwarf2_per_objfile->n_type_units); ++i)
3412     {
3413       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3414
3415       if (per_cu->v.quick->symtab)
3416         {
3417           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3418                                         INSERT);
3419
3420           *slot = per_cu->v.quick->file_names;
3421         }
3422     }
3423
3424   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3425                    + dwarf2_per_objfile->n_type_unit_groups); ++i)
3426     {
3427       int j;
3428       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3429       struct quick_file_names *file_data;
3430       void **slot;
3431
3432       /* We only need to look at symtabs not already expanded.  */
3433       if (per_cu->v.quick->symtab)
3434         continue;
3435
3436       file_data = dw2_get_file_names (objfile, per_cu);
3437       if (file_data == NULL)
3438         continue;
3439
3440       slot = htab_find_slot (visited, file_data, INSERT);
3441       if (*slot)
3442         {
3443           /* Already visited.  */
3444           continue;
3445         }
3446       *slot = file_data;
3447
3448       for (j = 0; j < file_data->num_file_names; ++j)
3449         {
3450           const char *this_real_name;
3451
3452           if (need_fullname)
3453             this_real_name = dw2_get_real_path (objfile, file_data, j);
3454           else
3455             this_real_name = NULL;
3456           (*fun) (file_data->file_names[j], this_real_name, data);
3457         }
3458     }
3459
3460   do_cleanups (cleanup);
3461 }
3462
3463 static int
3464 dw2_has_symbols (struct objfile *objfile)
3465 {
3466   return 1;
3467 }
3468
3469 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3470 {
3471   dw2_has_symbols,
3472   dw2_find_last_source_symtab,
3473   dw2_forget_cached_source_info,
3474   dw2_map_symtabs_matching_filename,
3475   dw2_lookup_symbol,
3476   dw2_pre_expand_symtabs_matching,
3477   dw2_print_stats,
3478   dw2_dump,
3479   dw2_relocate,
3480   dw2_expand_symtabs_for_function,
3481   dw2_expand_all_symtabs,
3482   dw2_expand_symtabs_with_filename,
3483   dw2_find_symbol_file,
3484   dw2_map_matching_symbols,
3485   dw2_expand_symtabs_matching,
3486   dw2_find_pc_sect_symtab,
3487   dw2_map_symbol_filenames
3488 };
3489
3490 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3491    file will use psymtabs, or 1 if using the GNU index.  */
3492
3493 int
3494 dwarf2_initialize_objfile (struct objfile *objfile)
3495 {
3496   /* If we're about to read full symbols, don't bother with the
3497      indices.  In this case we also don't care if some other debug
3498      format is making psymtabs, because they are all about to be
3499      expanded anyway.  */
3500   if ((objfile->flags & OBJF_READNOW))
3501     {
3502       int i;
3503
3504       dwarf2_per_objfile->using_index = 1;
3505       create_all_comp_units (objfile);
3506       create_all_type_units (objfile);
3507       dwarf2_per_objfile->quick_file_names_table =
3508         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3509
3510       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3511                        + dwarf2_per_objfile->n_type_units); ++i)
3512         {
3513           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3514
3515           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3516                                             struct dwarf2_per_cu_quick_data);
3517         }
3518
3519       /* Return 1 so that gdb sees the "quick" functions.  However,
3520          these functions will be no-ops because we will have expanded
3521          all symtabs.  */
3522       return 1;
3523     }
3524
3525   if (dwarf2_read_index (objfile))
3526     return 1;
3527
3528   return 0;
3529 }
3530
3531 \f
3532
3533 /* Build a partial symbol table.  */
3534
3535 void
3536 dwarf2_build_psymtabs (struct objfile *objfile)
3537 {
3538   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3539     {
3540       init_psymbol_list (objfile, 1024);
3541     }
3542
3543   dwarf2_build_psymtabs_hard (objfile);
3544 }
3545
3546 /* Return the total length of the CU described by HEADER.  */
3547
3548 static unsigned int
3549 get_cu_length (const struct comp_unit_head *header)
3550 {
3551   return header->initial_length_size + header->length;
3552 }
3553
3554 /* Return TRUE if OFFSET is within CU_HEADER.  */
3555
3556 static inline int
3557 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3558 {
3559   sect_offset bottom = { cu_header->offset.sect_off };
3560   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3561
3562   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3563 }
3564
3565 /* Find the base address of the compilation unit for range lists and
3566    location lists.  It will normally be specified by DW_AT_low_pc.
3567    In DWARF-3 draft 4, the base address could be overridden by
3568    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3569    compilation units with discontinuous ranges.  */
3570
3571 static void
3572 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3573 {
3574   struct attribute *attr;
3575
3576   cu->base_known = 0;
3577   cu->base_address = 0;
3578
3579   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3580   if (attr)
3581     {
3582       cu->base_address = DW_ADDR (attr);
3583       cu->base_known = 1;
3584     }
3585   else
3586     {
3587       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3588       if (attr)
3589         {
3590           cu->base_address = DW_ADDR (attr);
3591           cu->base_known = 1;
3592         }
3593     }
3594 }
3595
3596 /* Read in the comp unit header information from the debug_info at info_ptr.
3597    NOTE: This leaves members offset, first_die_offset to be filled in
3598    by the caller.  */
3599
3600 static gdb_byte *
3601 read_comp_unit_head (struct comp_unit_head *cu_header,
3602                      gdb_byte *info_ptr, bfd *abfd)
3603 {
3604   int signed_addr;
3605   unsigned int bytes_read;
3606
3607   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3608   cu_header->initial_length_size = bytes_read;
3609   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3610   info_ptr += bytes_read;
3611   cu_header->version = read_2_bytes (abfd, info_ptr);
3612   info_ptr += 2;
3613   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3614                                              &bytes_read);
3615   info_ptr += bytes_read;
3616   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3617   info_ptr += 1;
3618   signed_addr = bfd_get_sign_extend_vma (abfd);
3619   if (signed_addr < 0)
3620     internal_error (__FILE__, __LINE__,
3621                     _("read_comp_unit_head: dwarf from non elf file"));
3622   cu_header->signed_addr_p = signed_addr;
3623
3624   return info_ptr;
3625 }
3626
3627 /* Subroutine of read_and_check_comp_unit_head and
3628    read_and_check_type_unit_head to simplify them.
3629    Perform various error checking on the header.  */
3630
3631 static void
3632 error_check_comp_unit_head (struct comp_unit_head *header,
3633                             struct dwarf2_section_info *section,
3634                             struct dwarf2_section_info *abbrev_section)
3635 {
3636   bfd *abfd = section->asection->owner;
3637   const char *filename = bfd_get_filename (abfd);
3638
3639   if (header->version != 2 && header->version != 3 && header->version != 4)
3640     error (_("Dwarf Error: wrong version in compilation unit header "
3641            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3642            filename);
3643
3644   if (header->abbrev_offset.sect_off
3645       >= dwarf2_section_size (dwarf2_per_objfile->objfile,
3646                               &dwarf2_per_objfile->abbrev))
3647     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3648            "(offset 0x%lx + 6) [in module %s]"),
3649            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3650            filename);
3651
3652   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3653      avoid potential 32-bit overflow.  */
3654   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3655       > section->size)
3656     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3657            "(offset 0x%lx + 0) [in module %s]"),
3658            (long) header->length, (long) header->offset.sect_off,
3659            filename);
3660 }
3661
3662 /* Read in a CU/TU header and perform some basic error checking.
3663    The contents of the header are stored in HEADER.
3664    The result is a pointer to the start of the first DIE.  */
3665
3666 static gdb_byte *
3667 read_and_check_comp_unit_head (struct comp_unit_head *header,
3668                                struct dwarf2_section_info *section,
3669                                struct dwarf2_section_info *abbrev_section,
3670                                gdb_byte *info_ptr,
3671                                int is_debug_types_section)
3672 {
3673   gdb_byte *beg_of_comp_unit = info_ptr;
3674   bfd *abfd = section->asection->owner;
3675
3676   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3677
3678   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3679
3680   /* If we're reading a type unit, skip over the signature and
3681      type_offset fields.  */
3682   if (is_debug_types_section)
3683     info_ptr += 8 /*signature*/ + header->offset_size;
3684
3685   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3686
3687   error_check_comp_unit_head (header, section, abbrev_section);
3688
3689   return info_ptr;
3690 }
3691
3692 /* Read in the types comp unit header information from .debug_types entry at
3693    types_ptr.  The result is a pointer to one past the end of the header.  */
3694
3695 static gdb_byte *
3696 read_and_check_type_unit_head (struct comp_unit_head *header,
3697                                struct dwarf2_section_info *section,
3698                                struct dwarf2_section_info *abbrev_section,
3699                                gdb_byte *info_ptr,
3700                                ULONGEST *signature,
3701                                cu_offset *type_offset_in_tu)
3702 {
3703   gdb_byte *beg_of_comp_unit = info_ptr;
3704   bfd *abfd = section->asection->owner;
3705
3706   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3707
3708   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3709
3710   /* If we're reading a type unit, skip over the signature and
3711      type_offset fields.  */
3712   if (signature != NULL)
3713     *signature = read_8_bytes (abfd, info_ptr);
3714   info_ptr += 8;
3715   if (type_offset_in_tu != NULL)
3716     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
3717                                                header->offset_size);
3718   info_ptr += header->offset_size;
3719
3720   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3721
3722   error_check_comp_unit_head (header, section, abbrev_section);
3723
3724   return info_ptr;
3725 }
3726
3727 /* Fetch the abbreviation table offset from a comp or type unit header.  */
3728
3729 static sect_offset
3730 read_abbrev_offset (struct dwarf2_section_info *section,
3731                     sect_offset offset)
3732 {
3733   bfd *abfd = section->asection->owner;
3734   gdb_byte *info_ptr;
3735   unsigned int length, initial_length_size, offset_size;
3736   sect_offset abbrev_offset;
3737
3738   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
3739   info_ptr = section->buffer + offset.sect_off;
3740   length = read_initial_length (abfd, info_ptr, &initial_length_size);
3741   offset_size = initial_length_size == 4 ? 4 : 8;
3742   info_ptr += initial_length_size + 2 /*version*/;
3743   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
3744   return abbrev_offset;
3745 }
3746
3747 /* Allocate a new partial symtab for file named NAME and mark this new
3748    partial symtab as being an include of PST.  */
3749
3750 static void
3751 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
3752                                struct objfile *objfile)
3753 {
3754   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
3755
3756   subpst->section_offsets = pst->section_offsets;
3757   subpst->textlow = 0;
3758   subpst->texthigh = 0;
3759
3760   subpst->dependencies = (struct partial_symtab **)
3761     obstack_alloc (&objfile->objfile_obstack,
3762                    sizeof (struct partial_symtab *));
3763   subpst->dependencies[0] = pst;
3764   subpst->number_of_dependencies = 1;
3765
3766   subpst->globals_offset = 0;
3767   subpst->n_global_syms = 0;
3768   subpst->statics_offset = 0;
3769   subpst->n_static_syms = 0;
3770   subpst->symtab = NULL;
3771   subpst->read_symtab = pst->read_symtab;
3772   subpst->readin = 0;
3773
3774   /* No private part is necessary for include psymtabs.  This property
3775      can be used to differentiate between such include psymtabs and
3776      the regular ones.  */
3777   subpst->read_symtab_private = NULL;
3778 }
3779
3780 /* Read the Line Number Program data and extract the list of files
3781    included by the source file represented by PST.  Build an include
3782    partial symtab for each of these included files.  */
3783
3784 static void
3785 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
3786                                struct die_info *die,
3787                                struct partial_symtab *pst)
3788 {
3789   struct line_header *lh = NULL;
3790   struct attribute *attr;
3791
3792   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
3793   if (attr)
3794     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
3795   if (lh == NULL)
3796     return;  /* No linetable, so no includes.  */
3797
3798   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
3799   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
3800
3801   free_line_header (lh);
3802 }
3803
3804 static hashval_t
3805 hash_signatured_type (const void *item)
3806 {
3807   const struct signatured_type *sig_type = item;
3808
3809   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
3810   return sig_type->signature;
3811 }
3812
3813 static int
3814 eq_signatured_type (const void *item_lhs, const void *item_rhs)
3815 {
3816   const struct signatured_type *lhs = item_lhs;
3817   const struct signatured_type *rhs = item_rhs;
3818
3819   return lhs->signature == rhs->signature;
3820 }
3821
3822 /* Allocate a hash table for signatured types.  */
3823
3824 static htab_t
3825 allocate_signatured_type_table (struct objfile *objfile)
3826 {
3827   return htab_create_alloc_ex (41,
3828                                hash_signatured_type,
3829                                eq_signatured_type,
3830                                NULL,
3831                                &objfile->objfile_obstack,
3832                                hashtab_obstack_allocate,
3833                                dummy_obstack_deallocate);
3834 }
3835
3836 /* A helper function to add a signatured type CU to a table.  */
3837
3838 static int
3839 add_signatured_type_cu_to_table (void **slot, void *datum)
3840 {
3841   struct signatured_type *sigt = *slot;
3842   struct signatured_type ***datap = datum;
3843
3844   **datap = sigt;
3845   ++*datap;
3846
3847   return 1;
3848 }
3849
3850 /* Create the hash table of all entries in the .debug_types section.
3851    DWO_FILE is a pointer to the DWO file for .debug_types.dwo, NULL otherwise.
3852    The result is a pointer to the hash table or NULL if there are
3853    no types.  */
3854
3855 static htab_t
3856 create_debug_types_hash_table (struct dwo_file *dwo_file,
3857                                VEC (dwarf2_section_info_def) *types)
3858 {
3859   struct objfile *objfile = dwarf2_per_objfile->objfile;
3860   htab_t types_htab = NULL;
3861   int ix;
3862   struct dwarf2_section_info *section;
3863   struct dwarf2_section_info *abbrev_section;
3864
3865   if (VEC_empty (dwarf2_section_info_def, types))
3866     return NULL;
3867
3868   abbrev_section = (dwo_file != NULL
3869                     ? &dwo_file->sections.abbrev
3870                     : &dwarf2_per_objfile->abbrev);
3871
3872   if (dwarf2_read_debug)
3873     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
3874                         dwo_file ? ".dwo" : "",
3875                         bfd_get_filename (abbrev_section->asection->owner));
3876
3877   for (ix = 0;
3878        VEC_iterate (dwarf2_section_info_def, types, ix, section);
3879        ++ix)
3880     {
3881       bfd *abfd;
3882       gdb_byte *info_ptr, *end_ptr;
3883
3884       dwarf2_read_section (objfile, section);
3885       info_ptr = section->buffer;
3886
3887       if (info_ptr == NULL)
3888         continue;
3889
3890       /* We can't set abfd until now because the section may be empty or
3891          not present, in which case section->asection will be NULL.  */
3892       abfd = section->asection->owner;
3893
3894       if (types_htab == NULL)
3895         {
3896           if (dwo_file)
3897             types_htab = allocate_dwo_unit_table (objfile);
3898           else
3899             types_htab = allocate_signatured_type_table (objfile);
3900         }
3901
3902       /* We don't use init_cutu_and_read_dies_simple, or some such, here
3903          because we don't need to read any dies: the signature is in the
3904          header.  */
3905
3906       end_ptr = info_ptr + section->size;
3907       while (info_ptr < end_ptr)
3908         {
3909           sect_offset offset;
3910           cu_offset type_offset_in_tu;
3911           ULONGEST signature;
3912           struct signatured_type *sig_type;
3913           struct dwo_unit *dwo_tu;
3914           void **slot;
3915           gdb_byte *ptr = info_ptr;
3916           struct comp_unit_head header;
3917           unsigned int length;
3918
3919           offset.sect_off = ptr - section->buffer;
3920
3921           /* We need to read the type's signature in order to build the hash
3922              table, but we don't need anything else just yet.  */
3923
3924           ptr = read_and_check_type_unit_head (&header, section,
3925                                                abbrev_section, ptr,
3926                                                &signature, &type_offset_in_tu);
3927
3928           length = get_cu_length (&header);
3929
3930           /* Skip dummy type units.  */
3931           if (ptr >= info_ptr + length
3932               || peek_abbrev_code (abfd, ptr) == 0)
3933             {
3934               info_ptr += length;
3935               continue;
3936             }
3937
3938           if (dwo_file)
3939             {
3940               sig_type = NULL;
3941               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3942                                        struct dwo_unit);
3943               dwo_tu->dwo_file = dwo_file;
3944               dwo_tu->signature = signature;
3945               dwo_tu->type_offset_in_tu = type_offset_in_tu;
3946               dwo_tu->info_or_types_section = section;
3947               dwo_tu->offset = offset;
3948               dwo_tu->length = length;
3949             }
3950           else
3951             {
3952               /* N.B.: type_offset is not usable if this type uses a DWO file.
3953                  The real type_offset is in the DWO file.  */
3954               dwo_tu = NULL;
3955               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3956                                          struct signatured_type);
3957               sig_type->signature = signature;
3958               sig_type->type_offset_in_tu = type_offset_in_tu;
3959               sig_type->per_cu.objfile = objfile;
3960               sig_type->per_cu.is_debug_types = 1;
3961               sig_type->per_cu.info_or_types_section = section;
3962               sig_type->per_cu.offset = offset;
3963               sig_type->per_cu.length = length;
3964             }
3965
3966           slot = htab_find_slot (types_htab,
3967                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
3968                                  INSERT);
3969           gdb_assert (slot != NULL);
3970           if (*slot != NULL)
3971             {
3972               sect_offset dup_offset;
3973
3974               if (dwo_file)
3975                 {
3976                   const struct dwo_unit *dup_tu = *slot;
3977
3978                   dup_offset = dup_tu->offset;
3979                 }
3980               else
3981                 {
3982                   const struct signatured_type *dup_tu = *slot;
3983
3984                   dup_offset = dup_tu->per_cu.offset;
3985                 }
3986
3987               complaint (&symfile_complaints,
3988                          _("debug type entry at offset 0x%x is duplicate to the "
3989                            "entry at offset 0x%x, signature 0x%s"),
3990                          offset.sect_off, dup_offset.sect_off,
3991                          phex (signature, sizeof (signature)));
3992             }
3993           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
3994
3995           if (dwarf2_read_debug)
3996             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
3997                                 offset.sect_off,
3998                                 phex (signature, sizeof (signature)));
3999
4000           info_ptr += length;
4001         }
4002     }
4003
4004   return types_htab;
4005 }
4006
4007 /* Create the hash table of all entries in the .debug_types section,
4008    and initialize all_type_units.
4009    The result is zero if there is an error (e.g. missing .debug_types section),
4010    otherwise non-zero.  */
4011
4012 static int
4013 create_all_type_units (struct objfile *objfile)
4014 {
4015   htab_t types_htab;
4016   struct signatured_type **iter;
4017
4018   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4019   if (types_htab == NULL)
4020     {
4021       dwarf2_per_objfile->signatured_types = NULL;
4022       return 0;
4023     }
4024
4025   dwarf2_per_objfile->signatured_types = types_htab;
4026
4027   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4028   dwarf2_per_objfile->all_type_units
4029     = obstack_alloc (&objfile->objfile_obstack,
4030                      dwarf2_per_objfile->n_type_units
4031                      * sizeof (struct signatured_type *));
4032   iter = &dwarf2_per_objfile->all_type_units[0];
4033   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4034   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4035               == dwarf2_per_objfile->n_type_units);
4036
4037   return 1;
4038 }
4039
4040 /* Lookup a signature based type for DW_FORM_ref_sig8.
4041    Returns NULL if signature SIG is not present in the table.  */
4042
4043 static struct signatured_type *
4044 lookup_signatured_type (ULONGEST sig)
4045 {
4046   struct signatured_type find_entry, *entry;
4047
4048   if (dwarf2_per_objfile->signatured_types == NULL)
4049     {
4050       complaint (&symfile_complaints,
4051                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4052       return NULL;
4053     }
4054
4055   find_entry.signature = sig;
4056   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4057   return entry;
4058 }
4059 \f
4060 /* Low level DIE reading support.  */
4061
4062 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4063
4064 static void
4065 init_cu_die_reader (struct die_reader_specs *reader,
4066                     struct dwarf2_cu *cu,
4067                     struct dwarf2_section_info *section,
4068                     struct dwo_file *dwo_file)
4069 {
4070   gdb_assert (section->readin && section->buffer != NULL);
4071   reader->abfd = section->asection->owner;
4072   reader->cu = cu;
4073   reader->dwo_file = dwo_file;
4074   reader->die_section = section;
4075   reader->buffer = section->buffer;
4076   reader->buffer_end = section->buffer + section->size;
4077 }
4078
4079 /* Initialize a CU (or TU) and read its DIEs.
4080    If the CU defers to a DWO file, read the DWO file as well.
4081
4082    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4083    Otherwise the table specified in the comp unit header is read in and used.
4084    This is an optimization for when we already have the abbrev table.
4085
4086    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4087    Otherwise, a new CU is allocated with xmalloc.
4088
4089    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4090    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4091
4092    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4093    linker) then DIE_READER_FUNC will not get called.  */
4094
4095 static void
4096 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4097                          struct abbrev_table *abbrev_table,
4098                          int use_existing_cu, int keep,
4099                          die_reader_func_ftype *die_reader_func,
4100                          void *data)
4101 {
4102   struct objfile *objfile = dwarf2_per_objfile->objfile;
4103   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4104   bfd *abfd = section->asection->owner;
4105   struct dwarf2_cu *cu;
4106   gdb_byte *begin_info_ptr, *info_ptr;
4107   struct die_reader_specs reader;
4108   struct die_info *comp_unit_die;
4109   int has_children;
4110   struct attribute *attr;
4111   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4112   struct signatured_type *sig_type = NULL;
4113   struct dwarf2_section_info *abbrev_section;
4114   /* Non-zero if CU currently points to a DWO file and we need to
4115      reread it.  When this happens we need to reread the skeleton die
4116      before we can reread the DWO file.  */
4117   int rereading_dwo_cu = 0;
4118
4119   if (dwarf2_die_debug)
4120     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4121                         this_cu->is_debug_types ? "type" : "comp",
4122                         this_cu->offset.sect_off);
4123
4124   if (use_existing_cu)
4125     gdb_assert (keep);
4126
4127   cleanups = make_cleanup (null_cleanup, NULL);
4128
4129   /* This is cheap if the section is already read in.  */
4130   dwarf2_read_section (objfile, section);
4131
4132   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4133   abbrev_section = &dwarf2_per_objfile->abbrev;
4134
4135   if (use_existing_cu && this_cu->cu != NULL)
4136     {
4137       cu = this_cu->cu;
4138
4139       /* If this CU is from a DWO file we need to start over, we need to
4140          refetch the attributes from the skeleton CU.
4141          This could be optimized by retrieving those attributes from when we
4142          were here the first time: the previous comp_unit_die was stored in
4143          comp_unit_obstack.  But there's no data yet that we need this
4144          optimization.  */
4145       if (cu->dwo_unit != NULL)
4146         rereading_dwo_cu = 1;
4147     }
4148   else
4149     {
4150       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4151       gdb_assert (this_cu->cu == NULL);
4152
4153       cu = xmalloc (sizeof (*cu));
4154       init_one_comp_unit (cu, this_cu);
4155
4156       /* If an error occurs while loading, release our storage.  */
4157       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4158     }
4159
4160   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4161     {
4162       /* We already have the header, there's no need to read it in again.  */
4163       info_ptr += cu->header.first_die_offset.cu_off;
4164     }
4165   else
4166     {
4167       if (this_cu->is_debug_types)
4168         {
4169           ULONGEST signature;
4170           cu_offset type_offset_in_tu;
4171
4172           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4173                                                     abbrev_section, info_ptr,
4174                                                     &signature,
4175                                                     &type_offset_in_tu);
4176
4177           /* Since per_cu is the first member of struct signatured_type,
4178              we can go from a pointer to one to a pointer to the other.  */
4179           sig_type = (struct signatured_type *) this_cu;
4180           gdb_assert (sig_type->signature == signature);
4181           gdb_assert (sig_type->type_offset_in_tu.cu_off
4182                       == type_offset_in_tu.cu_off);
4183           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4184
4185           /* LENGTH has not been set yet for type units if we're
4186              using .gdb_index.  */
4187           this_cu->length = get_cu_length (&cu->header);
4188
4189           /* Establish the type offset that can be used to lookup the type.  */
4190           sig_type->type_offset_in_section.sect_off =
4191             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4192         }
4193       else
4194         {
4195           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4196                                                     abbrev_section,
4197                                                     info_ptr, 0);
4198
4199           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4200           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4201         }
4202     }
4203
4204   /* Skip dummy compilation units.  */
4205   if (info_ptr >= begin_info_ptr + this_cu->length
4206       || peek_abbrev_code (abfd, info_ptr) == 0)
4207     {
4208       do_cleanups (cleanups);
4209       return;
4210     }
4211
4212   /* If we don't have them yet, read the abbrevs for this compilation unit.
4213      And if we need to read them now, make sure they're freed when we're
4214      done.  Note that it's important that if the CU had an abbrev table
4215      on entry we don't free it when we're done: Somewhere up the call stack
4216      it may be in use.  */
4217   if (abbrev_table != NULL)
4218     {
4219       gdb_assert (cu->abbrev_table == NULL);
4220       gdb_assert (cu->header.abbrev_offset.sect_off
4221                   == abbrev_table->offset.sect_off);
4222       cu->abbrev_table = abbrev_table;
4223     }
4224   else if (cu->abbrev_table == NULL)
4225     {
4226       dwarf2_read_abbrevs (cu, abbrev_section);
4227       make_cleanup (dwarf2_free_abbrev_table, cu);
4228     }
4229   else if (rereading_dwo_cu)
4230     {
4231       dwarf2_free_abbrev_table (cu);
4232       dwarf2_read_abbrevs (cu, abbrev_section);
4233     }
4234
4235   /* Read the top level CU/TU die.  */
4236   init_cu_die_reader (&reader, cu, section, NULL);
4237   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4238
4239   /* If we have a DWO stub, process it and then read in the DWO file.
4240      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4241      a DWO CU, that this test will fail.  */
4242   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4243   if (attr)
4244     {
4245       char *dwo_name = DW_STRING (attr);
4246       const char *comp_dir_string;
4247       struct dwo_unit *dwo_unit;
4248       ULONGEST signature; /* Or dwo_id.  */
4249       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4250       int i,num_extra_attrs;
4251       struct dwarf2_section_info *dwo_abbrev_section;
4252
4253       if (has_children)
4254         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4255                  " has children (offset 0x%x) [in module %s]"),
4256                this_cu->offset.sect_off, bfd_get_filename (abfd));
4257
4258       /* These attributes aren't processed until later:
4259          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4260          However, the attribute is found in the stub which we won't have later.
4261          In order to not impose this complication on the rest of the code,
4262          we read them here and copy them to the DWO CU/TU die.  */
4263
4264       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4265          DWO file.  */
4266       stmt_list = NULL;
4267       if (! this_cu->is_debug_types)
4268         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4269       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4270       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4271       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4272       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4273
4274       /* There should be a DW_AT_addr_base attribute here (if needed).
4275          We need the value before we can process DW_FORM_GNU_addr_index.  */
4276       cu->addr_base = 0;
4277       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4278       if (attr)
4279         cu->addr_base = DW_UNSND (attr);
4280
4281       /* There should be a DW_AT_ranges_base attribute here (if needed).
4282          We need the value before we can process DW_AT_ranges.  */
4283       cu->ranges_base = 0;
4284       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4285       if (attr)
4286         cu->ranges_base = DW_UNSND (attr);
4287
4288       if (this_cu->is_debug_types)
4289         {
4290           gdb_assert (sig_type != NULL);
4291           signature = sig_type->signature;
4292         }
4293       else
4294         {
4295           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4296           if (! attr)
4297             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4298                    dwo_name);
4299           signature = DW_UNSND (attr);
4300         }
4301
4302       /* We may need the comp_dir in order to find the DWO file.  */
4303       comp_dir_string = NULL;
4304       if (comp_dir)
4305         comp_dir_string = DW_STRING (comp_dir);
4306
4307       if (this_cu->is_debug_types)
4308         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4309       else
4310         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4311                                          signature);
4312
4313       if (dwo_unit == NULL)
4314         {
4315           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4316                    " with ID %s [in module %s]"),
4317                  this_cu->offset.sect_off,
4318                  phex (signature, sizeof (signature)),
4319                  objfile->name);
4320         }
4321
4322       /* Set up for reading the DWO CU/TU.  */
4323       cu->dwo_unit = dwo_unit;
4324       section = dwo_unit->info_or_types_section;
4325       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4326       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4327       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4328
4329       if (this_cu->is_debug_types)
4330         {
4331           ULONGEST signature;
4332
4333           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4334                                                     dwo_abbrev_section,
4335                                                     info_ptr,
4336                                                     &signature, NULL);
4337           gdb_assert (sig_type->signature == signature);
4338           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4339           gdb_assert (dwo_unit->length == get_cu_length (&cu->header));
4340
4341           /* Establish the type offset that can be used to lookup the type.
4342              For DWO files, we don't know it until now.  */
4343           sig_type->type_offset_in_section.sect_off =
4344             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4345         }
4346       else
4347         {
4348           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4349                                                     dwo_abbrev_section,
4350                                                     info_ptr, 0);
4351           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4352           gdb_assert (dwo_unit->length == get_cu_length (&cu->header));
4353         }
4354
4355       /* Discard the original CU's abbrev table, and read the DWO's.  */
4356       if (abbrev_table == NULL)
4357         {
4358           dwarf2_free_abbrev_table (cu);
4359           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4360         }
4361       else
4362         {
4363           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4364           make_cleanup (dwarf2_free_abbrev_table, cu);
4365         }
4366
4367       /* Read in the die, but leave space to copy over the attributes
4368          from the stub.  This has the benefit of simplifying the rest of
4369          the code - all the real work is done here.  */
4370       num_extra_attrs = ((stmt_list != NULL)
4371                          + (low_pc != NULL)
4372                          + (high_pc != NULL)
4373                          + (ranges != NULL)
4374                          + (comp_dir != NULL));
4375       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4376                                   &has_children, num_extra_attrs);
4377
4378       /* Copy over the attributes from the stub to the DWO die.  */
4379       i = comp_unit_die->num_attrs;
4380       if (stmt_list != NULL)
4381         comp_unit_die->attrs[i++] = *stmt_list;
4382       if (low_pc != NULL)
4383         comp_unit_die->attrs[i++] = *low_pc;
4384       if (high_pc != NULL)
4385         comp_unit_die->attrs[i++] = *high_pc;
4386       if (ranges != NULL)
4387         comp_unit_die->attrs[i++] = *ranges;
4388       if (comp_dir != NULL)
4389         comp_unit_die->attrs[i++] = *comp_dir;
4390       comp_unit_die->num_attrs += num_extra_attrs;
4391
4392       /* Skip dummy compilation units.  */
4393       if (info_ptr >= begin_info_ptr + dwo_unit->length
4394           || peek_abbrev_code (abfd, info_ptr) == 0)
4395         {
4396           do_cleanups (cleanups);
4397           return;
4398         }
4399     }
4400
4401   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4402
4403   if (free_cu_cleanup != NULL)
4404     {
4405       if (keep)
4406         {
4407           /* We've successfully allocated this compilation unit.  Let our
4408              caller clean it up when finished with it.  */
4409           discard_cleanups (free_cu_cleanup);
4410
4411           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4412              So we have to manually free the abbrev table.  */
4413           dwarf2_free_abbrev_table (cu);
4414
4415           /* Link this CU into read_in_chain.  */
4416           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4417           dwarf2_per_objfile->read_in_chain = this_cu;
4418         }
4419       else
4420         do_cleanups (free_cu_cleanup);
4421     }
4422
4423   do_cleanups (cleanups);
4424 }
4425
4426 /* Read CU/TU THIS_CU in section SECTION,
4427    but do not follow DW_AT_GNU_dwo_name if present.
4428    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed to
4429    have already done the lookup to find the DWO file).
4430
4431    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4432    THIS_CU->is_debug_types, but nothing else.
4433
4434    We fill in THIS_CU->length.
4435
4436    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4437    linker) then DIE_READER_FUNC will not get called.
4438
4439    THIS_CU->cu is always freed when done.
4440    This is done in order to not leave THIS_CU->cu in a state where we have
4441    to care whether it refers to the "main" CU or the DWO CU.  */
4442
4443 static void
4444 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4445                                    struct dwarf2_section_info *abbrev_section,
4446                                    struct dwo_file *dwo_file,
4447                                    die_reader_func_ftype *die_reader_func,
4448                                    void *data)
4449 {
4450   struct objfile *objfile = dwarf2_per_objfile->objfile;
4451   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4452   bfd *abfd = section->asection->owner;
4453   struct dwarf2_cu cu;
4454   gdb_byte *begin_info_ptr, *info_ptr;
4455   struct die_reader_specs reader;
4456   struct cleanup *cleanups;
4457   struct die_info *comp_unit_die;
4458   int has_children;
4459
4460   if (dwarf2_die_debug)
4461     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4462                         this_cu->is_debug_types ? "type" : "comp",
4463                         this_cu->offset.sect_off);
4464
4465   gdb_assert (this_cu->cu == NULL);
4466
4467   /* This is cheap if the section is already read in.  */
4468   dwarf2_read_section (objfile, section);
4469
4470   init_one_comp_unit (&cu, this_cu);
4471
4472   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4473
4474   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4475   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4476                                             abbrev_section, info_ptr,
4477                                             this_cu->is_debug_types);
4478
4479   this_cu->length = get_cu_length (&cu.header);
4480
4481   /* Skip dummy compilation units.  */
4482   if (info_ptr >= begin_info_ptr + this_cu->length
4483       || peek_abbrev_code (abfd, info_ptr) == 0)
4484     {
4485       do_cleanups (cleanups);
4486       return;
4487     }
4488
4489   dwarf2_read_abbrevs (&cu, abbrev_section);
4490   make_cleanup (dwarf2_free_abbrev_table, &cu);
4491
4492   init_cu_die_reader (&reader, &cu, section, dwo_file);
4493   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4494
4495   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4496
4497   do_cleanups (cleanups);
4498 }
4499
4500 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4501    does not lookup the specified DWO file.
4502    This cannot be used to read DWO files.
4503
4504    THIS_CU->cu is always freed when done.
4505    This is done in order to not leave THIS_CU->cu in a state where we have
4506    to care whether it refers to the "main" CU or the DWO CU.
4507    We can revisit this if the data shows there's a performance issue.  */
4508
4509 static void
4510 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4511                                 die_reader_func_ftype *die_reader_func,
4512                                 void *data)
4513 {
4514   init_cutu_and_read_dies_no_follow (this_cu,
4515                                      &dwarf2_per_objfile->abbrev,
4516                                      NULL,
4517                                      die_reader_func, data);
4518 }
4519
4520 /* Create a psymtab named NAME and assign it to PER_CU.
4521
4522    The caller must fill in the following details:
4523    dirname, textlow, texthigh.  */
4524
4525 static struct partial_symtab *
4526 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4527 {
4528   struct objfile *objfile = per_cu->objfile;
4529   struct partial_symtab *pst;
4530
4531   pst = start_psymtab_common (objfile, objfile->section_offsets,
4532                               name, 0,
4533                               objfile->global_psymbols.next,
4534                               objfile->static_psymbols.next);
4535
4536   pst->psymtabs_addrmap_supported = 1;
4537
4538   /* This is the glue that links PST into GDB's symbol API.  */
4539   pst->read_symtab_private = per_cu;
4540   pst->read_symtab = dwarf2_psymtab_to_symtab;
4541   per_cu->v.psymtab = pst;
4542
4543   return pst;
4544 }
4545
4546 /* die_reader_func for process_psymtab_comp_unit.  */
4547
4548 static void
4549 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4550                                   gdb_byte *info_ptr,
4551                                   struct die_info *comp_unit_die,
4552                                   int has_children,
4553                                   void *data)
4554 {
4555   struct dwarf2_cu *cu = reader->cu;
4556   struct objfile *objfile = cu->objfile;
4557   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4558   struct attribute *attr;
4559   CORE_ADDR baseaddr;
4560   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4561   struct partial_symtab *pst;
4562   int has_pc_info;
4563   const char *filename;
4564   int *want_partial_unit_ptr = data;
4565
4566   if (comp_unit_die->tag == DW_TAG_partial_unit
4567       && (want_partial_unit_ptr == NULL
4568           || !*want_partial_unit_ptr))
4569     return;
4570
4571   gdb_assert (! per_cu->is_debug_types);
4572
4573   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4574
4575   cu->list_in_scope = &file_symbols;
4576
4577   /* Allocate a new partial symbol table structure.  */
4578   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4579   if (attr == NULL || !DW_STRING (attr))
4580     filename = "";
4581   else
4582     filename = DW_STRING (attr);
4583
4584   pst = create_partial_symtab (per_cu, filename);
4585
4586   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4587   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4588   if (attr != NULL)
4589     pst->dirname = DW_STRING (attr);
4590
4591   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4592
4593   dwarf2_find_base_address (comp_unit_die, cu);
4594
4595   /* Possibly set the default values of LOWPC and HIGHPC from
4596      `DW_AT_ranges'.  */
4597   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4598                                       &best_highpc, cu, pst);
4599   if (has_pc_info == 1 && best_lowpc < best_highpc)
4600     /* Store the contiguous range if it is not empty; it can be empty for
4601        CUs with no code.  */
4602     addrmap_set_empty (objfile->psymtabs_addrmap,
4603                        best_lowpc + baseaddr,
4604                        best_highpc + baseaddr - 1, pst);
4605
4606   /* Check if comp unit has_children.
4607      If so, read the rest of the partial symbols from this comp unit.
4608      If not, there's no more debug_info for this comp unit.  */
4609   if (has_children)
4610     {
4611       struct partial_die_info *first_die;
4612       CORE_ADDR lowpc, highpc;
4613
4614       lowpc = ((CORE_ADDR) -1);
4615       highpc = ((CORE_ADDR) 0);
4616
4617       first_die = load_partial_dies (reader, info_ptr, 1);
4618
4619       scan_partial_symbols (first_die, &lowpc, &highpc,
4620                             ! has_pc_info, cu);
4621
4622       /* If we didn't find a lowpc, set it to highpc to avoid
4623          complaints from `maint check'.  */
4624       if (lowpc == ((CORE_ADDR) -1))
4625         lowpc = highpc;
4626
4627       /* If the compilation unit didn't have an explicit address range,
4628          then use the information extracted from its child dies.  */
4629       if (! has_pc_info)
4630         {
4631           best_lowpc = lowpc;
4632           best_highpc = highpc;
4633         }
4634     }
4635   pst->textlow = best_lowpc + baseaddr;
4636   pst->texthigh = best_highpc + baseaddr;
4637
4638   pst->n_global_syms = objfile->global_psymbols.next -
4639     (objfile->global_psymbols.list + pst->globals_offset);
4640   pst->n_static_syms = objfile->static_psymbols.next -
4641     (objfile->static_psymbols.list + pst->statics_offset);
4642   sort_pst_symbols (pst);
4643
4644   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs))
4645     {
4646       int i;
4647       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs);
4648       struct dwarf2_per_cu_data *iter;
4649
4650       /* Fill in 'dependencies' here; we fill in 'users' in a
4651          post-pass.  */
4652       pst->number_of_dependencies = len;
4653       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4654                                          len * sizeof (struct symtab *));
4655       for (i = 0;
4656            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs,
4657                         i, iter);
4658            ++i)
4659         pst->dependencies[i] = iter->v.psymtab;
4660
4661       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs);
4662     }
4663
4664   /* Get the list of files included in the current compilation unit,
4665      and build a psymtab for each of them.  */
4666   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4667
4668   if (dwarf2_read_debug)
4669     {
4670       struct gdbarch *gdbarch = get_objfile_arch (objfile);
4671
4672       fprintf_unfiltered (gdb_stdlog,
4673                           "Psymtab for %s unit @0x%x: 0x%s - 0x%s"
4674                           ", %d global, %d static syms\n",
4675                           per_cu->is_debug_types ? "type" : "comp",
4676                           per_cu->offset.sect_off,
4677                           paddress (gdbarch, pst->textlow),
4678                           paddress (gdbarch, pst->texthigh),
4679                           pst->n_global_syms, pst->n_static_syms);
4680     }
4681 }
4682
4683 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4684    Process compilation unit THIS_CU for a psymtab.  */
4685
4686 static void
4687 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
4688                            int want_partial_unit)
4689 {
4690   /* If this compilation unit was already read in, free the
4691      cached copy in order to read it in again.  This is
4692      necessary because we skipped some symbols when we first
4693      read in the compilation unit (see load_partial_dies).
4694      This problem could be avoided, but the benefit is unclear.  */
4695   if (this_cu->cu != NULL)
4696     free_one_cached_comp_unit (this_cu);
4697
4698   gdb_assert (! this_cu->is_debug_types);
4699   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
4700                            process_psymtab_comp_unit_reader,
4701                            &want_partial_unit);
4702
4703   /* Age out any secondary CUs.  */
4704   age_cached_comp_units ();
4705 }
4706
4707 static hashval_t
4708 hash_type_unit_group (const void *item)
4709 {
4710   const struct type_unit_group *symtab = item;
4711
4712   return symtab->line_offset.sect_off;
4713 }
4714
4715 static int
4716 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
4717 {
4718   const struct type_unit_group *lhs = item_lhs;
4719   const struct type_unit_group *rhs = item_rhs;
4720
4721   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
4722 }
4723
4724 /* Allocate a hash table for type unit groups.  */
4725
4726 static htab_t
4727 allocate_type_unit_groups_table (void)
4728 {
4729   return htab_create_alloc_ex (3,
4730                                hash_type_unit_group,
4731                                eq_type_unit_group,
4732                                NULL,
4733                                &dwarf2_per_objfile->objfile->objfile_obstack,
4734                                hashtab_obstack_allocate,
4735                                dummy_obstack_deallocate);
4736 }
4737
4738 /* Type units that don't have DW_AT_stmt_list are grouped into their own
4739    partial symtabs.  We combine several TUs per psymtab to not let the size
4740    of any one psymtab grow too big.  */
4741 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
4742 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
4743
4744 /* Helper routine for build_type_psymtabs_reader.
4745    Create the type_unit_group object used to hold one or more TUs.  */
4746
4747 static struct type_unit_group *
4748 create_type_unit_group (struct dwarf2_per_cu_data *per_cu,
4749                         sect_offset line_offset_struct)
4750 {
4751   struct objfile *objfile = dwarf2_per_objfile->objfile;
4752   struct type_unit_group *tu_group;
4753   struct partial_symtab *pst;
4754   unsigned int line_offset;
4755   char *name;
4756
4757   line_offset = line_offset_struct.sect_off;
4758
4759   /* Give the symtab a useful name for debug purposes.  */
4760   if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
4761     name = xstrprintf ("<type_units_%d>",
4762                        (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
4763   else
4764     name = xstrprintf ("<type_units_at_0x%x>", line_offset);
4765
4766   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4767                              struct type_unit_group);
4768
4769   per_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4770                            struct dwarf2_per_cu_data);
4771   per_cu->objfile = objfile;
4772   per_cu->is_debug_types = 1;
4773   per_cu->s.type_unit_group = tu_group;
4774
4775   pst = create_partial_symtab (per_cu, name);
4776   pst->anonymous = 1;
4777
4778   xfree (name);
4779
4780   tu_group->per_cu = per_cu;
4781   tu_group->line_offset.sect_off = line_offset;
4782
4783   return tu_group;
4784 }
4785
4786 /* Look up the type_unit_group for PER_CU, and create it if necessary.
4787    STMT_LIST is an DW_AT_stmt_list attribute.  */
4788
4789 static struct type_unit_group *
4790 get_type_unit_group (struct dwarf2_per_cu_data *per_cu,
4791                      struct attribute *stmt_list)
4792 {
4793   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
4794   struct type_unit_group *tu_group;
4795   void **slot;
4796   unsigned int line_offset;
4797   struct type_unit_group type_unit_group_for_lookup;
4798
4799   if (dwarf2_per_objfile->type_unit_groups == NULL)
4800     {
4801       dwarf2_per_objfile->type_unit_groups =
4802         allocate_type_unit_groups_table ();
4803     }
4804
4805   /* Do we need to create a new group, or can we use an existing one?  */
4806
4807   if (stmt_list)
4808     {
4809       line_offset = DW_UNSND (stmt_list);
4810       ++tu_stats->nr_symtab_sharers;
4811     }
4812   else
4813     {
4814       /* Ugh, no stmt_list.  Rare, but we have to handle it.
4815          We can do various things here like create one group per TU or
4816          spread them over multiple groups to split up the expansion work.
4817          To avoid worst case scenarios (too many groups or too large groups)
4818          we, umm, group them in bunches.  */
4819       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
4820                      | (tu_stats->nr_stmt_less_type_units
4821                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
4822       ++tu_stats->nr_stmt_less_type_units;
4823     }
4824
4825   type_unit_group_for_lookup.line_offset.sect_off = line_offset;
4826   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
4827                          &type_unit_group_for_lookup, INSERT);
4828   if (*slot != NULL)
4829     {
4830       tu_group = *slot;
4831       gdb_assert (tu_group != NULL);
4832     }
4833   else
4834     {
4835       sect_offset line_offset_struct;
4836
4837       line_offset_struct.sect_off = line_offset;
4838       tu_group = create_type_unit_group (per_cu, line_offset_struct);
4839       *slot = tu_group;
4840       ++tu_stats->nr_symtabs;
4841     }
4842
4843   return tu_group;
4844 }
4845
4846 /* Struct used to sort TUs by their abbreviation table offset.  */
4847
4848 struct tu_abbrev_offset
4849 {
4850   struct signatured_type *sig_type;
4851   sect_offset abbrev_offset;
4852 };
4853
4854 /* Helper routine for build_type_unit_groups, passed to qsort.  */
4855
4856 static int
4857 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
4858 {
4859   const struct tu_abbrev_offset * const *a = ap;
4860   const struct tu_abbrev_offset * const *b = bp;
4861   unsigned int aoff = (*a)->abbrev_offset.sect_off;
4862   unsigned int boff = (*b)->abbrev_offset.sect_off;
4863
4864   return (aoff > boff) - (aoff < boff);
4865 }
4866
4867 /* A helper function to add a type_unit_group to a table.  */
4868
4869 static int
4870 add_type_unit_group_to_table (void **slot, void *datum)
4871 {
4872   struct type_unit_group *tu_group = *slot;
4873   struct type_unit_group ***datap = datum;
4874
4875   **datap = tu_group;
4876   ++*datap;
4877
4878   return 1;
4879 }
4880
4881 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
4882    each one passing FUNC,DATA.
4883
4884    The efficiency is because we sort TUs by the abbrev table they use and
4885    only read each abbrev table once.  In one program there are 200K TUs
4886    sharing 8K abbrev tables.
4887
4888    The main purpose of this function is to support building the
4889    dwarf2_per_objfile->type_unit_groups table.
4890    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
4891    can collapse the search space by grouping them by stmt_list.
4892    The savings can be significant, in the same program from above the 200K TUs
4893    share 8K stmt_list tables.
4894
4895    FUNC is expected to call get_type_unit_group, which will create the
4896    struct type_unit_group if necessary and add it to
4897    dwarf2_per_objfile->type_unit_groups.  */
4898
4899 static void
4900 build_type_unit_groups (die_reader_func_ftype *func, void *data)
4901 {
4902   struct objfile *objfile = dwarf2_per_objfile->objfile;
4903   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
4904   struct cleanup *cleanups;
4905   struct abbrev_table *abbrev_table;
4906   sect_offset abbrev_offset;
4907   struct tu_abbrev_offset *sorted_by_abbrev;
4908   struct type_unit_group **iter;
4909   int i;
4910
4911   /* It's up to the caller to not call us multiple times.  */
4912   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
4913
4914   if (dwarf2_per_objfile->n_type_units == 0)
4915     return;
4916
4917   /* TUs typically share abbrev tables, and there can be way more TUs than
4918      abbrev tables.  Sort by abbrev table to reduce the number of times we
4919      read each abbrev table in.
4920      Alternatives are to punt or to maintain a cache of abbrev tables.
4921      This is simpler and efficient enough for now.
4922
4923      Later we group TUs by their DW_AT_stmt_list value (as this defines the
4924      symtab to use).  Typically TUs with the same abbrev offset have the same
4925      stmt_list value too so in practice this should work well.
4926
4927      The basic algorithm here is:
4928
4929       sort TUs by abbrev table
4930       for each TU with same abbrev table:
4931         read abbrev table if first user
4932         read TU top level DIE
4933           [IWBN if DWO skeletons had DW_AT_stmt_list]
4934         call FUNC  */
4935
4936   if (dwarf2_read_debug)
4937     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
4938
4939   /* Sort in a separate table to maintain the order of all_type_units
4940      for .gdb_index: TU indices directly index all_type_units.  */
4941   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
4942                               dwarf2_per_objfile->n_type_units);
4943   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
4944     {
4945       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
4946
4947       sorted_by_abbrev[i].sig_type = sig_type;
4948       sorted_by_abbrev[i].abbrev_offset =
4949         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
4950                             sig_type->per_cu.offset);
4951     }
4952   cleanups = make_cleanup (xfree, sorted_by_abbrev);
4953   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
4954          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
4955
4956   memset (tu_stats, 0, sizeof (*tu_stats));
4957   abbrev_offset.sect_off = ~(unsigned) 0;
4958   abbrev_table = NULL;
4959   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
4960
4961   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
4962     {
4963       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
4964
4965       /* Switch to the next abbrev table if necessary.  */
4966       if (abbrev_table == NULL
4967           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
4968         {
4969           if (abbrev_table != NULL)
4970             {
4971               abbrev_table_free (abbrev_table);
4972               /* Reset to NULL in case abbrev_table_read_table throws
4973                  an error: abbrev_table_free_cleanup will get called.  */
4974               abbrev_table = NULL;
4975             }
4976           abbrev_offset = tu->abbrev_offset;
4977           abbrev_table =
4978             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
4979                                      abbrev_offset);
4980           ++tu_stats->nr_uniq_abbrev_tables;
4981         }
4982
4983       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
4984                                func, data);
4985     }
4986
4987   /* Create a vector of pointers to primary type units to make it easy to
4988      iterate over them and CUs.  See dw2_get_primary_cu.  */
4989   dwarf2_per_objfile->n_type_unit_groups =
4990     htab_elements (dwarf2_per_objfile->type_unit_groups);
4991   dwarf2_per_objfile->all_type_unit_groups =
4992     obstack_alloc (&objfile->objfile_obstack,
4993                    dwarf2_per_objfile->n_type_unit_groups
4994                    * sizeof (struct type_unit_group *));
4995   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
4996   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
4997                           add_type_unit_group_to_table, &iter);
4998   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
4999               == dwarf2_per_objfile->n_type_unit_groups);
5000
5001   do_cleanups (cleanups);
5002
5003   if (dwarf2_read_debug)
5004     {
5005       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5006       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5007                           dwarf2_per_objfile->n_type_units);
5008       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5009                           tu_stats->nr_uniq_abbrev_tables);
5010       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5011                           tu_stats->nr_symtabs);
5012       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5013                           tu_stats->nr_symtab_sharers);
5014       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5015                           tu_stats->nr_stmt_less_type_units);
5016     }
5017 }
5018
5019 /* Reader function for build_type_psymtabs.  */
5020
5021 static void
5022 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5023                             gdb_byte *info_ptr,
5024                             struct die_info *type_unit_die,
5025                             int has_children,
5026                             void *data)
5027 {
5028   struct objfile *objfile = dwarf2_per_objfile->objfile;
5029   struct dwarf2_cu *cu = reader->cu;
5030   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5031   struct type_unit_group *tu_group;
5032   struct attribute *attr;
5033   struct partial_die_info *first_die;
5034   CORE_ADDR lowpc, highpc;
5035   struct partial_symtab *pst;
5036
5037   gdb_assert (data == NULL);
5038
5039   if (! has_children)
5040     return;
5041
5042   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5043   tu_group = get_type_unit_group (per_cu, attr);
5044
5045   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->tus, per_cu);
5046
5047   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5048   cu->list_in_scope = &file_symbols;
5049   pst = create_partial_symtab (per_cu, "");
5050   pst->anonymous = 1;
5051
5052   first_die = load_partial_dies (reader, info_ptr, 1);
5053
5054   lowpc = (CORE_ADDR) -1;
5055   highpc = (CORE_ADDR) 0;
5056   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5057
5058   pst->n_global_syms = objfile->global_psymbols.next -
5059     (objfile->global_psymbols.list + pst->globals_offset);
5060   pst->n_static_syms = objfile->static_psymbols.next -
5061     (objfile->static_psymbols.list + pst->statics_offset);
5062   sort_pst_symbols (pst);
5063 }
5064
5065 /* Traversal function for build_type_psymtabs.  */
5066
5067 static int
5068 build_type_psymtab_dependencies (void **slot, void *info)
5069 {
5070   struct objfile *objfile = dwarf2_per_objfile->objfile;
5071   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5072   struct dwarf2_per_cu_data *per_cu = tu_group->per_cu;
5073   struct partial_symtab *pst = per_cu->v.psymtab;
5074   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->tus);
5075   struct dwarf2_per_cu_data *iter;
5076   int i;
5077
5078   gdb_assert (len > 0);
5079
5080   pst->number_of_dependencies = len;
5081   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5082                                      len * sizeof (struct psymtab *));
5083   for (i = 0;
5084        VEC_iterate (dwarf2_per_cu_ptr, tu_group->tus, i, iter);
5085        ++i)
5086     {
5087       pst->dependencies[i] = iter->v.psymtab;
5088       iter->s.type_unit_group = tu_group;
5089     }
5090
5091   VEC_free (dwarf2_per_cu_ptr, tu_group->tus);
5092
5093   return 1;
5094 }
5095
5096 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5097    Build partial symbol tables for the .debug_types comp-units.  */
5098
5099 static void
5100 build_type_psymtabs (struct objfile *objfile)
5101 {
5102   if (! create_all_type_units (objfile))
5103     return;
5104
5105   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5106
5107   /* Now that all TUs have been processed we can fill in the dependencies.  */
5108   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5109                           build_type_psymtab_dependencies, NULL);
5110 }
5111
5112 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5113
5114 static void
5115 psymtabs_addrmap_cleanup (void *o)
5116 {
5117   struct objfile *objfile = o;
5118
5119   objfile->psymtabs_addrmap = NULL;
5120 }
5121
5122 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5123
5124 static void
5125 set_partial_user (struct objfile *objfile)
5126 {
5127   int i;
5128
5129   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5130     {
5131       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5132       struct partial_symtab *pst = per_cu->v.psymtab;
5133       int j;
5134
5135       for (j = 0; j < pst->number_of_dependencies; ++j)
5136         {
5137           /* Set the 'user' field only if it is not already set.  */
5138           if (pst->dependencies[j]->user == NULL)
5139             pst->dependencies[j]->user = pst;
5140         }
5141     }
5142 }
5143
5144 /* Build the partial symbol table by doing a quick pass through the
5145    .debug_info and .debug_abbrev sections.  */
5146
5147 static void
5148 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5149 {
5150   struct cleanup *back_to, *addrmap_cleanup;
5151   struct obstack temp_obstack;
5152   int i;
5153
5154   if (dwarf2_read_debug)
5155     {
5156       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5157                           objfile->name);
5158     }
5159
5160   dwarf2_per_objfile->reading_partial_symbols = 1;
5161
5162   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5163
5164   /* Any cached compilation units will be linked by the per-objfile
5165      read_in_chain.  Make sure to free them when we're done.  */
5166   back_to = make_cleanup (free_cached_comp_units, NULL);
5167
5168   build_type_psymtabs (objfile);
5169
5170   create_all_comp_units (objfile);
5171
5172   /* Create a temporary address map on a temporary obstack.  We later
5173      copy this to the final obstack.  */
5174   obstack_init (&temp_obstack);
5175   make_cleanup_obstack_free (&temp_obstack);
5176   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5177   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5178
5179   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5180     {
5181       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5182
5183       process_psymtab_comp_unit (per_cu, 0);
5184     }
5185
5186   set_partial_user (objfile);
5187
5188   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5189                                                     &objfile->objfile_obstack);
5190   discard_cleanups (addrmap_cleanup);
5191
5192   do_cleanups (back_to);
5193
5194   if (dwarf2_read_debug)
5195     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5196                         objfile->name);
5197 }
5198
5199 /* die_reader_func for load_partial_comp_unit.  */
5200
5201 static void
5202 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5203                                gdb_byte *info_ptr,
5204                                struct die_info *comp_unit_die,
5205                                int has_children,
5206                                void *data)
5207 {
5208   struct dwarf2_cu *cu = reader->cu;
5209
5210   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5211
5212   /* Check if comp unit has_children.
5213      If so, read the rest of the partial symbols from this comp unit.
5214      If not, there's no more debug_info for this comp unit.  */
5215   if (has_children)
5216     load_partial_dies (reader, info_ptr, 0);
5217 }
5218
5219 /* Load the partial DIEs for a secondary CU into memory.
5220    This is also used when rereading a primary CU with load_all_dies.  */
5221
5222 static void
5223 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5224 {
5225   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5226                            load_partial_comp_unit_reader, NULL);
5227 }
5228
5229 /* Create a list of all compilation units in OBJFILE.
5230    This is only done for -readnow and building partial symtabs.  */
5231
5232 static void
5233 create_all_comp_units (struct objfile *objfile)
5234 {
5235   int n_allocated;
5236   int n_comp_units;
5237   struct dwarf2_per_cu_data **all_comp_units;
5238   gdb_byte *info_ptr;
5239
5240   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5241   info_ptr = dwarf2_per_objfile->info.buffer;
5242
5243   n_comp_units = 0;
5244   n_allocated = 10;
5245   all_comp_units = xmalloc (n_allocated
5246                             * sizeof (struct dwarf2_per_cu_data *));
5247
5248   while (info_ptr < dwarf2_per_objfile->info.buffer
5249          + dwarf2_per_objfile->info.size)
5250     {
5251       unsigned int length, initial_length_size;
5252       struct dwarf2_per_cu_data *this_cu;
5253       sect_offset offset;
5254
5255       offset.sect_off = info_ptr - dwarf2_per_objfile->info.buffer;
5256
5257       /* Read just enough information to find out where the next
5258          compilation unit is.  */
5259       length = read_initial_length (objfile->obfd, info_ptr,
5260                                     &initial_length_size);
5261
5262       /* Save the compilation unit for later lookup.  */
5263       this_cu = obstack_alloc (&objfile->objfile_obstack,
5264                                sizeof (struct dwarf2_per_cu_data));
5265       memset (this_cu, 0, sizeof (*this_cu));
5266       this_cu->offset = offset;
5267       this_cu->length = length + initial_length_size;
5268       this_cu->objfile = objfile;
5269       this_cu->info_or_types_section = &dwarf2_per_objfile->info;
5270
5271       if (n_comp_units == n_allocated)
5272         {
5273           n_allocated *= 2;
5274           all_comp_units = xrealloc (all_comp_units,
5275                                      n_allocated
5276                                      * sizeof (struct dwarf2_per_cu_data *));
5277         }
5278       all_comp_units[n_comp_units++] = this_cu;
5279
5280       info_ptr = info_ptr + this_cu->length;
5281     }
5282
5283   dwarf2_per_objfile->all_comp_units
5284     = obstack_alloc (&objfile->objfile_obstack,
5285                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5286   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5287           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5288   xfree (all_comp_units);
5289   dwarf2_per_objfile->n_comp_units = n_comp_units;
5290 }
5291
5292 /* Process all loaded DIEs for compilation unit CU, starting at
5293    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5294    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5295    DW_AT_ranges).  If NEED_PC is set, then this function will set
5296    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5297    and record the covered ranges in the addrmap.  */
5298
5299 static void
5300 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5301                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5302 {
5303   struct partial_die_info *pdi;
5304
5305   /* Now, march along the PDI's, descending into ones which have
5306      interesting children but skipping the children of the other ones,
5307      until we reach the end of the compilation unit.  */
5308
5309   pdi = first_die;
5310
5311   while (pdi != NULL)
5312     {
5313       fixup_partial_die (pdi, cu);
5314
5315       /* Anonymous namespaces or modules have no name but have interesting
5316          children, so we need to look at them.  Ditto for anonymous
5317          enums.  */
5318
5319       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5320           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5321           || pdi->tag == DW_TAG_imported_unit)
5322         {
5323           switch (pdi->tag)
5324             {
5325             case DW_TAG_subprogram:
5326               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5327               break;
5328             case DW_TAG_constant:
5329             case DW_TAG_variable:
5330             case DW_TAG_typedef:
5331             case DW_TAG_union_type:
5332               if (!pdi->is_declaration)
5333                 {
5334                   add_partial_symbol (pdi, cu);
5335                 }
5336               break;
5337             case DW_TAG_class_type:
5338             case DW_TAG_interface_type:
5339             case DW_TAG_structure_type:
5340               if (!pdi->is_declaration)
5341                 {
5342                   add_partial_symbol (pdi, cu);
5343                 }
5344               break;
5345             case DW_TAG_enumeration_type:
5346               if (!pdi->is_declaration)
5347                 add_partial_enumeration (pdi, cu);
5348               break;
5349             case DW_TAG_base_type:
5350             case DW_TAG_subrange_type:
5351               /* File scope base type definitions are added to the partial
5352                  symbol table.  */
5353               add_partial_symbol (pdi, cu);
5354               break;
5355             case DW_TAG_namespace:
5356               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5357               break;
5358             case DW_TAG_module:
5359               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5360               break;
5361             case DW_TAG_imported_unit:
5362               {
5363                 struct dwarf2_per_cu_data *per_cu;
5364
5365                 /* For now we don't handle imported units in type units.  */
5366                 if (cu->per_cu->is_debug_types)
5367                   {
5368                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5369                              " supported in type units [in module %s]"),
5370                            cu->objfile->name);
5371                   }
5372
5373                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5374                                                            cu->objfile);
5375
5376                 /* Go read the partial unit, if needed.  */
5377                 if (per_cu->v.psymtab == NULL)
5378                   process_psymtab_comp_unit (per_cu, 1);
5379
5380                 VEC_safe_push (dwarf2_per_cu_ptr,
5381                                cu->per_cu->s.imported_symtabs, per_cu);
5382               }
5383               break;
5384             default:
5385               break;
5386             }
5387         }
5388
5389       /* If the die has a sibling, skip to the sibling.  */
5390
5391       pdi = pdi->die_sibling;
5392     }
5393 }
5394
5395 /* Functions used to compute the fully scoped name of a partial DIE.
5396
5397    Normally, this is simple.  For C++, the parent DIE's fully scoped
5398    name is concatenated with "::" and the partial DIE's name.  For
5399    Java, the same thing occurs except that "." is used instead of "::".
5400    Enumerators are an exception; they use the scope of their parent
5401    enumeration type, i.e. the name of the enumeration type is not
5402    prepended to the enumerator.
5403
5404    There are two complexities.  One is DW_AT_specification; in this
5405    case "parent" means the parent of the target of the specification,
5406    instead of the direct parent of the DIE.  The other is compilers
5407    which do not emit DW_TAG_namespace; in this case we try to guess
5408    the fully qualified name of structure types from their members'
5409    linkage names.  This must be done using the DIE's children rather
5410    than the children of any DW_AT_specification target.  We only need
5411    to do this for structures at the top level, i.e. if the target of
5412    any DW_AT_specification (if any; otherwise the DIE itself) does not
5413    have a parent.  */
5414
5415 /* Compute the scope prefix associated with PDI's parent, in
5416    compilation unit CU.  The result will be allocated on CU's
5417    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5418    field.  NULL is returned if no prefix is necessary.  */
5419 static char *
5420 partial_die_parent_scope (struct partial_die_info *pdi,
5421                           struct dwarf2_cu *cu)
5422 {
5423   char *grandparent_scope;
5424   struct partial_die_info *parent, *real_pdi;
5425
5426   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5427      then this means the parent of the specification DIE.  */
5428
5429   real_pdi = pdi;
5430   while (real_pdi->has_specification)
5431     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
5432
5433   parent = real_pdi->die_parent;
5434   if (parent == NULL)
5435     return NULL;
5436
5437   if (parent->scope_set)
5438     return parent->scope;
5439
5440   fixup_partial_die (parent, cu);
5441
5442   grandparent_scope = partial_die_parent_scope (parent, cu);
5443
5444   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5445      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5446      Work around this problem here.  */
5447   if (cu->language == language_cplus
5448       && parent->tag == DW_TAG_namespace
5449       && strcmp (parent->name, "::") == 0
5450       && grandparent_scope == NULL)
5451     {
5452       parent->scope = NULL;
5453       parent->scope_set = 1;
5454       return NULL;
5455     }
5456
5457   if (pdi->tag == DW_TAG_enumerator)
5458     /* Enumerators should not get the name of the enumeration as a prefix.  */
5459     parent->scope = grandparent_scope;
5460   else if (parent->tag == DW_TAG_namespace
5461       || parent->tag == DW_TAG_module
5462       || parent->tag == DW_TAG_structure_type
5463       || parent->tag == DW_TAG_class_type
5464       || parent->tag == DW_TAG_interface_type
5465       || parent->tag == DW_TAG_union_type
5466       || parent->tag == DW_TAG_enumeration_type)
5467     {
5468       if (grandparent_scope == NULL)
5469         parent->scope = parent->name;
5470       else
5471         parent->scope = typename_concat (&cu->comp_unit_obstack,
5472                                          grandparent_scope,
5473                                          parent->name, 0, cu);
5474     }
5475   else
5476     {
5477       /* FIXME drow/2004-04-01: What should we be doing with
5478          function-local names?  For partial symbols, we should probably be
5479          ignoring them.  */
5480       complaint (&symfile_complaints,
5481                  _("unhandled containing DIE tag %d for DIE at %d"),
5482                  parent->tag, pdi->offset.sect_off);
5483       parent->scope = grandparent_scope;
5484     }
5485
5486   parent->scope_set = 1;
5487   return parent->scope;
5488 }
5489
5490 /* Return the fully scoped name associated with PDI, from compilation unit
5491    CU.  The result will be allocated with malloc.  */
5492
5493 static char *
5494 partial_die_full_name (struct partial_die_info *pdi,
5495                        struct dwarf2_cu *cu)
5496 {
5497   char *parent_scope;
5498
5499   /* If this is a template instantiation, we can not work out the
5500      template arguments from partial DIEs.  So, unfortunately, we have
5501      to go through the full DIEs.  At least any work we do building
5502      types here will be reused if full symbols are loaded later.  */
5503   if (pdi->has_template_arguments)
5504     {
5505       fixup_partial_die (pdi, cu);
5506
5507       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5508         {
5509           struct die_info *die;
5510           struct attribute attr;
5511           struct dwarf2_cu *ref_cu = cu;
5512
5513           /* DW_FORM_ref_addr is using section offset.  */
5514           attr.name = 0;
5515           attr.form = DW_FORM_ref_addr;
5516           attr.u.unsnd = pdi->offset.sect_off;
5517           die = follow_die_ref (NULL, &attr, &ref_cu);
5518
5519           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5520         }
5521     }
5522
5523   parent_scope = partial_die_parent_scope (pdi, cu);
5524   if (parent_scope == NULL)
5525     return NULL;
5526   else
5527     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5528 }
5529
5530 static void
5531 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5532 {
5533   struct objfile *objfile = cu->objfile;
5534   CORE_ADDR addr = 0;
5535   char *actual_name = NULL;
5536   CORE_ADDR baseaddr;
5537   int built_actual_name = 0;
5538
5539   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5540
5541   actual_name = partial_die_full_name (pdi, cu);
5542   if (actual_name)
5543     built_actual_name = 1;
5544
5545   if (actual_name == NULL)
5546     actual_name = pdi->name;
5547
5548   switch (pdi->tag)
5549     {
5550     case DW_TAG_subprogram:
5551       if (pdi->is_external || cu->language == language_ada)
5552         {
5553           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5554              of the global scope.  But in Ada, we want to be able to access
5555              nested procedures globally.  So all Ada subprograms are stored
5556              in the global scope.  */
5557           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5558              mst_text, objfile); */
5559           add_psymbol_to_list (actual_name, strlen (actual_name),
5560                                built_actual_name,
5561                                VAR_DOMAIN, LOC_BLOCK,
5562                                &objfile->global_psymbols,
5563                                0, pdi->lowpc + baseaddr,
5564                                cu->language, objfile);
5565         }
5566       else
5567         {
5568           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5569              mst_file_text, objfile); */
5570           add_psymbol_to_list (actual_name, strlen (actual_name),
5571                                built_actual_name,
5572                                VAR_DOMAIN, LOC_BLOCK,
5573                                &objfile->static_psymbols,
5574                                0, pdi->lowpc + baseaddr,
5575                                cu->language, objfile);
5576         }
5577       break;
5578     case DW_TAG_constant:
5579       {
5580         struct psymbol_allocation_list *list;
5581
5582         if (pdi->is_external)
5583           list = &objfile->global_psymbols;
5584         else
5585           list = &objfile->static_psymbols;
5586         add_psymbol_to_list (actual_name, strlen (actual_name),
5587                              built_actual_name, VAR_DOMAIN, LOC_STATIC,
5588                              list, 0, 0, cu->language, objfile);
5589       }
5590       break;
5591     case DW_TAG_variable:
5592       if (pdi->d.locdesc)
5593         addr = decode_locdesc (pdi->d.locdesc, cu);
5594
5595       if (pdi->d.locdesc
5596           && addr == 0
5597           && !dwarf2_per_objfile->has_section_at_zero)
5598         {
5599           /* A global or static variable may also have been stripped
5600              out by the linker if unused, in which case its address
5601              will be nullified; do not add such variables into partial
5602              symbol table then.  */
5603         }
5604       else if (pdi->is_external)
5605         {
5606           /* Global Variable.
5607              Don't enter into the minimal symbol tables as there is
5608              a minimal symbol table entry from the ELF symbols already.
5609              Enter into partial symbol table if it has a location
5610              descriptor or a type.
5611              If the location descriptor is missing, new_symbol will create
5612              a LOC_UNRESOLVED symbol, the address of the variable will then
5613              be determined from the minimal symbol table whenever the variable
5614              is referenced.
5615              The address for the partial symbol table entry is not
5616              used by GDB, but it comes in handy for debugging partial symbol
5617              table building.  */
5618
5619           if (pdi->d.locdesc || pdi->has_type)
5620             add_psymbol_to_list (actual_name, strlen (actual_name),
5621                                  built_actual_name,
5622                                  VAR_DOMAIN, LOC_STATIC,
5623                                  &objfile->global_psymbols,
5624                                  0, addr + baseaddr,
5625                                  cu->language, objfile);
5626         }
5627       else
5628         {
5629           /* Static Variable.  Skip symbols without location descriptors.  */
5630           if (pdi->d.locdesc == NULL)
5631             {
5632               if (built_actual_name)
5633                 xfree (actual_name);
5634               return;
5635             }
5636           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
5637              mst_file_data, objfile); */
5638           add_psymbol_to_list (actual_name, strlen (actual_name),
5639                                built_actual_name,
5640                                VAR_DOMAIN, LOC_STATIC,
5641                                &objfile->static_psymbols,
5642                                0, addr + baseaddr,
5643                                cu->language, objfile);
5644         }
5645       break;
5646     case DW_TAG_typedef:
5647     case DW_TAG_base_type:
5648     case DW_TAG_subrange_type:
5649       add_psymbol_to_list (actual_name, strlen (actual_name),
5650                            built_actual_name,
5651                            VAR_DOMAIN, LOC_TYPEDEF,
5652                            &objfile->static_psymbols,
5653                            0, (CORE_ADDR) 0, cu->language, objfile);
5654       break;
5655     case DW_TAG_namespace:
5656       add_psymbol_to_list (actual_name, strlen (actual_name),
5657                            built_actual_name,
5658                            VAR_DOMAIN, LOC_TYPEDEF,
5659                            &objfile->global_psymbols,
5660                            0, (CORE_ADDR) 0, cu->language, objfile);
5661       break;
5662     case DW_TAG_class_type:
5663     case DW_TAG_interface_type:
5664     case DW_TAG_structure_type:
5665     case DW_TAG_union_type:
5666     case DW_TAG_enumeration_type:
5667       /* Skip external references.  The DWARF standard says in the section
5668          about "Structure, Union, and Class Type Entries": "An incomplete
5669          structure, union or class type is represented by a structure,
5670          union or class entry that does not have a byte size attribute
5671          and that has a DW_AT_declaration attribute."  */
5672       if (!pdi->has_byte_size && pdi->is_declaration)
5673         {
5674           if (built_actual_name)
5675             xfree (actual_name);
5676           return;
5677         }
5678
5679       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
5680          static vs. global.  */
5681       add_psymbol_to_list (actual_name, strlen (actual_name),
5682                            built_actual_name,
5683                            STRUCT_DOMAIN, LOC_TYPEDEF,
5684                            (cu->language == language_cplus
5685                             || cu->language == language_java)
5686                            ? &objfile->global_psymbols
5687                            : &objfile->static_psymbols,
5688                            0, (CORE_ADDR) 0, cu->language, objfile);
5689
5690       break;
5691     case DW_TAG_enumerator:
5692       add_psymbol_to_list (actual_name, strlen (actual_name),
5693                            built_actual_name,
5694                            VAR_DOMAIN, LOC_CONST,
5695                            (cu->language == language_cplus
5696                             || cu->language == language_java)
5697                            ? &objfile->global_psymbols
5698                            : &objfile->static_psymbols,
5699                            0, (CORE_ADDR) 0, cu->language, objfile);
5700       break;
5701     default:
5702       break;
5703     }
5704
5705   if (built_actual_name)
5706     xfree (actual_name);
5707 }
5708
5709 /* Read a partial die corresponding to a namespace; also, add a symbol
5710    corresponding to that namespace to the symbol table.  NAMESPACE is
5711    the name of the enclosing namespace.  */
5712
5713 static void
5714 add_partial_namespace (struct partial_die_info *pdi,
5715                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
5716                        int need_pc, struct dwarf2_cu *cu)
5717 {
5718   /* Add a symbol for the namespace.  */
5719
5720   add_partial_symbol (pdi, cu);
5721
5722   /* Now scan partial symbols in that namespace.  */
5723
5724   if (pdi->has_children)
5725     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
5726 }
5727
5728 /* Read a partial die corresponding to a Fortran module.  */
5729
5730 static void
5731 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
5732                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5733 {
5734   /* Now scan partial symbols in that module.  */
5735
5736   if (pdi->has_children)
5737     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
5738 }
5739
5740 /* Read a partial die corresponding to a subprogram and create a partial
5741    symbol for that subprogram.  When the CU language allows it, this
5742    routine also defines a partial symbol for each nested subprogram
5743    that this subprogram contains.
5744
5745    DIE my also be a lexical block, in which case we simply search
5746    recursively for suprograms defined inside that lexical block.
5747    Again, this is only performed when the CU language allows this
5748    type of definitions.  */
5749
5750 static void
5751 add_partial_subprogram (struct partial_die_info *pdi,
5752                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
5753                         int need_pc, struct dwarf2_cu *cu)
5754 {
5755   if (pdi->tag == DW_TAG_subprogram)
5756     {
5757       if (pdi->has_pc_info)
5758         {
5759           if (pdi->lowpc < *lowpc)
5760             *lowpc = pdi->lowpc;
5761           if (pdi->highpc > *highpc)
5762             *highpc = pdi->highpc;
5763           if (need_pc)
5764             {
5765               CORE_ADDR baseaddr;
5766               struct objfile *objfile = cu->objfile;
5767
5768               baseaddr = ANOFFSET (objfile->section_offsets,
5769                                    SECT_OFF_TEXT (objfile));
5770               addrmap_set_empty (objfile->psymtabs_addrmap,
5771                                  pdi->lowpc + baseaddr,
5772                                  pdi->highpc - 1 + baseaddr,
5773                                  cu->per_cu->v.psymtab);
5774             }
5775         }
5776
5777       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
5778         {
5779           if (!pdi->is_declaration)
5780             /* Ignore subprogram DIEs that do not have a name, they are
5781                illegal.  Do not emit a complaint at this point, we will
5782                do so when we convert this psymtab into a symtab.  */
5783             if (pdi->name)
5784               add_partial_symbol (pdi, cu);
5785         }
5786     }
5787
5788   if (! pdi->has_children)
5789     return;
5790
5791   if (cu->language == language_ada)
5792     {
5793       pdi = pdi->die_child;
5794       while (pdi != NULL)
5795         {
5796           fixup_partial_die (pdi, cu);
5797           if (pdi->tag == DW_TAG_subprogram
5798               || pdi->tag == DW_TAG_lexical_block)
5799             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5800           pdi = pdi->die_sibling;
5801         }
5802     }
5803 }
5804
5805 /* Read a partial die corresponding to an enumeration type.  */
5806
5807 static void
5808 add_partial_enumeration (struct partial_die_info *enum_pdi,
5809                          struct dwarf2_cu *cu)
5810 {
5811   struct partial_die_info *pdi;
5812
5813   if (enum_pdi->name != NULL)
5814     add_partial_symbol (enum_pdi, cu);
5815
5816   pdi = enum_pdi->die_child;
5817   while (pdi)
5818     {
5819       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
5820         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
5821       else
5822         add_partial_symbol (pdi, cu);
5823       pdi = pdi->die_sibling;
5824     }
5825 }
5826
5827 /* Return the initial uleb128 in the die at INFO_PTR.  */
5828
5829 static unsigned int
5830 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
5831 {
5832   unsigned int bytes_read;
5833
5834   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5835 }
5836
5837 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
5838    Return the corresponding abbrev, or NULL if the number is zero (indicating
5839    an empty DIE).  In either case *BYTES_READ will be set to the length of
5840    the initial number.  */
5841
5842 static struct abbrev_info *
5843 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
5844                  struct dwarf2_cu *cu)
5845 {
5846   bfd *abfd = cu->objfile->obfd;
5847   unsigned int abbrev_number;
5848   struct abbrev_info *abbrev;
5849
5850   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
5851
5852   if (abbrev_number == 0)
5853     return NULL;
5854
5855   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
5856   if (!abbrev)
5857     {
5858       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
5859              abbrev_number, bfd_get_filename (abfd));
5860     }
5861
5862   return abbrev;
5863 }
5864
5865 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5866    Returns a pointer to the end of a series of DIEs, terminated by an empty
5867    DIE.  Any children of the skipped DIEs will also be skipped.  */
5868
5869 static gdb_byte *
5870 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
5871 {
5872   struct dwarf2_cu *cu = reader->cu;
5873   struct abbrev_info *abbrev;
5874   unsigned int bytes_read;
5875
5876   while (1)
5877     {
5878       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
5879       if (abbrev == NULL)
5880         return info_ptr + bytes_read;
5881       else
5882         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
5883     }
5884 }
5885
5886 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5887    INFO_PTR should point just after the initial uleb128 of a DIE, and the
5888    abbrev corresponding to that skipped uleb128 should be passed in
5889    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
5890    children.  */
5891
5892 static gdb_byte *
5893 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
5894               struct abbrev_info *abbrev)
5895 {
5896   unsigned int bytes_read;
5897   struct attribute attr;
5898   bfd *abfd = reader->abfd;
5899   struct dwarf2_cu *cu = reader->cu;
5900   gdb_byte *buffer = reader->buffer;
5901   const gdb_byte *buffer_end = reader->buffer_end;
5902   gdb_byte *start_info_ptr = info_ptr;
5903   unsigned int form, i;
5904
5905   for (i = 0; i < abbrev->num_attrs; i++)
5906     {
5907       /* The only abbrev we care about is DW_AT_sibling.  */
5908       if (abbrev->attrs[i].name == DW_AT_sibling)
5909         {
5910           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
5911           if (attr.form == DW_FORM_ref_addr)
5912             complaint (&symfile_complaints,
5913                        _("ignoring absolute DW_AT_sibling"));
5914           else
5915             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
5916         }
5917
5918       /* If it isn't DW_AT_sibling, skip this attribute.  */
5919       form = abbrev->attrs[i].form;
5920     skip_attribute:
5921       switch (form)
5922         {
5923         case DW_FORM_ref_addr:
5924           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
5925              and later it is offset sized.  */
5926           if (cu->header.version == 2)
5927             info_ptr += cu->header.addr_size;
5928           else
5929             info_ptr += cu->header.offset_size;
5930           break;
5931         case DW_FORM_addr:
5932           info_ptr += cu->header.addr_size;
5933           break;
5934         case DW_FORM_data1:
5935         case DW_FORM_ref1:
5936         case DW_FORM_flag:
5937           info_ptr += 1;
5938           break;
5939         case DW_FORM_flag_present:
5940           break;
5941         case DW_FORM_data2:
5942         case DW_FORM_ref2:
5943           info_ptr += 2;
5944           break;
5945         case DW_FORM_data4:
5946         case DW_FORM_ref4:
5947           info_ptr += 4;
5948           break;
5949         case DW_FORM_data8:
5950         case DW_FORM_ref8:
5951         case DW_FORM_ref_sig8:
5952           info_ptr += 8;
5953           break;
5954         case DW_FORM_string:
5955           read_direct_string (abfd, info_ptr, &bytes_read);
5956           info_ptr += bytes_read;
5957           break;
5958         case DW_FORM_sec_offset:
5959         case DW_FORM_strp:
5960           info_ptr += cu->header.offset_size;
5961           break;
5962         case DW_FORM_exprloc:
5963         case DW_FORM_block:
5964           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5965           info_ptr += bytes_read;
5966           break;
5967         case DW_FORM_block1:
5968           info_ptr += 1 + read_1_byte (abfd, info_ptr);
5969           break;
5970         case DW_FORM_block2:
5971           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
5972           break;
5973         case DW_FORM_block4:
5974           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
5975           break;
5976         case DW_FORM_sdata:
5977         case DW_FORM_udata:
5978         case DW_FORM_ref_udata:
5979         case DW_FORM_GNU_addr_index:
5980         case DW_FORM_GNU_str_index:
5981           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
5982           break;
5983         case DW_FORM_indirect:
5984           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5985           info_ptr += bytes_read;
5986           /* We need to continue parsing from here, so just go back to
5987              the top.  */
5988           goto skip_attribute;
5989
5990         default:
5991           error (_("Dwarf Error: Cannot handle %s "
5992                    "in DWARF reader [in module %s]"),
5993                  dwarf_form_name (form),
5994                  bfd_get_filename (abfd));
5995         }
5996     }
5997
5998   if (abbrev->has_children)
5999     return skip_children (reader, info_ptr);
6000   else
6001     return info_ptr;
6002 }
6003
6004 /* Locate ORIG_PDI's sibling.
6005    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6006
6007 static gdb_byte *
6008 locate_pdi_sibling (const struct die_reader_specs *reader,
6009                     struct partial_die_info *orig_pdi,
6010                     gdb_byte *info_ptr)
6011 {
6012   /* Do we know the sibling already?  */
6013
6014   if (orig_pdi->sibling)
6015     return orig_pdi->sibling;
6016
6017   /* Are there any children to deal with?  */
6018
6019   if (!orig_pdi->has_children)
6020     return info_ptr;
6021
6022   /* Skip the children the long way.  */
6023
6024   return skip_children (reader, info_ptr);
6025 }
6026
6027 /* Expand this partial symbol table into a full symbol table.  */
6028
6029 static void
6030 dwarf2_psymtab_to_symtab (struct partial_symtab *pst)
6031 {
6032   if (pst != NULL)
6033     {
6034       if (pst->readin)
6035         {
6036           warning (_("bug: psymtab for %s is already read in."),
6037                    pst->filename);
6038         }
6039       else
6040         {
6041           if (info_verbose)
6042             {
6043               printf_filtered (_("Reading in symbols for %s..."),
6044                                pst->filename);
6045               gdb_flush (gdb_stdout);
6046             }
6047
6048           /* Restore our global data.  */
6049           dwarf2_per_objfile = objfile_data (pst->objfile,
6050                                              dwarf2_objfile_data_key);
6051
6052           /* If this psymtab is constructed from a debug-only objfile, the
6053              has_section_at_zero flag will not necessarily be correct.  We
6054              can get the correct value for this flag by looking at the data
6055              associated with the (presumably stripped) associated objfile.  */
6056           if (pst->objfile->separate_debug_objfile_backlink)
6057             {
6058               struct dwarf2_per_objfile *dpo_backlink
6059                 = objfile_data (pst->objfile->separate_debug_objfile_backlink,
6060                                 dwarf2_objfile_data_key);
6061
6062               dwarf2_per_objfile->has_section_at_zero
6063                 = dpo_backlink->has_section_at_zero;
6064             }
6065
6066           dwarf2_per_objfile->reading_partial_symbols = 0;
6067
6068           psymtab_to_symtab_1 (pst);
6069
6070           /* Finish up the debug error message.  */
6071           if (info_verbose)
6072             printf_filtered (_("done.\n"));
6073         }
6074     }
6075
6076   process_cu_includes ();
6077 }
6078 \f
6079 /* Reading in full CUs.  */
6080
6081 /* Add PER_CU to the queue.  */
6082
6083 static void
6084 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6085                  enum language pretend_language)
6086 {
6087   struct dwarf2_queue_item *item;
6088
6089   per_cu->queued = 1;
6090   item = xmalloc (sizeof (*item));
6091   item->per_cu = per_cu;
6092   item->pretend_language = pretend_language;
6093   item->next = NULL;
6094
6095   if (dwarf2_queue == NULL)
6096     dwarf2_queue = item;
6097   else
6098     dwarf2_queue_tail->next = item;
6099
6100   dwarf2_queue_tail = item;
6101 }
6102
6103 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6104    unit and add it to our queue.
6105    The result is non-zero if PER_CU was queued, otherwise the result is zero
6106    meaning either PER_CU is already queued or it is already loaded.  */
6107
6108 static int
6109 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6110                        struct dwarf2_per_cu_data *per_cu,
6111                        enum language pretend_language)
6112 {
6113   /* We may arrive here during partial symbol reading, if we need full
6114      DIEs to process an unusual case (e.g. template arguments).  Do
6115      not queue PER_CU, just tell our caller to load its DIEs.  */
6116   if (dwarf2_per_objfile->reading_partial_symbols)
6117     {
6118       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6119         return 1;
6120       return 0;
6121     }
6122
6123   /* Mark the dependence relation so that we don't flush PER_CU
6124      too early.  */
6125   dwarf2_add_dependence (this_cu, per_cu);
6126
6127   /* If it's already on the queue, we have nothing to do.  */
6128   if (per_cu->queued)
6129     return 0;
6130
6131   /* If the compilation unit is already loaded, just mark it as
6132      used.  */
6133   if (per_cu->cu != NULL)
6134     {
6135       per_cu->cu->last_used = 0;
6136       return 0;
6137     }
6138
6139   /* Add it to the queue.  */
6140   queue_comp_unit (per_cu, pretend_language);
6141
6142   return 1;
6143 }
6144
6145 /* Process the queue.  */
6146
6147 static void
6148 process_queue (void)
6149 {
6150   struct dwarf2_queue_item *item, *next_item;
6151
6152   if (dwarf2_read_debug)
6153     {
6154       fprintf_unfiltered (gdb_stdlog,
6155                           "Expanding one or more symtabs of objfile %s ...\n",
6156                           dwarf2_per_objfile->objfile->name);
6157     }
6158
6159   /* The queue starts out with one item, but following a DIE reference
6160      may load a new CU, adding it to the end of the queue.  */
6161   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6162     {
6163       if (dwarf2_per_objfile->using_index
6164           ? !item->per_cu->v.quick->symtab
6165           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6166         {
6167           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6168
6169           if (dwarf2_read_debug)
6170             {
6171               fprintf_unfiltered (gdb_stdlog,
6172                                   "Expanding symtab of %s at offset 0x%x\n",
6173                                   per_cu->is_debug_types ? "TU" : "CU",
6174                                   per_cu->offset.sect_off);
6175             }
6176
6177           if (per_cu->is_debug_types)
6178             process_full_type_unit (per_cu, item->pretend_language);
6179           else
6180             process_full_comp_unit (per_cu, item->pretend_language);
6181
6182           if (dwarf2_read_debug)
6183             {
6184               fprintf_unfiltered (gdb_stdlog,
6185                                   "Done expanding %s at offset 0x%x\n",
6186                                   per_cu->is_debug_types ? "TU" : "CU",
6187                                   per_cu->offset.sect_off);
6188             }
6189         }
6190
6191       item->per_cu->queued = 0;
6192       next_item = item->next;
6193       xfree (item);
6194     }
6195
6196   dwarf2_queue_tail = NULL;
6197
6198   if (dwarf2_read_debug)
6199     {
6200       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6201                           dwarf2_per_objfile->objfile->name);
6202     }
6203 }
6204
6205 /* Free all allocated queue entries.  This function only releases anything if
6206    an error was thrown; if the queue was processed then it would have been
6207    freed as we went along.  */
6208
6209 static void
6210 dwarf2_release_queue (void *dummy)
6211 {
6212   struct dwarf2_queue_item *item, *last;
6213
6214   item = dwarf2_queue;
6215   while (item)
6216     {
6217       /* Anything still marked queued is likely to be in an
6218          inconsistent state, so discard it.  */
6219       if (item->per_cu->queued)
6220         {
6221           if (item->per_cu->cu != NULL)
6222             free_one_cached_comp_unit (item->per_cu);
6223           item->per_cu->queued = 0;
6224         }
6225
6226       last = item;
6227       item = item->next;
6228       xfree (last);
6229     }
6230
6231   dwarf2_queue = dwarf2_queue_tail = NULL;
6232 }
6233
6234 /* Read in full symbols for PST, and anything it depends on.  */
6235
6236 static void
6237 psymtab_to_symtab_1 (struct partial_symtab *pst)
6238 {
6239   struct dwarf2_per_cu_data *per_cu;
6240   int i;
6241
6242   if (pst->readin)
6243     return;
6244
6245   for (i = 0; i < pst->number_of_dependencies; i++)
6246     if (!pst->dependencies[i]->readin
6247         && pst->dependencies[i]->user == NULL)
6248       {
6249         /* Inform about additional files that need to be read in.  */
6250         if (info_verbose)
6251           {
6252             /* FIXME: i18n: Need to make this a single string.  */
6253             fputs_filtered (" ", gdb_stdout);
6254             wrap_here ("");
6255             fputs_filtered ("and ", gdb_stdout);
6256             wrap_here ("");
6257             printf_filtered ("%s...", pst->dependencies[i]->filename);
6258             wrap_here ("");     /* Flush output.  */
6259             gdb_flush (gdb_stdout);
6260           }
6261         psymtab_to_symtab_1 (pst->dependencies[i]);
6262       }
6263
6264   per_cu = pst->read_symtab_private;
6265
6266   if (per_cu == NULL)
6267     {
6268       /* It's an include file, no symbols to read for it.
6269          Everything is in the parent symtab.  */
6270       pst->readin = 1;
6271       return;
6272     }
6273
6274   dw2_do_instantiate_symtab (per_cu);
6275 }
6276
6277 /* Trivial hash function for die_info: the hash value of a DIE
6278    is its offset in .debug_info for this objfile.  */
6279
6280 static hashval_t
6281 die_hash (const void *item)
6282 {
6283   const struct die_info *die = item;
6284
6285   return die->offset.sect_off;
6286 }
6287
6288 /* Trivial comparison function for die_info structures: two DIEs
6289    are equal if they have the same offset.  */
6290
6291 static int
6292 die_eq (const void *item_lhs, const void *item_rhs)
6293 {
6294   const struct die_info *die_lhs = item_lhs;
6295   const struct die_info *die_rhs = item_rhs;
6296
6297   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6298 }
6299
6300 /* die_reader_func for load_full_comp_unit.
6301    This is identical to read_signatured_type_reader,
6302    but is kept separate for now.  */
6303
6304 static void
6305 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6306                             gdb_byte *info_ptr,
6307                             struct die_info *comp_unit_die,
6308                             int has_children,
6309                             void *data)
6310 {
6311   struct dwarf2_cu *cu = reader->cu;
6312   enum language *language_ptr = data;
6313
6314   gdb_assert (cu->die_hash == NULL);
6315   cu->die_hash =
6316     htab_create_alloc_ex (cu->header.length / 12,
6317                           die_hash,
6318                           die_eq,
6319                           NULL,
6320                           &cu->comp_unit_obstack,
6321                           hashtab_obstack_allocate,
6322                           dummy_obstack_deallocate);
6323
6324   if (has_children)
6325     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6326                                                   &info_ptr, comp_unit_die);
6327   cu->dies = comp_unit_die;
6328   /* comp_unit_die is not stored in die_hash, no need.  */
6329
6330   /* We try not to read any attributes in this function, because not
6331      all CUs needed for references have been loaded yet, and symbol
6332      table processing isn't initialized.  But we have to set the CU language,
6333      or we won't be able to build types correctly.
6334      Similarly, if we do not read the producer, we can not apply
6335      producer-specific interpretation.  */
6336   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6337 }
6338
6339 /* Load the DIEs associated with PER_CU into memory.  */
6340
6341 static void
6342 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6343                      enum language pretend_language)
6344 {
6345   gdb_assert (! this_cu->is_debug_types);
6346
6347   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6348                            load_full_comp_unit_reader, &pretend_language);
6349 }
6350
6351 /* Add a DIE to the delayed physname list.  */
6352
6353 static void
6354 add_to_method_list (struct type *type, int fnfield_index, int index,
6355                     const char *name, struct die_info *die,
6356                     struct dwarf2_cu *cu)
6357 {
6358   struct delayed_method_info mi;
6359   mi.type = type;
6360   mi.fnfield_index = fnfield_index;
6361   mi.index = index;
6362   mi.name = name;
6363   mi.die = die;
6364   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6365 }
6366
6367 /* A cleanup for freeing the delayed method list.  */
6368
6369 static void
6370 free_delayed_list (void *ptr)
6371 {
6372   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6373   if (cu->method_list != NULL)
6374     {
6375       VEC_free (delayed_method_info, cu->method_list);
6376       cu->method_list = NULL;
6377     }
6378 }
6379
6380 /* Compute the physnames of any methods on the CU's method list.
6381
6382    The computation of method physnames is delayed in order to avoid the
6383    (bad) condition that one of the method's formal parameters is of an as yet
6384    incomplete type.  */
6385
6386 static void
6387 compute_delayed_physnames (struct dwarf2_cu *cu)
6388 {
6389   int i;
6390   struct delayed_method_info *mi;
6391   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6392     {
6393       const char *physname;
6394       struct fn_fieldlist *fn_flp
6395         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6396       physname = dwarf2_physname ((char *) mi->name, mi->die, cu);
6397       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6398     }
6399 }
6400
6401 /* Go objects should be embedded in a DW_TAG_module DIE,
6402    and it's not clear if/how imported objects will appear.
6403    To keep Go support simple until that's worked out,
6404    go back through what we've read and create something usable.
6405    We could do this while processing each DIE, and feels kinda cleaner,
6406    but that way is more invasive.
6407    This is to, for example, allow the user to type "p var" or "b main"
6408    without having to specify the package name, and allow lookups
6409    of module.object to work in contexts that use the expression
6410    parser.  */
6411
6412 static void
6413 fixup_go_packaging (struct dwarf2_cu *cu)
6414 {
6415   char *package_name = NULL;
6416   struct pending *list;
6417   int i;
6418
6419   for (list = global_symbols; list != NULL; list = list->next)
6420     {
6421       for (i = 0; i < list->nsyms; ++i)
6422         {
6423           struct symbol *sym = list->symbol[i];
6424
6425           if (SYMBOL_LANGUAGE (sym) == language_go
6426               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6427             {
6428               char *this_package_name = go_symbol_package_name (sym);
6429
6430               if (this_package_name == NULL)
6431                 continue;
6432               if (package_name == NULL)
6433                 package_name = this_package_name;
6434               else
6435                 {
6436                   if (strcmp (package_name, this_package_name) != 0)
6437                     complaint (&symfile_complaints,
6438                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6439                                (sym->symtab && sym->symtab->filename
6440                                 ? sym->symtab->filename
6441                                 : cu->objfile->name),
6442                                this_package_name, package_name);
6443                   xfree (this_package_name);
6444                 }
6445             }
6446         }
6447     }
6448
6449   if (package_name != NULL)
6450     {
6451       struct objfile *objfile = cu->objfile;
6452       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6453                                      package_name, objfile);
6454       struct symbol *sym;
6455
6456       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6457
6458       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6459       SYMBOL_SET_LANGUAGE (sym, language_go);
6460       SYMBOL_SET_NAMES (sym, package_name, strlen (package_name), 1, objfile);
6461       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6462          e.g., "main" finds the "main" module and not C's main().  */
6463       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6464       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
6465       SYMBOL_TYPE (sym) = type;
6466
6467       add_symbol_to_list (sym, &global_symbols);
6468
6469       xfree (package_name);
6470     }
6471 }
6472
6473 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
6474
6475 /* Return the symtab for PER_CU.  This works properly regardless of
6476    whether we're using the index or psymtabs.  */
6477
6478 static struct symtab *
6479 get_symtab (struct dwarf2_per_cu_data *per_cu)
6480 {
6481   return (dwarf2_per_objfile->using_index
6482           ? per_cu->v.quick->symtab
6483           : per_cu->v.psymtab->symtab);
6484 }
6485
6486 /* A helper function for computing the list of all symbol tables
6487    included by PER_CU.  */
6488
6489 static void
6490 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6491                                 htab_t all_children,
6492                                 struct dwarf2_per_cu_data *per_cu)
6493 {
6494   void **slot;
6495   int ix;
6496   struct dwarf2_per_cu_data *iter;
6497
6498   slot = htab_find_slot (all_children, per_cu, INSERT);
6499   if (*slot != NULL)
6500     {
6501       /* This inclusion and its children have been processed.  */
6502       return;
6503     }
6504
6505   *slot = per_cu;
6506   /* Only add a CU if it has a symbol table.  */
6507   if (get_symtab (per_cu) != NULL)
6508     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6509
6510   for (ix = 0;
6511        VEC_iterate (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs, ix, iter);
6512        ++ix)
6513     recursively_compute_inclusions (result, all_children, iter);
6514 }
6515
6516 /* Compute the symtab 'includes' fields for the symtab related to
6517    PER_CU.  */
6518
6519 static void
6520 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6521 {
6522   gdb_assert (! per_cu->is_debug_types);
6523
6524   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs))
6525     {
6526       int ix, len;
6527       struct dwarf2_per_cu_data *iter;
6528       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6529       htab_t all_children;
6530       struct symtab *symtab = get_symtab (per_cu);
6531
6532       /* If we don't have a symtab, we can just skip this case.  */
6533       if (symtab == NULL)
6534         return;
6535
6536       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6537                                         NULL, xcalloc, xfree);
6538
6539       for (ix = 0;
6540            VEC_iterate (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs,
6541                         ix, iter);
6542            ++ix)
6543         recursively_compute_inclusions (&result_children, all_children, iter);
6544
6545       /* Now we have a transitive closure of all the included CUs, so
6546          we can convert it to a list of symtabs.  */
6547       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6548       symtab->includes
6549         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6550                          (len + 1) * sizeof (struct symtab *));
6551       for (ix = 0;
6552            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6553            ++ix)
6554         symtab->includes[ix] = get_symtab (iter);
6555       symtab->includes[len] = NULL;
6556
6557       VEC_free (dwarf2_per_cu_ptr, result_children);
6558       htab_delete (all_children);
6559     }
6560 }
6561
6562 /* Compute the 'includes' field for the symtabs of all the CUs we just
6563    read.  */
6564
6565 static void
6566 process_cu_includes (void)
6567 {
6568   int ix;
6569   struct dwarf2_per_cu_data *iter;
6570
6571   for (ix = 0;
6572        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6573                     ix, iter);
6574        ++ix)
6575     {
6576       if (! iter->is_debug_types)
6577         compute_symtab_includes (iter);
6578     }
6579
6580   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6581 }
6582
6583 /* Generate full symbol information for PER_CU, whose DIEs have
6584    already been loaded into memory.  */
6585
6586 static void
6587 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6588                         enum language pretend_language)
6589 {
6590   struct dwarf2_cu *cu = per_cu->cu;
6591   struct objfile *objfile = per_cu->objfile;
6592   CORE_ADDR lowpc, highpc;
6593   struct symtab *symtab;
6594   struct cleanup *back_to, *delayed_list_cleanup;
6595   CORE_ADDR baseaddr;
6596
6597   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6598
6599   buildsym_init ();
6600   back_to = make_cleanup (really_free_pendings, NULL);
6601   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6602
6603   cu->list_in_scope = &file_symbols;
6604
6605   cu->language = pretend_language;
6606   cu->language_defn = language_def (cu->language);
6607
6608   /* Do line number decoding in read_file_scope () */
6609   process_die (cu->dies, cu);
6610
6611   /* For now fudge the Go package.  */
6612   if (cu->language == language_go)
6613     fixup_go_packaging (cu);
6614
6615   /* Now that we have processed all the DIEs in the CU, all the types 
6616      should be complete, and it should now be safe to compute all of the
6617      physnames.  */
6618   compute_delayed_physnames (cu);
6619   do_cleanups (delayed_list_cleanup);
6620
6621   /* Some compilers don't define a DW_AT_high_pc attribute for the
6622      compilation unit.  If the DW_AT_high_pc is missing, synthesize
6623      it, by scanning the DIE's below the compilation unit.  */
6624   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
6625
6626   symtab = end_symtab (highpc + baseaddr, objfile, SECT_OFF_TEXT (objfile));
6627
6628   if (symtab != NULL)
6629     {
6630       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
6631
6632       /* Set symtab language to language from DW_AT_language.  If the
6633          compilation is from a C file generated by language preprocessors, do
6634          not set the language if it was already deduced by start_subfile.  */
6635       if (!(cu->language == language_c && symtab->language != language_c))
6636         symtab->language = cu->language;
6637
6638       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
6639          produce DW_AT_location with location lists but it can be possibly
6640          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
6641          there were bugs in prologue debug info, fixed later in GCC-4.5
6642          by "unwind info for epilogues" patch (which is not directly related).
6643
6644          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
6645          needed, it would be wrong due to missing DW_AT_producer there.
6646
6647          Still one can confuse GDB by using non-standard GCC compilation
6648          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
6649          */ 
6650       if (cu->has_loclist && gcc_4_minor >= 5)
6651         symtab->locations_valid = 1;
6652
6653       if (gcc_4_minor >= 5)
6654         symtab->epilogue_unwind_valid = 1;
6655
6656       symtab->call_site_htab = cu->call_site_htab;
6657     }
6658
6659   if (dwarf2_per_objfile->using_index)
6660     per_cu->v.quick->symtab = symtab;
6661   else
6662     {
6663       struct partial_symtab *pst = per_cu->v.psymtab;
6664       pst->symtab = symtab;
6665       pst->readin = 1;
6666     }
6667
6668   /* Push it for inclusion processing later.  */
6669   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
6670
6671   do_cleanups (back_to);
6672 }
6673
6674 /* Generate full symbol information for type unit PER_CU, whose DIEs have
6675    already been loaded into memory.  */
6676
6677 static void
6678 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
6679                         enum language pretend_language)
6680 {
6681   struct dwarf2_cu *cu = per_cu->cu;
6682   struct objfile *objfile = per_cu->objfile;
6683   struct symtab *symtab;
6684   struct cleanup *back_to, *delayed_list_cleanup;
6685
6686   buildsym_init ();
6687   back_to = make_cleanup (really_free_pendings, NULL);
6688   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6689
6690   cu->list_in_scope = &file_symbols;
6691
6692   cu->language = pretend_language;
6693   cu->language_defn = language_def (cu->language);
6694
6695   /* The symbol tables are set up in read_type_unit_scope.  */
6696   process_die (cu->dies, cu);
6697
6698   /* For now fudge the Go package.  */
6699   if (cu->language == language_go)
6700     fixup_go_packaging (cu);
6701
6702   /* Now that we have processed all the DIEs in the CU, all the types 
6703      should be complete, and it should now be safe to compute all of the
6704      physnames.  */
6705   compute_delayed_physnames (cu);
6706   do_cleanups (delayed_list_cleanup);
6707
6708   /* TUs share symbol tables.
6709      If this is the first TU to use this symtab, complete the construction
6710      of it with end_symtab.  Otherwise, complete the addition of this TU's
6711      symbols to the existing symtab.  */
6712   if (per_cu->s.type_unit_group->primary_symtab == NULL)
6713     {
6714       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
6715       per_cu->s.type_unit_group->primary_symtab = symtab;
6716
6717       if (symtab != NULL)
6718         {
6719           /* Set symtab language to language from DW_AT_language.  If the
6720              compilation is from a C file generated by language preprocessors,
6721              do not set the language if it was already deduced by
6722              start_subfile.  */
6723           if (!(cu->language == language_c && symtab->language != language_c))
6724             symtab->language = cu->language;
6725         }
6726     }
6727   else
6728     {
6729       augment_type_symtab (objfile,
6730                            per_cu->s.type_unit_group->primary_symtab);
6731       symtab = per_cu->s.type_unit_group->primary_symtab;
6732     }
6733
6734   if (dwarf2_per_objfile->using_index)
6735     per_cu->v.quick->symtab = symtab;
6736   else
6737     {
6738       struct partial_symtab *pst = per_cu->v.psymtab;
6739       pst->symtab = symtab;
6740       pst->readin = 1;
6741     }
6742
6743   do_cleanups (back_to);
6744 }
6745
6746 /* Process an imported unit DIE.  */
6747
6748 static void
6749 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
6750 {
6751   struct attribute *attr;
6752
6753   /* For now we don't handle imported units in type units.  */
6754   if (cu->per_cu->is_debug_types)
6755     {
6756       error (_("Dwarf Error: DW_TAG_imported_unit is not"
6757                " supported in type units [in module %s]"),
6758              cu->objfile->name);
6759     }
6760
6761   attr = dwarf2_attr (die, DW_AT_import, cu);
6762   if (attr != NULL)
6763     {
6764       struct dwarf2_per_cu_data *per_cu;
6765       struct symtab *imported_symtab;
6766       sect_offset offset;
6767
6768       offset = dwarf2_get_ref_die_offset (attr);
6769       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
6770
6771       /* Queue the unit, if needed.  */
6772       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
6773         load_full_comp_unit (per_cu, cu->language);
6774
6775       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs,
6776                      per_cu);
6777     }
6778 }
6779
6780 /* Process a die and its children.  */
6781
6782 static void
6783 process_die (struct die_info *die, struct dwarf2_cu *cu)
6784 {
6785   switch (die->tag)
6786     {
6787     case DW_TAG_padding:
6788       break;
6789     case DW_TAG_compile_unit:
6790     case DW_TAG_partial_unit:
6791       read_file_scope (die, cu);
6792       break;
6793     case DW_TAG_type_unit:
6794       read_type_unit_scope (die, cu);
6795       break;
6796     case DW_TAG_subprogram:
6797     case DW_TAG_inlined_subroutine:
6798       read_func_scope (die, cu);
6799       break;
6800     case DW_TAG_lexical_block:
6801     case DW_TAG_try_block:
6802     case DW_TAG_catch_block:
6803       read_lexical_block_scope (die, cu);
6804       break;
6805     case DW_TAG_GNU_call_site:
6806       read_call_site_scope (die, cu);
6807       break;
6808     case DW_TAG_class_type:
6809     case DW_TAG_interface_type:
6810     case DW_TAG_structure_type:
6811     case DW_TAG_union_type:
6812       process_structure_scope (die, cu);
6813       break;
6814     case DW_TAG_enumeration_type:
6815       process_enumeration_scope (die, cu);
6816       break;
6817
6818     /* These dies have a type, but processing them does not create
6819        a symbol or recurse to process the children.  Therefore we can
6820        read them on-demand through read_type_die.  */
6821     case DW_TAG_subroutine_type:
6822     case DW_TAG_set_type:
6823     case DW_TAG_array_type:
6824     case DW_TAG_pointer_type:
6825     case DW_TAG_ptr_to_member_type:
6826     case DW_TAG_reference_type:
6827     case DW_TAG_string_type:
6828       break;
6829
6830     case DW_TAG_base_type:
6831     case DW_TAG_subrange_type:
6832     case DW_TAG_typedef:
6833       /* Add a typedef symbol for the type definition, if it has a
6834          DW_AT_name.  */
6835       new_symbol (die, read_type_die (die, cu), cu);
6836       break;
6837     case DW_TAG_common_block:
6838       read_common_block (die, cu);
6839       break;
6840     case DW_TAG_common_inclusion:
6841       break;
6842     case DW_TAG_namespace:
6843       processing_has_namespace_info = 1;
6844       read_namespace (die, cu);
6845       break;
6846     case DW_TAG_module:
6847       processing_has_namespace_info = 1;
6848       read_module (die, cu);
6849       break;
6850     case DW_TAG_imported_declaration:
6851     case DW_TAG_imported_module:
6852       processing_has_namespace_info = 1;
6853       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
6854                                  || cu->language != language_fortran))
6855         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
6856                    dwarf_tag_name (die->tag));
6857       read_import_statement (die, cu);
6858       break;
6859
6860     case DW_TAG_imported_unit:
6861       process_imported_unit_die (die, cu);
6862       break;
6863
6864     default:
6865       new_symbol (die, NULL, cu);
6866       break;
6867     }
6868 }
6869
6870 /* A helper function for dwarf2_compute_name which determines whether DIE
6871    needs to have the name of the scope prepended to the name listed in the
6872    die.  */
6873
6874 static int
6875 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
6876 {
6877   struct attribute *attr;
6878
6879   switch (die->tag)
6880     {
6881     case DW_TAG_namespace:
6882     case DW_TAG_typedef:
6883     case DW_TAG_class_type:
6884     case DW_TAG_interface_type:
6885     case DW_TAG_structure_type:
6886     case DW_TAG_union_type:
6887     case DW_TAG_enumeration_type:
6888     case DW_TAG_enumerator:
6889     case DW_TAG_subprogram:
6890     case DW_TAG_member:
6891       return 1;
6892
6893     case DW_TAG_variable:
6894     case DW_TAG_constant:
6895       /* We only need to prefix "globally" visible variables.  These include
6896          any variable marked with DW_AT_external or any variable that
6897          lives in a namespace.  [Variables in anonymous namespaces
6898          require prefixing, but they are not DW_AT_external.]  */
6899
6900       if (dwarf2_attr (die, DW_AT_specification, cu))
6901         {
6902           struct dwarf2_cu *spec_cu = cu;
6903
6904           return die_needs_namespace (die_specification (die, &spec_cu),
6905                                       spec_cu);
6906         }
6907
6908       attr = dwarf2_attr (die, DW_AT_external, cu);
6909       if (attr == NULL && die->parent->tag != DW_TAG_namespace
6910           && die->parent->tag != DW_TAG_module)
6911         return 0;
6912       /* A variable in a lexical block of some kind does not need a
6913          namespace, even though in C++ such variables may be external
6914          and have a mangled name.  */
6915       if (die->parent->tag ==  DW_TAG_lexical_block
6916           || die->parent->tag ==  DW_TAG_try_block
6917           || die->parent->tag ==  DW_TAG_catch_block
6918           || die->parent->tag == DW_TAG_subprogram)
6919         return 0;
6920       return 1;
6921
6922     default:
6923       return 0;
6924     }
6925 }
6926
6927 /* Retrieve the last character from a mem_file.  */
6928
6929 static void
6930 do_ui_file_peek_last (void *object, const char *buffer, long length)
6931 {
6932   char *last_char_p = (char *) object;
6933
6934   if (length > 0)
6935     *last_char_p = buffer[length - 1];
6936 }
6937
6938 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
6939    compute the physname for the object, which include a method's:
6940    - formal parameters (C++/Java),
6941    - receiver type (Go),
6942    - return type (Java).
6943
6944    The term "physname" is a bit confusing.
6945    For C++, for example, it is the demangled name.
6946    For Go, for example, it's the mangled name.
6947
6948    For Ada, return the DIE's linkage name rather than the fully qualified
6949    name.  PHYSNAME is ignored..
6950
6951    The result is allocated on the objfile_obstack and canonicalized.  */
6952
6953 static const char *
6954 dwarf2_compute_name (char *name, struct die_info *die, struct dwarf2_cu *cu,
6955                      int physname)
6956 {
6957   struct objfile *objfile = cu->objfile;
6958
6959   if (name == NULL)
6960     name = dwarf2_name (die, cu);
6961
6962   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
6963      compute it by typename_concat inside GDB.  */
6964   if (cu->language == language_ada
6965       || (cu->language == language_fortran && physname))
6966     {
6967       /* For Ada unit, we prefer the linkage name over the name, as
6968          the former contains the exported name, which the user expects
6969          to be able to reference.  Ideally, we want the user to be able
6970          to reference this entity using either natural or linkage name,
6971          but we haven't started looking at this enhancement yet.  */
6972       struct attribute *attr;
6973
6974       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
6975       if (attr == NULL)
6976         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
6977       if (attr && DW_STRING (attr))
6978         return DW_STRING (attr);
6979     }
6980
6981   /* These are the only languages we know how to qualify names in.  */
6982   if (name != NULL
6983       && (cu->language == language_cplus || cu->language == language_java
6984           || cu->language == language_fortran))
6985     {
6986       if (die_needs_namespace (die, cu))
6987         {
6988           long length;
6989           const char *prefix;
6990           struct ui_file *buf;
6991
6992           prefix = determine_prefix (die, cu);
6993           buf = mem_fileopen ();
6994           if (*prefix != '\0')
6995             {
6996               char *prefixed_name = typename_concat (NULL, prefix, name,
6997                                                      physname, cu);
6998
6999               fputs_unfiltered (prefixed_name, buf);
7000               xfree (prefixed_name);
7001             }
7002           else
7003             fputs_unfiltered (name, buf);
7004
7005           /* Template parameters may be specified in the DIE's DW_AT_name, or
7006              as children with DW_TAG_template_type_param or
7007              DW_TAG_value_type_param.  If the latter, add them to the name
7008              here.  If the name already has template parameters, then
7009              skip this step; some versions of GCC emit both, and
7010              it is more efficient to use the pre-computed name.
7011
7012              Something to keep in mind about this process: it is very
7013              unlikely, or in some cases downright impossible, to produce
7014              something that will match the mangled name of a function.
7015              If the definition of the function has the same debug info,
7016              we should be able to match up with it anyway.  But fallbacks
7017              using the minimal symbol, for instance to find a method
7018              implemented in a stripped copy of libstdc++, will not work.
7019              If we do not have debug info for the definition, we will have to
7020              match them up some other way.
7021
7022              When we do name matching there is a related problem with function
7023              templates; two instantiated function templates are allowed to
7024              differ only by their return types, which we do not add here.  */
7025
7026           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7027             {
7028               struct attribute *attr;
7029               struct die_info *child;
7030               int first = 1;
7031
7032               die->building_fullname = 1;
7033
7034               for (child = die->child; child != NULL; child = child->sibling)
7035                 {
7036                   struct type *type;
7037                   LONGEST value;
7038                   gdb_byte *bytes;
7039                   struct dwarf2_locexpr_baton *baton;
7040                   struct value *v;
7041
7042                   if (child->tag != DW_TAG_template_type_param
7043                       && child->tag != DW_TAG_template_value_param)
7044                     continue;
7045
7046                   if (first)
7047                     {
7048                       fputs_unfiltered ("<", buf);
7049                       first = 0;
7050                     }
7051                   else
7052                     fputs_unfiltered (", ", buf);
7053
7054                   attr = dwarf2_attr (child, DW_AT_type, cu);
7055                   if (attr == NULL)
7056                     {
7057                       complaint (&symfile_complaints,
7058                                  _("template parameter missing DW_AT_type"));
7059                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7060                       continue;
7061                     }
7062                   type = die_type (child, cu);
7063
7064                   if (child->tag == DW_TAG_template_type_param)
7065                     {
7066                       c_print_type (type, "", buf, -1, 0);
7067                       continue;
7068                     }
7069
7070                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7071                   if (attr == NULL)
7072                     {
7073                       complaint (&symfile_complaints,
7074                                  _("template parameter missing "
7075                                    "DW_AT_const_value"));
7076                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7077                       continue;
7078                     }
7079
7080                   dwarf2_const_value_attr (attr, type, name,
7081                                            &cu->comp_unit_obstack, cu,
7082                                            &value, &bytes, &baton);
7083
7084                   if (TYPE_NOSIGN (type))
7085                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7086                        changed, this can use value_print instead.  */
7087                     c_printchar (value, type, buf);
7088                   else
7089                     {
7090                       struct value_print_options opts;
7091
7092                       if (baton != NULL)
7093                         v = dwarf2_evaluate_loc_desc (type, NULL,
7094                                                       baton->data,
7095                                                       baton->size,
7096                                                       baton->per_cu);
7097                       else if (bytes != NULL)
7098                         {
7099                           v = allocate_value (type);
7100                           memcpy (value_contents_writeable (v), bytes,
7101                                   TYPE_LENGTH (type));
7102                         }
7103                       else
7104                         v = value_from_longest (type, value);
7105
7106                       /* Specify decimal so that we do not depend on
7107                          the radix.  */
7108                       get_formatted_print_options (&opts, 'd');
7109                       opts.raw = 1;
7110                       value_print (v, buf, &opts);
7111                       release_value (v);
7112                       value_free (v);
7113                     }
7114                 }
7115
7116               die->building_fullname = 0;
7117
7118               if (!first)
7119                 {
7120                   /* Close the argument list, with a space if necessary
7121                      (nested templates).  */
7122                   char last_char = '\0';
7123                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7124                   if (last_char == '>')
7125                     fputs_unfiltered (" >", buf);
7126                   else
7127                     fputs_unfiltered (">", buf);
7128                 }
7129             }
7130
7131           /* For Java and C++ methods, append formal parameter type
7132              information, if PHYSNAME.  */
7133
7134           if (physname && die->tag == DW_TAG_subprogram
7135               && (cu->language == language_cplus
7136                   || cu->language == language_java))
7137             {
7138               struct type *type = read_type_die (die, cu);
7139
7140               c_type_print_args (type, buf, 1, cu->language);
7141
7142               if (cu->language == language_java)
7143                 {
7144                   /* For java, we must append the return type to method
7145                      names.  */
7146                   if (die->tag == DW_TAG_subprogram)
7147                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7148                                      0, 0);
7149                 }
7150               else if (cu->language == language_cplus)
7151                 {
7152                   /* Assume that an artificial first parameter is
7153                      "this", but do not crash if it is not.  RealView
7154                      marks unnamed (and thus unused) parameters as
7155                      artificial; there is no way to differentiate
7156                      the two cases.  */
7157                   if (TYPE_NFIELDS (type) > 0
7158                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7159                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7160                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7161                                                                         0))))
7162                     fputs_unfiltered (" const", buf);
7163                 }
7164             }
7165
7166           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7167                                        &length);
7168           ui_file_delete (buf);
7169
7170           if (cu->language == language_cplus)
7171             {
7172               char *cname
7173                 = dwarf2_canonicalize_name (name, cu,
7174                                             &objfile->objfile_obstack);
7175
7176               if (cname != NULL)
7177                 name = cname;
7178             }
7179         }
7180     }
7181
7182   return name;
7183 }
7184
7185 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7186    If scope qualifiers are appropriate they will be added.  The result
7187    will be allocated on the objfile_obstack, or NULL if the DIE does
7188    not have a name.  NAME may either be from a previous call to
7189    dwarf2_name or NULL.
7190
7191    The output string will be canonicalized (if C++/Java).  */
7192
7193 static const char *
7194 dwarf2_full_name (char *name, struct die_info *die, struct dwarf2_cu *cu)
7195 {
7196   return dwarf2_compute_name (name, die, cu, 0);
7197 }
7198
7199 /* Construct a physname for the given DIE in CU.  NAME may either be
7200    from a previous call to dwarf2_name or NULL.  The result will be
7201    allocated on the objfile_objstack or NULL if the DIE does not have a
7202    name.
7203
7204    The output string will be canonicalized (if C++/Java).  */
7205
7206 static const char *
7207 dwarf2_physname (char *name, struct die_info *die, struct dwarf2_cu *cu)
7208 {
7209   struct objfile *objfile = cu->objfile;
7210   struct attribute *attr;
7211   const char *retval, *mangled = NULL, *canon = NULL;
7212   struct cleanup *back_to;
7213   int need_copy = 1;
7214
7215   /* In this case dwarf2_compute_name is just a shortcut not building anything
7216      on its own.  */
7217   if (!die_needs_namespace (die, cu))
7218     return dwarf2_compute_name (name, die, cu, 1);
7219
7220   back_to = make_cleanup (null_cleanup, NULL);
7221
7222   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7223   if (!attr)
7224     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7225
7226   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7227      has computed.  */
7228   if (attr && DW_STRING (attr))
7229     {
7230       char *demangled;
7231
7232       mangled = DW_STRING (attr);
7233
7234       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7235          type.  It is easier for GDB users to search for such functions as
7236          `name(params)' than `long name(params)'.  In such case the minimal
7237          symbol names do not match the full symbol names but for template
7238          functions there is never a need to look up their definition from their
7239          declaration so the only disadvantage remains the minimal symbol
7240          variant `long name(params)' does not have the proper inferior type.
7241          */
7242
7243       if (cu->language == language_go)
7244         {
7245           /* This is a lie, but we already lie to the caller new_symbol_full.
7246              new_symbol_full assumes we return the mangled name.
7247              This just undoes that lie until things are cleaned up.  */
7248           demangled = NULL;
7249         }
7250       else
7251         {
7252           demangled = cplus_demangle (mangled,
7253                                       (DMGL_PARAMS | DMGL_ANSI
7254                                        | (cu->language == language_java
7255                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7256                                           : DMGL_RET_DROP)));
7257         }
7258       if (demangled)
7259         {
7260           make_cleanup (xfree, demangled);
7261           canon = demangled;
7262         }
7263       else
7264         {
7265           canon = mangled;
7266           need_copy = 0;
7267         }
7268     }
7269
7270   if (canon == NULL || check_physname)
7271     {
7272       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7273
7274       if (canon != NULL && strcmp (physname, canon) != 0)
7275         {
7276           /* It may not mean a bug in GDB.  The compiler could also
7277              compute DW_AT_linkage_name incorrectly.  But in such case
7278              GDB would need to be bug-to-bug compatible.  */
7279
7280           complaint (&symfile_complaints,
7281                      _("Computed physname <%s> does not match demangled <%s> "
7282                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7283                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7284
7285           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7286              is available here - over computed PHYSNAME.  It is safer
7287              against both buggy GDB and buggy compilers.  */
7288
7289           retval = canon;
7290         }
7291       else
7292         {
7293           retval = physname;
7294           need_copy = 0;
7295         }
7296     }
7297   else
7298     retval = canon;
7299
7300   if (need_copy)
7301     retval = obsavestring (retval, strlen (retval),
7302                            &objfile->objfile_obstack);
7303
7304   do_cleanups (back_to);
7305   return retval;
7306 }
7307
7308 /* Read the import statement specified by the given die and record it.  */
7309
7310 static void
7311 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7312 {
7313   struct objfile *objfile = cu->objfile;
7314   struct attribute *import_attr;
7315   struct die_info *imported_die, *child_die;
7316   struct dwarf2_cu *imported_cu;
7317   const char *imported_name;
7318   const char *imported_name_prefix;
7319   const char *canonical_name;
7320   const char *import_alias;
7321   const char *imported_declaration = NULL;
7322   const char *import_prefix;
7323   VEC (const_char_ptr) *excludes = NULL;
7324   struct cleanup *cleanups;
7325
7326   char *temp;
7327
7328   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7329   if (import_attr == NULL)
7330     {
7331       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7332                  dwarf_tag_name (die->tag));
7333       return;
7334     }
7335
7336   imported_cu = cu;
7337   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7338   imported_name = dwarf2_name (imported_die, imported_cu);
7339   if (imported_name == NULL)
7340     {
7341       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7342
7343         The import in the following code:
7344         namespace A
7345           {
7346             typedef int B;
7347           }
7348
7349         int main ()
7350           {
7351             using A::B;
7352             B b;
7353             return b;
7354           }
7355
7356         ...
7357          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7358             <52>   DW_AT_decl_file   : 1
7359             <53>   DW_AT_decl_line   : 6
7360             <54>   DW_AT_import      : <0x75>
7361          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7362             <59>   DW_AT_name        : B
7363             <5b>   DW_AT_decl_file   : 1
7364             <5c>   DW_AT_decl_line   : 2
7365             <5d>   DW_AT_type        : <0x6e>
7366         ...
7367          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7368             <76>   DW_AT_byte_size   : 4
7369             <77>   DW_AT_encoding    : 5        (signed)
7370
7371         imports the wrong die ( 0x75 instead of 0x58 ).
7372         This case will be ignored until the gcc bug is fixed.  */
7373       return;
7374     }
7375
7376   /* Figure out the local name after import.  */
7377   import_alias = dwarf2_name (die, cu);
7378
7379   /* Figure out where the statement is being imported to.  */
7380   import_prefix = determine_prefix (die, cu);
7381
7382   /* Figure out what the scope of the imported die is and prepend it
7383      to the name of the imported die.  */
7384   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7385
7386   if (imported_die->tag != DW_TAG_namespace
7387       && imported_die->tag != DW_TAG_module)
7388     {
7389       imported_declaration = imported_name;
7390       canonical_name = imported_name_prefix;
7391     }
7392   else if (strlen (imported_name_prefix) > 0)
7393     {
7394       temp = alloca (strlen (imported_name_prefix)
7395                      + 2 + strlen (imported_name) + 1);
7396       strcpy (temp, imported_name_prefix);
7397       strcat (temp, "::");
7398       strcat (temp, imported_name);
7399       canonical_name = temp;
7400     }
7401   else
7402     canonical_name = imported_name;
7403
7404   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7405
7406   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7407     for (child_die = die->child; child_die && child_die->tag;
7408          child_die = sibling_die (child_die))
7409       {
7410         /* DWARF-4: A Fortran use statement with a “rename list” may be
7411            represented by an imported module entry with an import attribute
7412            referring to the module and owned entries corresponding to those
7413            entities that are renamed as part of being imported.  */
7414
7415         if (child_die->tag != DW_TAG_imported_declaration)
7416           {
7417             complaint (&symfile_complaints,
7418                        _("child DW_TAG_imported_declaration expected "
7419                          "- DIE at 0x%x [in module %s]"),
7420                        child_die->offset.sect_off, objfile->name);
7421             continue;
7422           }
7423
7424         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7425         if (import_attr == NULL)
7426           {
7427             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7428                        dwarf_tag_name (child_die->tag));
7429             continue;
7430           }
7431
7432         imported_cu = cu;
7433         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7434                                               &imported_cu);
7435         imported_name = dwarf2_name (imported_die, imported_cu);
7436         if (imported_name == NULL)
7437           {
7438             complaint (&symfile_complaints,
7439                        _("child DW_TAG_imported_declaration has unknown "
7440                          "imported name - DIE at 0x%x [in module %s]"),
7441                        child_die->offset.sect_off, objfile->name);
7442             continue;
7443           }
7444
7445         VEC_safe_push (const_char_ptr, excludes, imported_name);
7446
7447         process_die (child_die, cu);
7448       }
7449
7450   cp_add_using_directive (import_prefix,
7451                           canonical_name,
7452                           import_alias,
7453                           imported_declaration,
7454                           excludes,
7455                           &objfile->objfile_obstack);
7456
7457   do_cleanups (cleanups);
7458 }
7459
7460 /* Cleanup function for handle_DW_AT_stmt_list.  */
7461
7462 static void
7463 free_cu_line_header (void *arg)
7464 {
7465   struct dwarf2_cu *cu = arg;
7466
7467   free_line_header (cu->line_header);
7468   cu->line_header = NULL;
7469 }
7470
7471 static void
7472 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7473                          char **name, char **comp_dir)
7474 {
7475   struct attribute *attr;
7476
7477   *name = NULL;
7478   *comp_dir = NULL;
7479
7480   /* Find the filename.  Do not use dwarf2_name here, since the filename
7481      is not a source language identifier.  */
7482   attr = dwarf2_attr (die, DW_AT_name, cu);
7483   if (attr)
7484     {
7485       *name = DW_STRING (attr);
7486     }
7487
7488   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7489   if (attr)
7490     *comp_dir = DW_STRING (attr);
7491   else if (*name != NULL && IS_ABSOLUTE_PATH (*name))
7492     {
7493       *comp_dir = ldirname (*name);
7494       if (*comp_dir != NULL)
7495         make_cleanup (xfree, *comp_dir);
7496     }
7497   if (*comp_dir != NULL)
7498     {
7499       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7500          directory, get rid of it.  */
7501       char *cp = strchr (*comp_dir, ':');
7502
7503       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7504         *comp_dir = cp + 1;
7505     }
7506
7507   if (*name == NULL)
7508     *name = "<unknown>";
7509 }
7510
7511 /* Handle DW_AT_stmt_list for a compilation unit.
7512    DIE is the DW_TAG_compile_unit die for CU.
7513    COMP_DIR is the compilation directory.
7514    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7515
7516 static void
7517 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7518                         const char *comp_dir)
7519 {
7520   struct attribute *attr;
7521
7522   gdb_assert (! cu->per_cu->is_debug_types);
7523
7524   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7525   if (attr)
7526     {
7527       unsigned int line_offset = DW_UNSND (attr);
7528       struct line_header *line_header
7529         = dwarf_decode_line_header (line_offset, cu);
7530
7531       if (line_header)
7532         {
7533           cu->line_header = line_header;
7534           make_cleanup (free_cu_line_header, cu);
7535           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7536         }
7537     }
7538 }
7539
7540 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7541
7542 static void
7543 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7544 {
7545   struct objfile *objfile = dwarf2_per_objfile->objfile;
7546   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7547   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7548   CORE_ADDR highpc = ((CORE_ADDR) 0);
7549   struct attribute *attr;
7550   char *name = NULL;
7551   char *comp_dir = NULL;
7552   struct die_info *child_die;
7553   bfd *abfd = objfile->obfd;
7554   CORE_ADDR baseaddr;
7555
7556   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7557
7558   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7559
7560   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7561      from finish_block.  */
7562   if (lowpc == ((CORE_ADDR) -1))
7563     lowpc = highpc;
7564   lowpc += baseaddr;
7565   highpc += baseaddr;
7566
7567   find_file_and_directory (die, cu, &name, &comp_dir);
7568
7569   prepare_one_comp_unit (cu, die, cu->language);
7570
7571   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7572      standardised yet.  As a workaround for the language detection we fall
7573      back to the DW_AT_producer string.  */
7574   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7575     cu->language = language_opencl;
7576
7577   /* Similar hack for Go.  */
7578   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
7579     set_cu_language (DW_LANG_Go, cu);
7580
7581   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
7582
7583   /* Decode line number information if present.  We do this before
7584      processing child DIEs, so that the line header table is available
7585      for DW_AT_decl_file.  */
7586   handle_DW_AT_stmt_list (die, cu, comp_dir);
7587
7588   /* Process all dies in compilation unit.  */
7589   if (die->child != NULL)
7590     {
7591       child_die = die->child;
7592       while (child_die && child_die->tag)
7593         {
7594           process_die (child_die, cu);
7595           child_die = sibling_die (child_die);
7596         }
7597     }
7598
7599   /* Decode macro information, if present.  Dwarf 2 macro information
7600      refers to information in the line number info statement program
7601      header, so we can only read it if we've read the header
7602      successfully.  */
7603   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
7604   if (attr && cu->line_header)
7605     {
7606       if (dwarf2_attr (die, DW_AT_macro_info, cu))
7607         complaint (&symfile_complaints,
7608                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
7609
7610       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
7611     }
7612   else
7613     {
7614       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
7615       if (attr && cu->line_header)
7616         {
7617           unsigned int macro_offset = DW_UNSND (attr);
7618
7619           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
7620         }
7621     }
7622
7623   do_cleanups (back_to);
7624 }
7625
7626 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
7627    Create the set of symtabs used by this TU, or if this TU is sharing
7628    symtabs with another TU and the symtabs have already been created
7629    then restore those symtabs in the line header.
7630    We don't need the pc/line-number mapping for type units.  */
7631
7632 static void
7633 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
7634 {
7635   struct objfile *objfile = dwarf2_per_objfile->objfile;
7636   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7637   struct type_unit_group *tu_group;
7638   int first_time;
7639   struct line_header *lh;
7640   struct attribute *attr;
7641   unsigned int i, line_offset;
7642
7643   gdb_assert (per_cu->is_debug_types);
7644
7645   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7646
7647   /* If we're using .gdb_index (includes -readnow) then
7648      per_cu->s.type_unit_group may not have been set up yet.  */
7649   if (per_cu->s.type_unit_group == NULL)
7650     per_cu->s.type_unit_group = get_type_unit_group (per_cu, attr);
7651   tu_group = per_cu->s.type_unit_group;
7652
7653   /* If we've already processed this stmt_list there's no real need to
7654      do it again, we could fake it and just recreate the part we need
7655      (file name,index -> symtab mapping).  If data shows this optimization
7656      is useful we can do it then.  */
7657   first_time = tu_group->primary_symtab == NULL;
7658
7659   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
7660      debug info.  */
7661   lh = NULL;
7662   if (attr != NULL)
7663     {
7664       line_offset = DW_UNSND (attr);
7665       lh = dwarf_decode_line_header (line_offset, cu);
7666     }
7667   if (lh == NULL)
7668     {
7669       if (first_time)
7670         dwarf2_start_symtab (cu, "", NULL, 0);
7671       else
7672         {
7673           gdb_assert (tu_group->symtabs == NULL);
7674           restart_symtab (0);
7675         }
7676       /* Note: The primary symtab will get allocated at the end.  */
7677       return;
7678     }
7679
7680   cu->line_header = lh;
7681   make_cleanup (free_cu_line_header, cu);
7682
7683   if (first_time)
7684     {
7685       dwarf2_start_symtab (cu, "", NULL, 0);
7686
7687       tu_group->num_symtabs = lh->num_file_names;
7688       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
7689
7690       for (i = 0; i < lh->num_file_names; ++i)
7691         {
7692           char *dir = NULL;
7693           struct file_entry *fe = &lh->file_names[i];
7694
7695           if (fe->dir_index)
7696             dir = lh->include_dirs[fe->dir_index - 1];
7697           dwarf2_start_subfile (fe->name, dir, NULL);
7698
7699           /* Note: We don't have to watch for the main subfile here, type units
7700              don't have DW_AT_name.  */
7701
7702           if (current_subfile->symtab == NULL)
7703             {
7704               /* NOTE: start_subfile will recognize when it's been passed
7705                  a file it has already seen.  So we can't assume there's a
7706                  simple mapping from lh->file_names to subfiles,
7707                  lh->file_names may contain dups.  */
7708               current_subfile->symtab = allocate_symtab (current_subfile->name,
7709                                                          objfile);
7710             }
7711
7712           fe->symtab = current_subfile->symtab;
7713           tu_group->symtabs[i] = fe->symtab;
7714         }
7715     }
7716   else
7717     {
7718       restart_symtab (0);
7719
7720       for (i = 0; i < lh->num_file_names; ++i)
7721         {
7722           struct file_entry *fe = &lh->file_names[i];
7723
7724           fe->symtab = tu_group->symtabs[i];
7725         }
7726     }
7727
7728   /* The main symtab is allocated last.  Type units don't have DW_AT_name
7729      so they don't have a "real" (so to speak) symtab anyway.
7730      There is later code that will assign the main symtab to all symbols
7731      that don't have one.  We need to handle the case of a symbol with a
7732      missing symtab (DW_AT_decl_file) anyway.  */
7733 }
7734
7735 /* Process DW_TAG_type_unit.
7736    For TUs we want to skip the first top level sibling if it's not the
7737    actual type being defined by this TU.  In this case the first top
7738    level sibling is there to provide context only.  */
7739
7740 static void
7741 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
7742 {
7743   struct die_info *child_die;
7744
7745   prepare_one_comp_unit (cu, die, language_minimal);
7746
7747   /* Initialize (or reinitialize) the machinery for building symtabs.
7748      We do this before processing child DIEs, so that the line header table
7749      is available for DW_AT_decl_file.  */
7750   setup_type_unit_groups (die, cu);
7751
7752   if (die->child != NULL)
7753     {
7754       child_die = die->child;
7755       while (child_die && child_die->tag)
7756         {
7757           process_die (child_die, cu);
7758           child_die = sibling_die (child_die);
7759         }
7760     }
7761 }
7762 \f
7763 /* DWO files.  */
7764
7765 static hashval_t
7766 hash_dwo_file (const void *item)
7767 {
7768   const struct dwo_file *dwo_file = item;
7769
7770   return htab_hash_string (dwo_file->dwo_name);
7771 }
7772
7773 static int
7774 eq_dwo_file (const void *item_lhs, const void *item_rhs)
7775 {
7776   const struct dwo_file *lhs = item_lhs;
7777   const struct dwo_file *rhs = item_rhs;
7778
7779   return strcmp (lhs->dwo_name, rhs->dwo_name) == 0;
7780 }
7781
7782 /* Allocate a hash table for DWO files.  */
7783
7784 static htab_t
7785 allocate_dwo_file_hash_table (void)
7786 {
7787   struct objfile *objfile = dwarf2_per_objfile->objfile;
7788
7789   return htab_create_alloc_ex (41,
7790                                hash_dwo_file,
7791                                eq_dwo_file,
7792                                NULL,
7793                                &objfile->objfile_obstack,
7794                                hashtab_obstack_allocate,
7795                                dummy_obstack_deallocate);
7796 }
7797
7798 static hashval_t
7799 hash_dwo_unit (const void *item)
7800 {
7801   const struct dwo_unit *dwo_unit = item;
7802
7803   /* This drops the top 32 bits of the id, but is ok for a hash.  */
7804   return dwo_unit->signature;
7805 }
7806
7807 static int
7808 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
7809 {
7810   const struct dwo_unit *lhs = item_lhs;
7811   const struct dwo_unit *rhs = item_rhs;
7812
7813   /* The signature is assumed to be unique within the DWO file.
7814      So while object file CU dwo_id's always have the value zero,
7815      that's OK, assuming each object file DWO file has only one CU,
7816      and that's the rule for now.  */
7817   return lhs->signature == rhs->signature;
7818 }
7819
7820 /* Allocate a hash table for DWO CUs,TUs.
7821    There is one of these tables for each of CUs,TUs for each DWO file.  */
7822
7823 static htab_t
7824 allocate_dwo_unit_table (struct objfile *objfile)
7825 {
7826   /* Start out with a pretty small number.
7827      Generally DWO files contain only one CU and maybe some TUs.  */
7828   return htab_create_alloc_ex (3,
7829                                hash_dwo_unit,
7830                                eq_dwo_unit,
7831                                NULL,
7832                                &objfile->objfile_obstack,
7833                                hashtab_obstack_allocate,
7834                                dummy_obstack_deallocate);
7835 }
7836
7837 /* This function is mapped across the sections and remembers the offset and
7838    size of each of the DWO debugging sections we are interested in.  */
7839
7840 static void
7841 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_file_ptr)
7842 {
7843   struct dwo_file *dwo_file = dwo_file_ptr;
7844   const struct dwo_section_names *names = &dwo_section_names;
7845
7846   if (section_is_p (sectp->name, &names->abbrev_dwo))
7847     {
7848       dwo_file->sections.abbrev.asection = sectp;
7849       dwo_file->sections.abbrev.size = bfd_get_section_size (sectp);
7850     }
7851   else if (section_is_p (sectp->name, &names->info_dwo))
7852     {
7853       dwo_file->sections.info.asection = sectp;
7854       dwo_file->sections.info.size = bfd_get_section_size (sectp);
7855     }
7856   else if (section_is_p (sectp->name, &names->line_dwo))
7857     {
7858       dwo_file->sections.line.asection = sectp;
7859       dwo_file->sections.line.size = bfd_get_section_size (sectp);
7860     }
7861   else if (section_is_p (sectp->name, &names->loc_dwo))
7862     {
7863       dwo_file->sections.loc.asection = sectp;
7864       dwo_file->sections.loc.size = bfd_get_section_size (sectp);
7865     }
7866   else if (section_is_p (sectp->name, &names->macinfo_dwo))
7867     {
7868       dwo_file->sections.macinfo.asection = sectp;
7869       dwo_file->sections.macinfo.size = bfd_get_section_size (sectp);
7870     }
7871   else if (section_is_p (sectp->name, &names->macro_dwo))
7872     {
7873       dwo_file->sections.macro.asection = sectp;
7874       dwo_file->sections.macro.size = bfd_get_section_size (sectp);
7875     }
7876   else if (section_is_p (sectp->name, &names->str_dwo))
7877     {
7878       dwo_file->sections.str.asection = sectp;
7879       dwo_file->sections.str.size = bfd_get_section_size (sectp);
7880     }
7881   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
7882     {
7883       dwo_file->sections.str_offsets.asection = sectp;
7884       dwo_file->sections.str_offsets.size = bfd_get_section_size (sectp);
7885     }
7886   else if (section_is_p (sectp->name, &names->types_dwo))
7887     {
7888       struct dwarf2_section_info type_section;
7889
7890       memset (&type_section, 0, sizeof (type_section));
7891       type_section.asection = sectp;
7892       type_section.size = bfd_get_section_size (sectp);
7893       VEC_safe_push (dwarf2_section_info_def, dwo_file->sections.types,
7894                      &type_section);
7895     }
7896 }
7897
7898 /* Structure used to pass data to create_debug_info_hash_table_reader.  */
7899
7900 struct create_dwo_info_table_data
7901 {
7902   struct dwo_file *dwo_file;
7903   htab_t cu_htab;
7904 };
7905
7906 /* die_reader_func for create_debug_info_hash_table.  */
7907
7908 static void
7909 create_debug_info_hash_table_reader (const struct die_reader_specs *reader,
7910                                      gdb_byte *info_ptr,
7911                                      struct die_info *comp_unit_die,
7912                                      int has_children,
7913                                      void *datap)
7914 {
7915   struct dwarf2_cu *cu = reader->cu;
7916   struct objfile *objfile = dwarf2_per_objfile->objfile;
7917   sect_offset offset = cu->per_cu->offset;
7918   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
7919   struct create_dwo_info_table_data *data = datap;
7920   struct dwo_file *dwo_file = data->dwo_file;
7921   htab_t cu_htab = data->cu_htab;
7922   void **slot;
7923   struct attribute *attr;
7924   struct dwo_unit *dwo_unit;
7925
7926   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7927   if (attr == NULL)
7928     {
7929       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
7930                " its dwo_id [in module %s]"),
7931              offset.sect_off, dwo_file->dwo_name);
7932       return;
7933     }
7934
7935   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
7936   dwo_unit->dwo_file = dwo_file;
7937   dwo_unit->signature = DW_UNSND (attr);
7938   dwo_unit->info_or_types_section = section;
7939   dwo_unit->offset = offset;
7940   dwo_unit->length = cu->per_cu->length;
7941
7942   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
7943   gdb_assert (slot != NULL);
7944   if (*slot != NULL)
7945     {
7946       const struct dwo_unit *dup_dwo_unit = *slot;
7947
7948       complaint (&symfile_complaints,
7949                  _("debug entry at offset 0x%x is duplicate to the entry at"
7950                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
7951                  offset.sect_off, dup_dwo_unit->offset.sect_off,
7952                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
7953                  dwo_file->dwo_name);
7954     }
7955   else
7956     *slot = dwo_unit;
7957
7958   if (dwarf2_read_debug)
7959     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
7960                         offset.sect_off,
7961                         phex (dwo_unit->signature,
7962                               sizeof (dwo_unit->signature)));
7963 }
7964
7965 /* Create a hash table to map DWO IDs to their CU entry in .debug_info.dwo.  */
7966
7967 static htab_t
7968 create_debug_info_hash_table (struct dwo_file *dwo_file)
7969 {
7970   struct objfile *objfile = dwarf2_per_objfile->objfile;
7971   struct dwarf2_section_info *section = &dwo_file->sections.info;
7972   bfd *abfd;
7973   htab_t cu_htab;
7974   gdb_byte *info_ptr, *end_ptr;
7975   struct create_dwo_info_table_data create_dwo_info_table_data;
7976
7977   dwarf2_read_section (objfile, section);
7978   info_ptr = section->buffer;
7979
7980   if (info_ptr == NULL)
7981     return NULL;
7982
7983   /* We can't set abfd until now because the section may be empty or
7984      not present, in which case section->asection will be NULL.  */
7985   abfd = section->asection->owner;
7986
7987   if (dwarf2_read_debug)
7988     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
7989                         bfd_get_filename (abfd));
7990
7991   cu_htab = allocate_dwo_unit_table (objfile);
7992
7993   create_dwo_info_table_data.dwo_file = dwo_file;
7994   create_dwo_info_table_data.cu_htab = cu_htab;
7995
7996   end_ptr = info_ptr + section->size;
7997   while (info_ptr < end_ptr)
7998     {
7999       struct dwarf2_per_cu_data per_cu;
8000
8001       memset (&per_cu, 0, sizeof (per_cu));
8002       per_cu.objfile = objfile;
8003       per_cu.is_debug_types = 0;
8004       per_cu.offset.sect_off = info_ptr - section->buffer;
8005       per_cu.info_or_types_section = section;
8006
8007       init_cutu_and_read_dies_no_follow (&per_cu,
8008                                          &dwo_file->sections.abbrev,
8009                                          dwo_file,
8010                                          create_debug_info_hash_table_reader,
8011                                          &create_dwo_info_table_data);
8012
8013       info_ptr += per_cu.length;
8014     }
8015
8016   return cu_htab;
8017 }
8018
8019 /* Subroutine of open_dwo_file to simplify it.
8020    Open the file specified by FILE_NAME and hand it off to BFD for
8021    preliminary analysis.  Return a newly initialized bfd *, which
8022    includes a canonicalized copy of FILE_NAME.
8023    In case of trouble, return NULL.
8024    NOTE: This function is derived from symfile_bfd_open.  */
8025
8026 static bfd *
8027 try_open_dwo_file (const char *file_name)
8028 {
8029   bfd *sym_bfd;
8030   int desc;
8031   char *absolute_name;
8032
8033   desc = openp (debug_file_directory, OPF_TRY_CWD_FIRST, file_name,
8034                 O_RDONLY | O_BINARY, &absolute_name);
8035   if (desc < 0)
8036     return NULL;
8037
8038   sym_bfd = bfd_fopen (absolute_name, gnutarget, FOPEN_RB, desc);
8039   if (!sym_bfd)
8040     {
8041       xfree (absolute_name);
8042       return NULL;
8043     }
8044   bfd_set_cacheable (sym_bfd, 1);
8045
8046   if (!bfd_check_format (sym_bfd, bfd_object))
8047     {
8048       bfd_close (sym_bfd); /* This also closes desc.  */
8049       xfree (absolute_name);
8050       return NULL;
8051     }
8052
8053   /* bfd_usrdata exists for applications and libbfd must not touch it.  */
8054   gdb_assert (bfd_usrdata (sym_bfd) == NULL);
8055
8056   return sym_bfd;
8057 }
8058
8059 /* Try to open DWO file DWO_NAME.
8060    COMP_DIR is the DW_AT_comp_dir attribute.
8061    The result is the bfd handle of the file.
8062    If there is a problem finding or opening the file, return NULL.
8063    Upon success, the canonicalized path of the file is stored in the bfd,
8064    same as symfile_bfd_open.  */
8065
8066 static bfd *
8067 open_dwo_file (const char *dwo_name, const char *comp_dir)
8068 {
8069   bfd *abfd;
8070
8071   if (IS_ABSOLUTE_PATH (dwo_name))
8072     return try_open_dwo_file (dwo_name);
8073
8074   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8075
8076   if (comp_dir != NULL)
8077     {
8078       char *path_to_try = concat (comp_dir, SLASH_STRING, dwo_name, NULL);
8079
8080       /* NOTE: If comp_dir is a relative path, this will also try the
8081          search path, which seems useful.  */
8082       abfd = try_open_dwo_file (path_to_try);
8083       xfree (path_to_try);
8084       if (abfd != NULL)
8085         return abfd;
8086     }
8087
8088   /* That didn't work, try debug-file-directory, which, despite its name,
8089      is a list of paths.  */
8090
8091   if (*debug_file_directory == '\0')
8092     return NULL;
8093
8094   return try_open_dwo_file (dwo_name);
8095 }
8096
8097 /* Initialize the use of the DWO file specified by DWO_NAME.  */
8098
8099 static struct dwo_file *
8100 init_dwo_file (const char *dwo_name, const char *comp_dir)
8101 {
8102   struct objfile *objfile = dwarf2_per_objfile->objfile;
8103   struct dwo_file *dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8104                                               struct dwo_file);
8105   bfd *abfd;
8106   struct cleanup *cleanups;
8107
8108   if (dwarf2_read_debug)
8109     fprintf_unfiltered (gdb_stdlog, "Reading DWO file %s:\n", dwo_name);
8110
8111   abfd = open_dwo_file (dwo_name, comp_dir);
8112   if (abfd == NULL)
8113     return NULL;
8114   dwo_file->dwo_name = dwo_name;
8115   dwo_file->dwo_bfd = abfd;
8116
8117   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8118
8119   bfd_map_over_sections (abfd, dwarf2_locate_dwo_sections, dwo_file);
8120
8121   dwo_file->cus = create_debug_info_hash_table (dwo_file);
8122
8123   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8124                                                  dwo_file->sections.types);
8125
8126   discard_cleanups (cleanups);
8127
8128   return dwo_file;
8129 }
8130
8131 /* Lookup DWO file DWO_NAME.  */
8132
8133 static struct dwo_file *
8134 lookup_dwo_file (char *dwo_name, const char *comp_dir)
8135 {
8136   struct dwo_file *dwo_file;
8137   struct dwo_file find_entry;
8138   void **slot;
8139
8140   if (dwarf2_per_objfile->dwo_files == NULL)
8141     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8142
8143   /* Have we already seen this DWO file?  */
8144   find_entry.dwo_name = dwo_name;
8145   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8146
8147   /* If not, read it in and build a table of the DWOs it contains.  */
8148   if (*slot == NULL)
8149     *slot = init_dwo_file (dwo_name, comp_dir);
8150
8151   /* NOTE: This will be NULL if unable to open the file.  */
8152   dwo_file = *slot;
8153
8154   return dwo_file;
8155 }
8156
8157 /* Lookup the DWO CU referenced from THIS_CU in DWO file DWO_NAME.
8158    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
8159    SIGNATURE is the "dwo_id" of the CU (for consistency we use the same
8160    nomenclature as TUs).
8161    The result is a pointer to the dwo_unit object or NULL if we didn't find it
8162    (dwo_id mismatch or couldn't find the DWO file).  */
8163
8164 static struct dwo_unit *
8165 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
8166                       char *dwo_name, const char *comp_dir,
8167                       ULONGEST signature)
8168 {
8169   struct objfile *objfile = dwarf2_per_objfile->objfile;
8170   struct dwo_file *dwo_file;
8171
8172   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
8173   if (dwo_file == NULL)
8174     return NULL;
8175
8176   /* Look up the DWO using its signature(dwo_id).  */
8177
8178   if (dwo_file->cus != NULL)
8179     {
8180       struct dwo_unit find_dwo_cu, *dwo_cu;
8181
8182       find_dwo_cu.signature = signature;
8183       dwo_cu = htab_find (dwo_file->cus, &find_dwo_cu);
8184
8185       if (dwo_cu != NULL)
8186         return dwo_cu;
8187     }
8188
8189   /* We didn't find it.  This must mean a dwo_id mismatch.  */
8190
8191   complaint (&symfile_complaints,
8192              _("Could not find DWO CU referenced by CU at offset 0x%x"
8193                " [in module %s]"),
8194              this_cu->offset.sect_off, objfile->name);
8195   return NULL;
8196 }
8197
8198 /* Lookup the DWO TU referenced from THIS_TU in DWO file DWO_NAME.
8199    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
8200    The result is a pointer to the dwo_unit object or NULL if we didn't find it
8201    (dwo_id mismatch or couldn't find the DWO file).  */
8202
8203 static struct dwo_unit *
8204 lookup_dwo_type_unit (struct signatured_type *this_tu,
8205                       char *dwo_name, const char *comp_dir)
8206 {
8207   struct objfile *objfile = dwarf2_per_objfile->objfile;
8208   struct dwo_file *dwo_file;
8209
8210   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
8211   if (dwo_file == NULL)
8212     return NULL;
8213
8214   /* Look up the DWO using its signature(dwo_id).  */
8215
8216   if (dwo_file->tus != NULL)
8217     {
8218       struct dwo_unit find_dwo_tu, *dwo_tu;
8219
8220       find_dwo_tu.signature = this_tu->signature;
8221       dwo_tu = htab_find (dwo_file->tus, &find_dwo_tu);
8222
8223       if (dwo_tu != NULL)
8224         return dwo_tu;
8225     }
8226
8227   /* We didn't find it.  This must mean a dwo_id mismatch.  */
8228
8229   complaint (&symfile_complaints,
8230              _("Could not find DWO TU referenced by TU at offset 0x%x"
8231                " [in module %s]"),
8232              this_tu->per_cu.offset.sect_off, objfile->name);
8233   return NULL;
8234 }
8235
8236 /* Free all resources associated with DWO_FILE.
8237    Close the DWO file and munmap the sections.
8238    All memory should be on the objfile obstack.  */
8239
8240 static void
8241 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
8242 {
8243   int ix;
8244   struct dwarf2_section_info *section;
8245
8246   gdb_assert (dwo_file->dwo_bfd != objfile->obfd);
8247   bfd_close (dwo_file->dwo_bfd);
8248
8249   munmap_section_buffer (&dwo_file->sections.abbrev);
8250   munmap_section_buffer (&dwo_file->sections.info);
8251   munmap_section_buffer (&dwo_file->sections.line);
8252   munmap_section_buffer (&dwo_file->sections.loc);
8253   munmap_section_buffer (&dwo_file->sections.str);
8254   munmap_section_buffer (&dwo_file->sections.str_offsets);
8255
8256   for (ix = 0;
8257        VEC_iterate (dwarf2_section_info_def, dwo_file->sections.types,
8258                     ix, section);
8259        ++ix)
8260     munmap_section_buffer (section);
8261
8262   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
8263 }
8264
8265 /* Wrapper for free_dwo_file for use in cleanups.  */
8266
8267 static void
8268 free_dwo_file_cleanup (void *arg)
8269 {
8270   struct dwo_file *dwo_file = (struct dwo_file *) arg;
8271   struct objfile *objfile = dwarf2_per_objfile->objfile;
8272
8273   free_dwo_file (dwo_file, objfile);
8274 }
8275
8276 /* Traversal function for free_dwo_files.  */
8277
8278 static int
8279 free_dwo_file_from_slot (void **slot, void *info)
8280 {
8281   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8282   struct objfile *objfile = (struct objfile *) info;
8283
8284   free_dwo_file (dwo_file, objfile);
8285
8286   return 1;
8287 }
8288
8289 /* Free all resources associated with DWO_FILES.  */
8290
8291 static void
8292 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
8293 {
8294   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
8295 }
8296 \f
8297 /* Read in various DIEs.  */
8298
8299 /* qsort helper for inherit_abstract_dies.  */
8300
8301 static int
8302 unsigned_int_compar (const void *ap, const void *bp)
8303 {
8304   unsigned int a = *(unsigned int *) ap;
8305   unsigned int b = *(unsigned int *) bp;
8306
8307   return (a > b) - (b > a);
8308 }
8309
8310 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
8311    Inherit only the children of the DW_AT_abstract_origin DIE not being
8312    already referenced by DW_AT_abstract_origin from the children of the
8313    current DIE.  */
8314
8315 static void
8316 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
8317 {
8318   struct die_info *child_die;
8319   unsigned die_children_count;
8320   /* CU offsets which were referenced by children of the current DIE.  */
8321   sect_offset *offsets;
8322   sect_offset *offsets_end, *offsetp;
8323   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
8324   struct die_info *origin_die;
8325   /* Iterator of the ORIGIN_DIE children.  */
8326   struct die_info *origin_child_die;
8327   struct cleanup *cleanups;
8328   struct attribute *attr;
8329   struct dwarf2_cu *origin_cu;
8330   struct pending **origin_previous_list_in_scope;
8331
8332   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
8333   if (!attr)
8334     return;
8335
8336   /* Note that following die references may follow to a die in a
8337      different cu.  */
8338
8339   origin_cu = cu;
8340   origin_die = follow_die_ref (die, attr, &origin_cu);
8341
8342   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
8343      symbols in.  */
8344   origin_previous_list_in_scope = origin_cu->list_in_scope;
8345   origin_cu->list_in_scope = cu->list_in_scope;
8346
8347   if (die->tag != origin_die->tag
8348       && !(die->tag == DW_TAG_inlined_subroutine
8349            && origin_die->tag == DW_TAG_subprogram))
8350     complaint (&symfile_complaints,
8351                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
8352                die->offset.sect_off, origin_die->offset.sect_off);
8353
8354   child_die = die->child;
8355   die_children_count = 0;
8356   while (child_die && child_die->tag)
8357     {
8358       child_die = sibling_die (child_die);
8359       die_children_count++;
8360     }
8361   offsets = xmalloc (sizeof (*offsets) * die_children_count);
8362   cleanups = make_cleanup (xfree, offsets);
8363
8364   offsets_end = offsets;
8365   child_die = die->child;
8366   while (child_die && child_die->tag)
8367     {
8368       /* For each CHILD_DIE, find the corresponding child of
8369          ORIGIN_DIE.  If there is more than one layer of
8370          DW_AT_abstract_origin, follow them all; there shouldn't be,
8371          but GCC versions at least through 4.4 generate this (GCC PR
8372          40573).  */
8373       struct die_info *child_origin_die = child_die;
8374       struct dwarf2_cu *child_origin_cu = cu;
8375
8376       while (1)
8377         {
8378           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
8379                               child_origin_cu);
8380           if (attr == NULL)
8381             break;
8382           child_origin_die = follow_die_ref (child_origin_die, attr,
8383                                              &child_origin_cu);
8384         }
8385
8386       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
8387          counterpart may exist.  */
8388       if (child_origin_die != child_die)
8389         {
8390           if (child_die->tag != child_origin_die->tag
8391               && !(child_die->tag == DW_TAG_inlined_subroutine
8392                    && child_origin_die->tag == DW_TAG_subprogram))
8393             complaint (&symfile_complaints,
8394                        _("Child DIE 0x%x and its abstract origin 0x%x have "
8395                          "different tags"), child_die->offset.sect_off,
8396                        child_origin_die->offset.sect_off);
8397           if (child_origin_die->parent != origin_die)
8398             complaint (&symfile_complaints,
8399                        _("Child DIE 0x%x and its abstract origin 0x%x have "
8400                          "different parents"), child_die->offset.sect_off,
8401                        child_origin_die->offset.sect_off);
8402           else
8403             *offsets_end++ = child_origin_die->offset;
8404         }
8405       child_die = sibling_die (child_die);
8406     }
8407   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
8408          unsigned_int_compar);
8409   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
8410     if (offsetp[-1].sect_off == offsetp->sect_off)
8411       complaint (&symfile_complaints,
8412                  _("Multiple children of DIE 0x%x refer "
8413                    "to DIE 0x%x as their abstract origin"),
8414                  die->offset.sect_off, offsetp->sect_off);
8415
8416   offsetp = offsets;
8417   origin_child_die = origin_die->child;
8418   while (origin_child_die && origin_child_die->tag)
8419     {
8420       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
8421       while (offsetp < offsets_end
8422              && offsetp->sect_off < origin_child_die->offset.sect_off)
8423         offsetp++;
8424       if (offsetp >= offsets_end
8425           || offsetp->sect_off > origin_child_die->offset.sect_off)
8426         {
8427           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
8428           process_die (origin_child_die, origin_cu);
8429         }
8430       origin_child_die = sibling_die (origin_child_die);
8431     }
8432   origin_cu->list_in_scope = origin_previous_list_in_scope;
8433
8434   do_cleanups (cleanups);
8435 }
8436
8437 static void
8438 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
8439 {
8440   struct objfile *objfile = cu->objfile;
8441   struct context_stack *new;
8442   CORE_ADDR lowpc;
8443   CORE_ADDR highpc;
8444   struct die_info *child_die;
8445   struct attribute *attr, *call_line, *call_file;
8446   char *name;
8447   CORE_ADDR baseaddr;
8448   struct block *block;
8449   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
8450   VEC (symbolp) *template_args = NULL;
8451   struct template_symbol *templ_func = NULL;
8452
8453   if (inlined_func)
8454     {
8455       /* If we do not have call site information, we can't show the
8456          caller of this inlined function.  That's too confusing, so
8457          only use the scope for local variables.  */
8458       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
8459       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
8460       if (call_line == NULL || call_file == NULL)
8461         {
8462           read_lexical_block_scope (die, cu);
8463           return;
8464         }
8465     }
8466
8467   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8468
8469   name = dwarf2_name (die, cu);
8470
8471   /* Ignore functions with missing or empty names.  These are actually
8472      illegal according to the DWARF standard.  */
8473   if (name == NULL)
8474     {
8475       complaint (&symfile_complaints,
8476                  _("missing name for subprogram DIE at %d"),
8477                  die->offset.sect_off);
8478       return;
8479     }
8480
8481   /* Ignore functions with missing or invalid low and high pc attributes.  */
8482   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
8483     {
8484       attr = dwarf2_attr (die, DW_AT_external, cu);
8485       if (!attr || !DW_UNSND (attr))
8486         complaint (&symfile_complaints,
8487                    _("cannot get low and high bounds "
8488                      "for subprogram DIE at %d"),
8489                    die->offset.sect_off);
8490       return;
8491     }
8492
8493   lowpc += baseaddr;
8494   highpc += baseaddr;
8495
8496   /* If we have any template arguments, then we must allocate a
8497      different sort of symbol.  */
8498   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
8499     {
8500       if (child_die->tag == DW_TAG_template_type_param
8501           || child_die->tag == DW_TAG_template_value_param)
8502         {
8503           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8504                                        struct template_symbol);
8505           templ_func->base.is_cplus_template_function = 1;
8506           break;
8507         }
8508     }
8509
8510   new = push_context (0, lowpc);
8511   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
8512                                (struct symbol *) templ_func);
8513
8514   /* If there is a location expression for DW_AT_frame_base, record
8515      it.  */
8516   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
8517   if (attr)
8518     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
8519        expression is being recorded directly in the function's symbol
8520        and not in a separate frame-base object.  I guess this hack is
8521        to avoid adding some sort of frame-base adjunct/annex to the
8522        function's symbol :-(.  The problem with doing this is that it
8523        results in a function symbol with a location expression that
8524        has nothing to do with the location of the function, ouch!  The
8525        relationship should be: a function's symbol has-a frame base; a
8526        frame-base has-a location expression.  */
8527     dwarf2_symbol_mark_computed (attr, new->name, cu);
8528
8529   cu->list_in_scope = &local_symbols;
8530
8531   if (die->child != NULL)
8532     {
8533       child_die = die->child;
8534       while (child_die && child_die->tag)
8535         {
8536           if (child_die->tag == DW_TAG_template_type_param
8537               || child_die->tag == DW_TAG_template_value_param)
8538             {
8539               struct symbol *arg = new_symbol (child_die, NULL, cu);
8540
8541               if (arg != NULL)
8542                 VEC_safe_push (symbolp, template_args, arg);
8543             }
8544           else
8545             process_die (child_die, cu);
8546           child_die = sibling_die (child_die);
8547         }
8548     }
8549
8550   inherit_abstract_dies (die, cu);
8551
8552   /* If we have a DW_AT_specification, we might need to import using
8553      directives from the context of the specification DIE.  See the
8554      comment in determine_prefix.  */
8555   if (cu->language == language_cplus
8556       && dwarf2_attr (die, DW_AT_specification, cu))
8557     {
8558       struct dwarf2_cu *spec_cu = cu;
8559       struct die_info *spec_die = die_specification (die, &spec_cu);
8560
8561       while (spec_die)
8562         {
8563           child_die = spec_die->child;
8564           while (child_die && child_die->tag)
8565             {
8566               if (child_die->tag == DW_TAG_imported_module)
8567                 process_die (child_die, spec_cu);
8568               child_die = sibling_die (child_die);
8569             }
8570
8571           /* In some cases, GCC generates specification DIEs that
8572              themselves contain DW_AT_specification attributes.  */
8573           spec_die = die_specification (spec_die, &spec_cu);
8574         }
8575     }
8576
8577   new = pop_context ();
8578   /* Make a block for the local symbols within.  */
8579   block = finish_block (new->name, &local_symbols, new->old_blocks,
8580                         lowpc, highpc, objfile);
8581
8582   /* For C++, set the block's scope.  */
8583   if (cu->language == language_cplus || cu->language == language_fortran)
8584     cp_set_block_scope (new->name, block, &objfile->objfile_obstack,
8585                         determine_prefix (die, cu),
8586                         processing_has_namespace_info);
8587
8588   /* If we have address ranges, record them.  */
8589   dwarf2_record_block_ranges (die, block, baseaddr, cu);
8590
8591   /* Attach template arguments to function.  */
8592   if (! VEC_empty (symbolp, template_args))
8593     {
8594       gdb_assert (templ_func != NULL);
8595
8596       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
8597       templ_func->template_arguments
8598         = obstack_alloc (&objfile->objfile_obstack,
8599                          (templ_func->n_template_arguments
8600                           * sizeof (struct symbol *)));
8601       memcpy (templ_func->template_arguments,
8602               VEC_address (symbolp, template_args),
8603               (templ_func->n_template_arguments * sizeof (struct symbol *)));
8604       VEC_free (symbolp, template_args);
8605     }
8606
8607   /* In C++, we can have functions nested inside functions (e.g., when
8608      a function declares a class that has methods).  This means that
8609      when we finish processing a function scope, we may need to go
8610      back to building a containing block's symbol lists.  */
8611   local_symbols = new->locals;
8612   param_symbols = new->params;
8613   using_directives = new->using_directives;
8614
8615   /* If we've finished processing a top-level function, subsequent
8616      symbols go in the file symbol list.  */
8617   if (outermost_context_p ())
8618     cu->list_in_scope = &file_symbols;
8619 }
8620
8621 /* Process all the DIES contained within a lexical block scope.  Start
8622    a new scope, process the dies, and then close the scope.  */
8623
8624 static void
8625 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
8626 {
8627   struct objfile *objfile = cu->objfile;
8628   struct context_stack *new;
8629   CORE_ADDR lowpc, highpc;
8630   struct die_info *child_die;
8631   CORE_ADDR baseaddr;
8632
8633   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8634
8635   /* Ignore blocks with missing or invalid low and high pc attributes.  */
8636   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
8637      as multiple lexical blocks?  Handling children in a sane way would
8638      be nasty.  Might be easier to properly extend generic blocks to
8639      describe ranges.  */
8640   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
8641     return;
8642   lowpc += baseaddr;
8643   highpc += baseaddr;
8644
8645   push_context (0, lowpc);
8646   if (die->child != NULL)
8647     {
8648       child_die = die->child;
8649       while (child_die && child_die->tag)
8650         {
8651           process_die (child_die, cu);
8652           child_die = sibling_die (child_die);
8653         }
8654     }
8655   new = pop_context ();
8656
8657   if (local_symbols != NULL || using_directives != NULL)
8658     {
8659       struct block *block
8660         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
8661                         highpc, objfile);
8662
8663       /* Note that recording ranges after traversing children, as we
8664          do here, means that recording a parent's ranges entails
8665          walking across all its children's ranges as they appear in
8666          the address map, which is quadratic behavior.
8667
8668          It would be nicer to record the parent's ranges before
8669          traversing its children, simply overriding whatever you find
8670          there.  But since we don't even decide whether to create a
8671          block until after we've traversed its children, that's hard
8672          to do.  */
8673       dwarf2_record_block_ranges (die, block, baseaddr, cu);
8674     }
8675   local_symbols = new->locals;
8676   using_directives = new->using_directives;
8677 }
8678
8679 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
8680
8681 static void
8682 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
8683 {
8684   struct objfile *objfile = cu->objfile;
8685   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8686   CORE_ADDR pc, baseaddr;
8687   struct attribute *attr;
8688   struct call_site *call_site, call_site_local;
8689   void **slot;
8690   int nparams;
8691   struct die_info *child_die;
8692
8693   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8694
8695   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
8696   if (!attr)
8697     {
8698       complaint (&symfile_complaints,
8699                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
8700                    "DIE 0x%x [in module %s]"),
8701                  die->offset.sect_off, objfile->name);
8702       return;
8703     }
8704   pc = DW_ADDR (attr) + baseaddr;
8705
8706   if (cu->call_site_htab == NULL)
8707     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
8708                                                NULL, &objfile->objfile_obstack,
8709                                                hashtab_obstack_allocate, NULL);
8710   call_site_local.pc = pc;
8711   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
8712   if (*slot != NULL)
8713     {
8714       complaint (&symfile_complaints,
8715                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
8716                    "DIE 0x%x [in module %s]"),
8717                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
8718       return;
8719     }
8720
8721   /* Count parameters at the caller.  */
8722
8723   nparams = 0;
8724   for (child_die = die->child; child_die && child_die->tag;
8725        child_die = sibling_die (child_die))
8726     {
8727       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
8728         {
8729           complaint (&symfile_complaints,
8730                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
8731                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
8732                      child_die->tag, child_die->offset.sect_off, objfile->name);
8733           continue;
8734         }
8735
8736       nparams++;
8737     }
8738
8739   call_site = obstack_alloc (&objfile->objfile_obstack,
8740                              (sizeof (*call_site)
8741                               + (sizeof (*call_site->parameter)
8742                                  * (nparams - 1))));
8743   *slot = call_site;
8744   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
8745   call_site->pc = pc;
8746
8747   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
8748     {
8749       struct die_info *func_die;
8750
8751       /* Skip also over DW_TAG_inlined_subroutine.  */
8752       for (func_die = die->parent;
8753            func_die && func_die->tag != DW_TAG_subprogram
8754            && func_die->tag != DW_TAG_subroutine_type;
8755            func_die = func_die->parent);
8756
8757       /* DW_AT_GNU_all_call_sites is a superset
8758          of DW_AT_GNU_all_tail_call_sites.  */
8759       if (func_die
8760           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
8761           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
8762         {
8763           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
8764              not complete.  But keep CALL_SITE for look ups via call_site_htab,
8765              both the initial caller containing the real return address PC and
8766              the final callee containing the current PC of a chain of tail
8767              calls do not need to have the tail call list complete.  But any
8768              function candidate for a virtual tail call frame searched via
8769              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
8770              determined unambiguously.  */
8771         }
8772       else
8773         {
8774           struct type *func_type = NULL;
8775
8776           if (func_die)
8777             func_type = get_die_type (func_die, cu);
8778           if (func_type != NULL)
8779             {
8780               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
8781
8782               /* Enlist this call site to the function.  */
8783               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
8784               TYPE_TAIL_CALL_LIST (func_type) = call_site;
8785             }
8786           else
8787             complaint (&symfile_complaints,
8788                        _("Cannot find function owning DW_TAG_GNU_call_site "
8789                          "DIE 0x%x [in module %s]"),
8790                        die->offset.sect_off, objfile->name);
8791         }
8792     }
8793
8794   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
8795   if (attr == NULL)
8796     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
8797   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
8798   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
8799     /* Keep NULL DWARF_BLOCK.  */;
8800   else if (attr_form_is_block (attr))
8801     {
8802       struct dwarf2_locexpr_baton *dlbaton;
8803
8804       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
8805       dlbaton->data = DW_BLOCK (attr)->data;
8806       dlbaton->size = DW_BLOCK (attr)->size;
8807       dlbaton->per_cu = cu->per_cu;
8808
8809       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
8810     }
8811   else if (is_ref_attr (attr))
8812     {
8813       struct dwarf2_cu *target_cu = cu;
8814       struct die_info *target_die;
8815
8816       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
8817       gdb_assert (target_cu->objfile == objfile);
8818       if (die_is_declaration (target_die, target_cu))
8819         {
8820           const char *target_physname;
8821
8822           target_physname = dwarf2_physname (NULL, target_die, target_cu);
8823           if (target_physname == NULL)
8824             complaint (&symfile_complaints,
8825                        _("DW_AT_GNU_call_site_target target DIE has invalid "
8826                          "physname, for referencing DIE 0x%x [in module %s]"),
8827                        die->offset.sect_off, objfile->name);
8828           else
8829             SET_FIELD_PHYSNAME (call_site->target, (char *) target_physname);
8830         }
8831       else
8832         {
8833           CORE_ADDR lowpc;
8834
8835           /* DW_AT_entry_pc should be preferred.  */
8836           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
8837             complaint (&symfile_complaints,
8838                        _("DW_AT_GNU_call_site_target target DIE has invalid "
8839                          "low pc, for referencing DIE 0x%x [in module %s]"),
8840                        die->offset.sect_off, objfile->name);
8841           else
8842             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
8843         }
8844     }
8845   else
8846     complaint (&symfile_complaints,
8847                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
8848                  "block nor reference, for DIE 0x%x [in module %s]"),
8849                die->offset.sect_off, objfile->name);
8850
8851   call_site->per_cu = cu->per_cu;
8852
8853   for (child_die = die->child;
8854        child_die && child_die->tag;
8855        child_die = sibling_die (child_die))
8856     {
8857       struct call_site_parameter *parameter;
8858       struct attribute *loc, *origin;
8859
8860       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
8861         {
8862           /* Already printed the complaint above.  */
8863           continue;
8864         }
8865
8866       gdb_assert (call_site->parameter_count < nparams);
8867       parameter = &call_site->parameter[call_site->parameter_count];
8868
8869       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
8870          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
8871          register is contained in DW_AT_GNU_call_site_value.  */
8872
8873       loc = dwarf2_attr (child_die, DW_AT_location, cu);
8874       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
8875       if (loc == NULL && origin != NULL && is_ref_attr (origin))
8876         {
8877           sect_offset offset;
8878
8879           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
8880           offset = dwarf2_get_ref_die_offset (origin);
8881           if (!offset_in_cu_p (&cu->header, offset))
8882             {
8883               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
8884                  binding can be done only inside one CU.  Such referenced DIE
8885                  therefore cannot be even moved to DW_TAG_partial_unit.  */
8886               complaint (&symfile_complaints,
8887                          _("DW_AT_abstract_origin offset is not in CU for "
8888                            "DW_TAG_GNU_call_site child DIE 0x%x "
8889                            "[in module %s]"),
8890                          child_die->offset.sect_off, objfile->name);
8891               continue;
8892             }
8893           parameter->u.param_offset.cu_off = (offset.sect_off
8894                                               - cu->header.offset.sect_off);
8895         }
8896       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
8897         {
8898           complaint (&symfile_complaints,
8899                      _("No DW_FORM_block* DW_AT_location for "
8900                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
8901                      child_die->offset.sect_off, objfile->name);
8902           continue;
8903         }
8904       else
8905         {
8906           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
8907             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
8908           if (parameter->u.dwarf_reg != -1)
8909             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
8910           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
8911                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
8912                                              &parameter->u.fb_offset))
8913             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
8914           else
8915             {
8916               complaint (&symfile_complaints,
8917                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
8918                            "for DW_FORM_block* DW_AT_location is supported for "
8919                            "DW_TAG_GNU_call_site child DIE 0x%x "
8920                            "[in module %s]"),
8921                          child_die->offset.sect_off, objfile->name);
8922               continue;
8923             }
8924         }
8925
8926       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
8927       if (!attr_form_is_block (attr))
8928         {
8929           complaint (&symfile_complaints,
8930                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
8931                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
8932                      child_die->offset.sect_off, objfile->name);
8933           continue;
8934         }
8935       parameter->value = DW_BLOCK (attr)->data;
8936       parameter->value_size = DW_BLOCK (attr)->size;
8937
8938       /* Parameters are not pre-cleared by memset above.  */
8939       parameter->data_value = NULL;
8940       parameter->data_value_size = 0;
8941       call_site->parameter_count++;
8942
8943       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
8944       if (attr)
8945         {
8946           if (!attr_form_is_block (attr))
8947             complaint (&symfile_complaints,
8948                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
8949                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
8950                        child_die->offset.sect_off, objfile->name);
8951           else
8952             {
8953               parameter->data_value = DW_BLOCK (attr)->data;
8954               parameter->data_value_size = DW_BLOCK (attr)->size;
8955             }
8956         }
8957     }
8958 }
8959
8960 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
8961    Return 1 if the attributes are present and valid, otherwise, return 0.
8962    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
8963
8964 static int
8965 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
8966                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
8967                     struct partial_symtab *ranges_pst)
8968 {
8969   struct objfile *objfile = cu->objfile;
8970   struct comp_unit_head *cu_header = &cu->header;
8971   bfd *obfd = objfile->obfd;
8972   unsigned int addr_size = cu_header->addr_size;
8973   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
8974   /* Base address selection entry.  */
8975   CORE_ADDR base;
8976   int found_base;
8977   unsigned int dummy;
8978   gdb_byte *buffer;
8979   CORE_ADDR marker;
8980   int low_set;
8981   CORE_ADDR low = 0;
8982   CORE_ADDR high = 0;
8983   CORE_ADDR baseaddr;
8984
8985   found_base = cu->base_known;
8986   base = cu->base_address;
8987
8988   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
8989   if (offset >= dwarf2_per_objfile->ranges.size)
8990     {
8991       complaint (&symfile_complaints,
8992                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
8993                  offset);
8994       return 0;
8995     }
8996   buffer = dwarf2_per_objfile->ranges.buffer + offset;
8997
8998   /* Read in the largest possible address.  */
8999   marker = read_address (obfd, buffer, cu, &dummy);
9000   if ((marker & mask) == mask)
9001     {
9002       /* If we found the largest possible address, then
9003          read the base address.  */
9004       base = read_address (obfd, buffer + addr_size, cu, &dummy);
9005       buffer += 2 * addr_size;
9006       offset += 2 * addr_size;
9007       found_base = 1;
9008     }
9009
9010   low_set = 0;
9011
9012   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9013
9014   while (1)
9015     {
9016       CORE_ADDR range_beginning, range_end;
9017
9018       range_beginning = read_address (obfd, buffer, cu, &dummy);
9019       buffer += addr_size;
9020       range_end = read_address (obfd, buffer, cu, &dummy);
9021       buffer += addr_size;
9022       offset += 2 * addr_size;
9023
9024       /* An end of list marker is a pair of zero addresses.  */
9025       if (range_beginning == 0 && range_end == 0)
9026         /* Found the end of list entry.  */
9027         break;
9028
9029       /* Each base address selection entry is a pair of 2 values.
9030          The first is the largest possible address, the second is
9031          the base address.  Check for a base address here.  */
9032       if ((range_beginning & mask) == mask)
9033         {
9034           /* If we found the largest possible address, then
9035              read the base address.  */
9036           base = read_address (obfd, buffer + addr_size, cu, &dummy);
9037           found_base = 1;
9038           continue;
9039         }
9040
9041       if (!found_base)
9042         {
9043           /* We have no valid base address for the ranges
9044              data.  */
9045           complaint (&symfile_complaints,
9046                      _("Invalid .debug_ranges data (no base address)"));
9047           return 0;
9048         }
9049
9050       if (range_beginning > range_end)
9051         {
9052           /* Inverted range entries are invalid.  */
9053           complaint (&symfile_complaints,
9054                      _("Invalid .debug_ranges data (inverted range)"));
9055           return 0;
9056         }
9057
9058       /* Empty range entries have no effect.  */
9059       if (range_beginning == range_end)
9060         continue;
9061
9062       range_beginning += base;
9063       range_end += base;
9064
9065       if (ranges_pst != NULL)
9066         addrmap_set_empty (objfile->psymtabs_addrmap,
9067                            range_beginning + baseaddr,
9068                            range_end - 1 + baseaddr,
9069                            ranges_pst);
9070
9071       /* FIXME: This is recording everything as a low-high
9072          segment of consecutive addresses.  We should have a
9073          data structure for discontiguous block ranges
9074          instead.  */
9075       if (! low_set)
9076         {
9077           low = range_beginning;
9078           high = range_end;
9079           low_set = 1;
9080         }
9081       else
9082         {
9083           if (range_beginning < low)
9084             low = range_beginning;
9085           if (range_end > high)
9086             high = range_end;
9087         }
9088     }
9089
9090   if (! low_set)
9091     /* If the first entry is an end-of-list marker, the range
9092        describes an empty scope, i.e. no instructions.  */
9093     return 0;
9094
9095   if (low_return)
9096     *low_return = low;
9097   if (high_return)
9098     *high_return = high;
9099   return 1;
9100 }
9101
9102 /* Get low and high pc attributes from a die.  Return 1 if the attributes
9103    are present and valid, otherwise, return 0.  Return -1 if the range is
9104    discontinuous, i.e. derived from DW_AT_ranges information.  */
9105
9106 static int
9107 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
9108                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
9109                       struct partial_symtab *pst)
9110 {
9111   struct attribute *attr;
9112   struct attribute *attr_high;
9113   CORE_ADDR low = 0;
9114   CORE_ADDR high = 0;
9115   int ret = 0;
9116
9117   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
9118   if (attr_high)
9119     {
9120       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9121       if (attr)
9122         {
9123           low = DW_ADDR (attr);
9124           if (attr_high->form == DW_FORM_addr
9125               || attr_high->form == DW_FORM_GNU_addr_index)
9126             high = DW_ADDR (attr_high);
9127           else
9128             high = low + DW_UNSND (attr_high);
9129         }
9130       else
9131         /* Found high w/o low attribute.  */
9132         return 0;
9133
9134       /* Found consecutive range of addresses.  */
9135       ret = 1;
9136     }
9137   else
9138     {
9139       attr = dwarf2_attr (die, DW_AT_ranges, cu);
9140       if (attr != NULL)
9141         {
9142           unsigned int ranges_offset = DW_UNSND (attr) + cu->ranges_base;
9143
9144           /* Value of the DW_AT_ranges attribute is the offset in the
9145              .debug_ranges section.  */
9146           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
9147             return 0;
9148           /* Found discontinuous range of addresses.  */
9149           ret = -1;
9150         }
9151     }
9152
9153   /* read_partial_die has also the strict LOW < HIGH requirement.  */
9154   if (high <= low)
9155     return 0;
9156
9157   /* When using the GNU linker, .gnu.linkonce. sections are used to
9158      eliminate duplicate copies of functions and vtables and such.
9159      The linker will arbitrarily choose one and discard the others.
9160      The AT_*_pc values for such functions refer to local labels in
9161      these sections.  If the section from that file was discarded, the
9162      labels are not in the output, so the relocs get a value of 0.
9163      If this is a discarded function, mark the pc bounds as invalid,
9164      so that GDB will ignore it.  */
9165   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
9166     return 0;
9167
9168   *lowpc = low;
9169   if (highpc)
9170     *highpc = high;
9171   return ret;
9172 }
9173
9174 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
9175    its low and high PC addresses.  Do nothing if these addresses could not
9176    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
9177    and HIGHPC to the high address if greater than HIGHPC.  */
9178
9179 static void
9180 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
9181                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
9182                                  struct dwarf2_cu *cu)
9183 {
9184   CORE_ADDR low, high;
9185   struct die_info *child = die->child;
9186
9187   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
9188     {
9189       *lowpc = min (*lowpc, low);
9190       *highpc = max (*highpc, high);
9191     }
9192
9193   /* If the language does not allow nested subprograms (either inside
9194      subprograms or lexical blocks), we're done.  */
9195   if (cu->language != language_ada)
9196     return;
9197
9198   /* Check all the children of the given DIE.  If it contains nested
9199      subprograms, then check their pc bounds.  Likewise, we need to
9200      check lexical blocks as well, as they may also contain subprogram
9201      definitions.  */
9202   while (child && child->tag)
9203     {
9204       if (child->tag == DW_TAG_subprogram
9205           || child->tag == DW_TAG_lexical_block)
9206         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
9207       child = sibling_die (child);
9208     }
9209 }
9210
9211 /* Get the low and high pc's represented by the scope DIE, and store
9212    them in *LOWPC and *HIGHPC.  If the correct values can't be
9213    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
9214
9215 static void
9216 get_scope_pc_bounds (struct die_info *die,
9217                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
9218                      struct dwarf2_cu *cu)
9219 {
9220   CORE_ADDR best_low = (CORE_ADDR) -1;
9221   CORE_ADDR best_high = (CORE_ADDR) 0;
9222   CORE_ADDR current_low, current_high;
9223
9224   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
9225     {
9226       best_low = current_low;
9227       best_high = current_high;
9228     }
9229   else
9230     {
9231       struct die_info *child = die->child;
9232
9233       while (child && child->tag)
9234         {
9235           switch (child->tag) {
9236           case DW_TAG_subprogram:
9237             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
9238             break;
9239           case DW_TAG_namespace:
9240           case DW_TAG_module:
9241             /* FIXME: carlton/2004-01-16: Should we do this for
9242                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
9243                that current GCC's always emit the DIEs corresponding
9244                to definitions of methods of classes as children of a
9245                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
9246                the DIEs giving the declarations, which could be
9247                anywhere).  But I don't see any reason why the
9248                standards says that they have to be there.  */
9249             get_scope_pc_bounds (child, &current_low, &current_high, cu);
9250
9251             if (current_low != ((CORE_ADDR) -1))
9252               {
9253                 best_low = min (best_low, current_low);
9254                 best_high = max (best_high, current_high);
9255               }
9256             break;
9257           default:
9258             /* Ignore.  */
9259             break;
9260           }
9261
9262           child = sibling_die (child);
9263         }
9264     }
9265
9266   *lowpc = best_low;
9267   *highpc = best_high;
9268 }
9269
9270 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
9271    in DIE.  */
9272
9273 static void
9274 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
9275                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
9276 {
9277   struct objfile *objfile = cu->objfile;
9278   struct attribute *attr;
9279   struct attribute *attr_high;
9280
9281   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
9282   if (attr_high)
9283     {
9284       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9285       if (attr)
9286         {
9287           CORE_ADDR low = DW_ADDR (attr);
9288           CORE_ADDR high;
9289           if (attr_high->form == DW_FORM_addr
9290               || attr_high->form == DW_FORM_GNU_addr_index)
9291             high = DW_ADDR (attr_high);
9292           else
9293             high = low + DW_UNSND (attr_high);
9294
9295           record_block_range (block, baseaddr + low, baseaddr + high - 1);
9296         }
9297     }
9298
9299   attr = dwarf2_attr (die, DW_AT_ranges, cu);
9300   if (attr)
9301     {
9302       bfd *obfd = objfile->obfd;
9303
9304       /* The value of the DW_AT_ranges attribute is the offset of the
9305          address range list in the .debug_ranges section.  */
9306       unsigned long offset = DW_UNSND (attr) + cu->ranges_base;
9307       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
9308
9309       /* For some target architectures, but not others, the
9310          read_address function sign-extends the addresses it returns.
9311          To recognize base address selection entries, we need a
9312          mask.  */
9313       unsigned int addr_size = cu->header.addr_size;
9314       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9315
9316       /* The base address, to which the next pair is relative.  Note
9317          that this 'base' is a DWARF concept: most entries in a range
9318          list are relative, to reduce the number of relocs against the
9319          debugging information.  This is separate from this function's
9320          'baseaddr' argument, which GDB uses to relocate debugging
9321          information from a shared library based on the address at
9322          which the library was loaded.  */
9323       CORE_ADDR base = cu->base_address;
9324       int base_known = cu->base_known;
9325
9326       gdb_assert (dwarf2_per_objfile->ranges.readin);
9327       if (offset >= dwarf2_per_objfile->ranges.size)
9328         {
9329           complaint (&symfile_complaints,
9330                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
9331                      offset);
9332           return;
9333         }
9334
9335       for (;;)
9336         {
9337           unsigned int bytes_read;
9338           CORE_ADDR start, end;
9339
9340           start = read_address (obfd, buffer, cu, &bytes_read);
9341           buffer += bytes_read;
9342           end = read_address (obfd, buffer, cu, &bytes_read);
9343           buffer += bytes_read;
9344
9345           /* Did we find the end of the range list?  */
9346           if (start == 0 && end == 0)
9347             break;
9348
9349           /* Did we find a base address selection entry?  */
9350           else if ((start & base_select_mask) == base_select_mask)
9351             {
9352               base = end;
9353               base_known = 1;
9354             }
9355
9356           /* We found an ordinary address range.  */
9357           else
9358             {
9359               if (!base_known)
9360                 {
9361                   complaint (&symfile_complaints,
9362                              _("Invalid .debug_ranges data "
9363                                "(no base address)"));
9364                   return;
9365                 }
9366
9367               if (start > end)
9368                 {
9369                   /* Inverted range entries are invalid.  */
9370                   complaint (&symfile_complaints,
9371                              _("Invalid .debug_ranges data "
9372                                "(inverted range)"));
9373                   return;
9374                 }
9375
9376               /* Empty range entries have no effect.  */
9377               if (start == end)
9378                 continue;
9379
9380               record_block_range (block,
9381                                   baseaddr + base + start,
9382                                   baseaddr + base + end - 1);
9383             }
9384         }
9385     }
9386 }
9387
9388 /* Check whether the producer field indicates either of GCC < 4.6, or the
9389    Intel C/C++ compiler, and cache the result in CU.  */
9390
9391 static void
9392 check_producer (struct dwarf2_cu *cu)
9393 {
9394   const char *cs;
9395   int major, minor, release;
9396
9397   if (cu->producer == NULL)
9398     {
9399       /* For unknown compilers expect their behavior is DWARF version
9400          compliant.
9401
9402          GCC started to support .debug_types sections by -gdwarf-4 since
9403          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
9404          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
9405          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
9406          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
9407     }
9408   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
9409     {
9410       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
9411
9412       cs = &cu->producer[strlen ("GNU ")];
9413       while (*cs && !isdigit (*cs))
9414         cs++;
9415       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
9416         {
9417           /* Not recognized as GCC.  */
9418         }
9419       else
9420         cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
9421     }
9422   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
9423     cu->producer_is_icc = 1;
9424   else
9425     {
9426       /* For other non-GCC compilers, expect their behavior is DWARF version
9427          compliant.  */
9428     }
9429
9430   cu->checked_producer = 1;
9431 }
9432
9433 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
9434    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
9435    during 4.6.0 experimental.  */
9436
9437 static int
9438 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
9439 {
9440   if (!cu->checked_producer)
9441     check_producer (cu);
9442
9443   return cu->producer_is_gxx_lt_4_6;
9444 }
9445
9446 /* Return the default accessibility type if it is not overriden by
9447    DW_AT_accessibility.  */
9448
9449 static enum dwarf_access_attribute
9450 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
9451 {
9452   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
9453     {
9454       /* The default DWARF 2 accessibility for members is public, the default
9455          accessibility for inheritance is private.  */
9456
9457       if (die->tag != DW_TAG_inheritance)
9458         return DW_ACCESS_public;
9459       else
9460         return DW_ACCESS_private;
9461     }
9462   else
9463     {
9464       /* DWARF 3+ defines the default accessibility a different way.  The same
9465          rules apply now for DW_TAG_inheritance as for the members and it only
9466          depends on the container kind.  */
9467
9468       if (die->parent->tag == DW_TAG_class_type)
9469         return DW_ACCESS_private;
9470       else
9471         return DW_ACCESS_public;
9472     }
9473 }
9474
9475 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
9476    offset.  If the attribute was not found return 0, otherwise return
9477    1.  If it was found but could not properly be handled, set *OFFSET
9478    to 0.  */
9479
9480 static int
9481 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
9482                              LONGEST *offset)
9483 {
9484   struct attribute *attr;
9485
9486   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
9487   if (attr != NULL)
9488     {
9489       *offset = 0;
9490
9491       /* Note that we do not check for a section offset first here.
9492          This is because DW_AT_data_member_location is new in DWARF 4,
9493          so if we see it, we can assume that a constant form is really
9494          a constant and not a section offset.  */
9495       if (attr_form_is_constant (attr))
9496         *offset = dwarf2_get_attr_constant_value (attr, 0);
9497       else if (attr_form_is_section_offset (attr))
9498         dwarf2_complex_location_expr_complaint ();
9499       else if (attr_form_is_block (attr))
9500         *offset = decode_locdesc (DW_BLOCK (attr), cu);
9501       else
9502         dwarf2_complex_location_expr_complaint ();
9503
9504       return 1;
9505     }
9506
9507   return 0;
9508 }
9509
9510 /* Add an aggregate field to the field list.  */
9511
9512 static void
9513 dwarf2_add_field (struct field_info *fip, struct die_info *die,
9514                   struct dwarf2_cu *cu)
9515 {
9516   struct objfile *objfile = cu->objfile;
9517   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9518   struct nextfield *new_field;
9519   struct attribute *attr;
9520   struct field *fp;
9521   char *fieldname = "";
9522
9523   /* Allocate a new field list entry and link it in.  */
9524   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
9525   make_cleanup (xfree, new_field);
9526   memset (new_field, 0, sizeof (struct nextfield));
9527
9528   if (die->tag == DW_TAG_inheritance)
9529     {
9530       new_field->next = fip->baseclasses;
9531       fip->baseclasses = new_field;
9532     }
9533   else
9534     {
9535       new_field->next = fip->fields;
9536       fip->fields = new_field;
9537     }
9538   fip->nfields++;
9539
9540   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
9541   if (attr)
9542     new_field->accessibility = DW_UNSND (attr);
9543   else
9544     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
9545   if (new_field->accessibility != DW_ACCESS_public)
9546     fip->non_public_fields = 1;
9547
9548   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
9549   if (attr)
9550     new_field->virtuality = DW_UNSND (attr);
9551   else
9552     new_field->virtuality = DW_VIRTUALITY_none;
9553
9554   fp = &new_field->field;
9555
9556   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
9557     {
9558       LONGEST offset;
9559
9560       /* Data member other than a C++ static data member.  */
9561
9562       /* Get type of field.  */
9563       fp->type = die_type (die, cu);
9564
9565       SET_FIELD_BITPOS (*fp, 0);
9566
9567       /* Get bit size of field (zero if none).  */
9568       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
9569       if (attr)
9570         {
9571           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
9572         }
9573       else
9574         {
9575           FIELD_BITSIZE (*fp) = 0;
9576         }
9577
9578       /* Get bit offset of field.  */
9579       if (handle_data_member_location (die, cu, &offset))
9580         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
9581       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
9582       if (attr)
9583         {
9584           if (gdbarch_bits_big_endian (gdbarch))
9585             {
9586               /* For big endian bits, the DW_AT_bit_offset gives the
9587                  additional bit offset from the MSB of the containing
9588                  anonymous object to the MSB of the field.  We don't
9589                  have to do anything special since we don't need to
9590                  know the size of the anonymous object.  */
9591               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
9592             }
9593           else
9594             {
9595               /* For little endian bits, compute the bit offset to the
9596                  MSB of the anonymous object, subtract off the number of
9597                  bits from the MSB of the field to the MSB of the
9598                  object, and then subtract off the number of bits of
9599                  the field itself.  The result is the bit offset of
9600                  the LSB of the field.  */
9601               int anonymous_size;
9602               int bit_offset = DW_UNSND (attr);
9603
9604               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9605               if (attr)
9606                 {
9607                   /* The size of the anonymous object containing
9608                      the bit field is explicit, so use the
9609                      indicated size (in bytes).  */
9610                   anonymous_size = DW_UNSND (attr);
9611                 }
9612               else
9613                 {
9614                   /* The size of the anonymous object containing
9615                      the bit field must be inferred from the type
9616                      attribute of the data member containing the
9617                      bit field.  */
9618                   anonymous_size = TYPE_LENGTH (fp->type);
9619                 }
9620               SET_FIELD_BITPOS (*fp,
9621                                 (FIELD_BITPOS (*fp)
9622                                  + anonymous_size * bits_per_byte
9623                                  - bit_offset - FIELD_BITSIZE (*fp)));
9624             }
9625         }
9626
9627       /* Get name of field.  */
9628       fieldname = dwarf2_name (die, cu);
9629       if (fieldname == NULL)
9630         fieldname = "";
9631
9632       /* The name is already allocated along with this objfile, so we don't
9633          need to duplicate it for the type.  */
9634       fp->name = fieldname;
9635
9636       /* Change accessibility for artificial fields (e.g. virtual table
9637          pointer or virtual base class pointer) to private.  */
9638       if (dwarf2_attr (die, DW_AT_artificial, cu))
9639         {
9640           FIELD_ARTIFICIAL (*fp) = 1;
9641           new_field->accessibility = DW_ACCESS_private;
9642           fip->non_public_fields = 1;
9643         }
9644     }
9645   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
9646     {
9647       /* C++ static member.  */
9648
9649       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
9650          is a declaration, but all versions of G++ as of this writing
9651          (so through at least 3.2.1) incorrectly generate
9652          DW_TAG_variable tags.  */
9653
9654       const char *physname;
9655
9656       /* Get name of field.  */
9657       fieldname = dwarf2_name (die, cu);
9658       if (fieldname == NULL)
9659         return;
9660
9661       attr = dwarf2_attr (die, DW_AT_const_value, cu);
9662       if (attr
9663           /* Only create a symbol if this is an external value.
9664              new_symbol checks this and puts the value in the global symbol
9665              table, which we want.  If it is not external, new_symbol
9666              will try to put the value in cu->list_in_scope which is wrong.  */
9667           && dwarf2_flag_true_p (die, DW_AT_external, cu))
9668         {
9669           /* A static const member, not much different than an enum as far as
9670              we're concerned, except that we can support more types.  */
9671           new_symbol (die, NULL, cu);
9672         }
9673
9674       /* Get physical name.  */
9675       physname = dwarf2_physname (fieldname, die, cu);
9676
9677       /* The name is already allocated along with this objfile, so we don't
9678          need to duplicate it for the type.  */
9679       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
9680       FIELD_TYPE (*fp) = die_type (die, cu);
9681       FIELD_NAME (*fp) = fieldname;
9682     }
9683   else if (die->tag == DW_TAG_inheritance)
9684     {
9685       LONGEST offset;
9686
9687       /* C++ base class field.  */
9688       if (handle_data_member_location (die, cu, &offset))
9689         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
9690       FIELD_BITSIZE (*fp) = 0;
9691       FIELD_TYPE (*fp) = die_type (die, cu);
9692       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
9693       fip->nbaseclasses++;
9694     }
9695 }
9696
9697 /* Add a typedef defined in the scope of the FIP's class.  */
9698
9699 static void
9700 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
9701                     struct dwarf2_cu *cu)
9702 {
9703   struct objfile *objfile = cu->objfile;
9704   struct typedef_field_list *new_field;
9705   struct attribute *attr;
9706   struct typedef_field *fp;
9707   char *fieldname = "";
9708
9709   /* Allocate a new field list entry and link it in.  */
9710   new_field = xzalloc (sizeof (*new_field));
9711   make_cleanup (xfree, new_field);
9712
9713   gdb_assert (die->tag == DW_TAG_typedef);
9714
9715   fp = &new_field->field;
9716
9717   /* Get name of field.  */
9718   fp->name = dwarf2_name (die, cu);
9719   if (fp->name == NULL)
9720     return;
9721
9722   fp->type = read_type_die (die, cu);
9723
9724   new_field->next = fip->typedef_field_list;
9725   fip->typedef_field_list = new_field;
9726   fip->typedef_field_list_count++;
9727 }
9728
9729 /* Create the vector of fields, and attach it to the type.  */
9730
9731 static void
9732 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
9733                               struct dwarf2_cu *cu)
9734 {
9735   int nfields = fip->nfields;
9736
9737   /* Record the field count, allocate space for the array of fields,
9738      and create blank accessibility bitfields if necessary.  */
9739   TYPE_NFIELDS (type) = nfields;
9740   TYPE_FIELDS (type) = (struct field *)
9741     TYPE_ALLOC (type, sizeof (struct field) * nfields);
9742   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
9743
9744   if (fip->non_public_fields && cu->language != language_ada)
9745     {
9746       ALLOCATE_CPLUS_STRUCT_TYPE (type);
9747
9748       TYPE_FIELD_PRIVATE_BITS (type) =
9749         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
9750       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
9751
9752       TYPE_FIELD_PROTECTED_BITS (type) =
9753         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
9754       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
9755
9756       TYPE_FIELD_IGNORE_BITS (type) =
9757         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
9758       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
9759     }
9760
9761   /* If the type has baseclasses, allocate and clear a bit vector for
9762      TYPE_FIELD_VIRTUAL_BITS.  */
9763   if (fip->nbaseclasses && cu->language != language_ada)
9764     {
9765       int num_bytes = B_BYTES (fip->nbaseclasses);
9766       unsigned char *pointer;
9767
9768       ALLOCATE_CPLUS_STRUCT_TYPE (type);
9769       pointer = TYPE_ALLOC (type, num_bytes);
9770       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
9771       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
9772       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
9773     }
9774
9775   /* Copy the saved-up fields into the field vector.  Start from the head of
9776      the list, adding to the tail of the field array, so that they end up in
9777      the same order in the array in which they were added to the list.  */
9778   while (nfields-- > 0)
9779     {
9780       struct nextfield *fieldp;
9781
9782       if (fip->fields)
9783         {
9784           fieldp = fip->fields;
9785           fip->fields = fieldp->next;
9786         }
9787       else
9788         {
9789           fieldp = fip->baseclasses;
9790           fip->baseclasses = fieldp->next;
9791         }
9792
9793       TYPE_FIELD (type, nfields) = fieldp->field;
9794       switch (fieldp->accessibility)
9795         {
9796         case DW_ACCESS_private:
9797           if (cu->language != language_ada)
9798             SET_TYPE_FIELD_PRIVATE (type, nfields);
9799           break;
9800
9801         case DW_ACCESS_protected:
9802           if (cu->language != language_ada)
9803             SET_TYPE_FIELD_PROTECTED (type, nfields);
9804           break;
9805
9806         case DW_ACCESS_public:
9807           break;
9808
9809         default:
9810           /* Unknown accessibility.  Complain and treat it as public.  */
9811           {
9812             complaint (&symfile_complaints, _("unsupported accessibility %d"),
9813                        fieldp->accessibility);
9814           }
9815           break;
9816         }
9817       if (nfields < fip->nbaseclasses)
9818         {
9819           switch (fieldp->virtuality)
9820             {
9821             case DW_VIRTUALITY_virtual:
9822             case DW_VIRTUALITY_pure_virtual:
9823               if (cu->language == language_ada)
9824                 error (_("unexpected virtuality in component of Ada type"));
9825               SET_TYPE_FIELD_VIRTUAL (type, nfields);
9826               break;
9827             }
9828         }
9829     }
9830 }
9831
9832 /* Add a member function to the proper fieldlist.  */
9833
9834 static void
9835 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
9836                       struct type *type, struct dwarf2_cu *cu)
9837 {
9838   struct objfile *objfile = cu->objfile;
9839   struct attribute *attr;
9840   struct fnfieldlist *flp;
9841   int i;
9842   struct fn_field *fnp;
9843   char *fieldname;
9844   struct nextfnfield *new_fnfield;
9845   struct type *this_type;
9846   enum dwarf_access_attribute accessibility;
9847
9848   if (cu->language == language_ada)
9849     error (_("unexpected member function in Ada type"));
9850
9851   /* Get name of member function.  */
9852   fieldname = dwarf2_name (die, cu);
9853   if (fieldname == NULL)
9854     return;
9855
9856   /* Look up member function name in fieldlist.  */
9857   for (i = 0; i < fip->nfnfields; i++)
9858     {
9859       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
9860         break;
9861     }
9862
9863   /* Create new list element if necessary.  */
9864   if (i < fip->nfnfields)
9865     flp = &fip->fnfieldlists[i];
9866   else
9867     {
9868       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
9869         {
9870           fip->fnfieldlists = (struct fnfieldlist *)
9871             xrealloc (fip->fnfieldlists,
9872                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
9873                       * sizeof (struct fnfieldlist));
9874           if (fip->nfnfields == 0)
9875             make_cleanup (free_current_contents, &fip->fnfieldlists);
9876         }
9877       flp = &fip->fnfieldlists[fip->nfnfields];
9878       flp->name = fieldname;
9879       flp->length = 0;
9880       flp->head = NULL;
9881       i = fip->nfnfields++;
9882     }
9883
9884   /* Create a new member function field and chain it to the field list
9885      entry.  */
9886   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
9887   make_cleanup (xfree, new_fnfield);
9888   memset (new_fnfield, 0, sizeof (struct nextfnfield));
9889   new_fnfield->next = flp->head;
9890   flp->head = new_fnfield;
9891   flp->length++;
9892
9893   /* Fill in the member function field info.  */
9894   fnp = &new_fnfield->fnfield;
9895
9896   /* Delay processing of the physname until later.  */
9897   if (cu->language == language_cplus || cu->language == language_java)
9898     {
9899       add_to_method_list (type, i, flp->length - 1, fieldname,
9900                           die, cu);
9901     }
9902   else
9903     {
9904       const char *physname = dwarf2_physname (fieldname, die, cu);
9905       fnp->physname = physname ? physname : "";
9906     }
9907
9908   fnp->type = alloc_type (objfile);
9909   this_type = read_type_die (die, cu);
9910   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
9911     {
9912       int nparams = TYPE_NFIELDS (this_type);
9913
9914       /* TYPE is the domain of this method, and THIS_TYPE is the type
9915            of the method itself (TYPE_CODE_METHOD).  */
9916       smash_to_method_type (fnp->type, type,
9917                             TYPE_TARGET_TYPE (this_type),
9918                             TYPE_FIELDS (this_type),
9919                             TYPE_NFIELDS (this_type),
9920                             TYPE_VARARGS (this_type));
9921
9922       /* Handle static member functions.
9923          Dwarf2 has no clean way to discern C++ static and non-static
9924          member functions.  G++ helps GDB by marking the first
9925          parameter for non-static member functions (which is the this
9926          pointer) as artificial.  We obtain this information from
9927          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
9928       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
9929         fnp->voffset = VOFFSET_STATIC;
9930     }
9931   else
9932     complaint (&symfile_complaints, _("member function type missing for '%s'"),
9933                dwarf2_full_name (fieldname, die, cu));
9934
9935   /* Get fcontext from DW_AT_containing_type if present.  */
9936   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
9937     fnp->fcontext = die_containing_type (die, cu);
9938
9939   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
9940      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
9941
9942   /* Get accessibility.  */
9943   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
9944   if (attr)
9945     accessibility = DW_UNSND (attr);
9946   else
9947     accessibility = dwarf2_default_access_attribute (die, cu);
9948   switch (accessibility)
9949     {
9950     case DW_ACCESS_private:
9951       fnp->is_private = 1;
9952       break;
9953     case DW_ACCESS_protected:
9954       fnp->is_protected = 1;
9955       break;
9956     }
9957
9958   /* Check for artificial methods.  */
9959   attr = dwarf2_attr (die, DW_AT_artificial, cu);
9960   if (attr && DW_UNSND (attr) != 0)
9961     fnp->is_artificial = 1;
9962
9963   /* Get index in virtual function table if it is a virtual member
9964      function.  For older versions of GCC, this is an offset in the
9965      appropriate virtual table, as specified by DW_AT_containing_type.
9966      For everyone else, it is an expression to be evaluated relative
9967      to the object address.  */
9968
9969   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
9970   if (attr)
9971     {
9972       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
9973         {
9974           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
9975             {
9976               /* Old-style GCC.  */
9977               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
9978             }
9979           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
9980                    || (DW_BLOCK (attr)->size > 1
9981                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
9982                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
9983             {
9984               struct dwarf_block blk;
9985               int offset;
9986
9987               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
9988                         ? 1 : 2);
9989               blk.size = DW_BLOCK (attr)->size - offset;
9990               blk.data = DW_BLOCK (attr)->data + offset;
9991               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
9992               if ((fnp->voffset % cu->header.addr_size) != 0)
9993                 dwarf2_complex_location_expr_complaint ();
9994               else
9995                 fnp->voffset /= cu->header.addr_size;
9996               fnp->voffset += 2;
9997             }
9998           else
9999             dwarf2_complex_location_expr_complaint ();
10000
10001           if (!fnp->fcontext)
10002             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
10003         }
10004       else if (attr_form_is_section_offset (attr))
10005         {
10006           dwarf2_complex_location_expr_complaint ();
10007         }
10008       else
10009         {
10010           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
10011                                                  fieldname);
10012         }
10013     }
10014   else
10015     {
10016       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10017       if (attr && DW_UNSND (attr))
10018         {
10019           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
10020           complaint (&symfile_complaints,
10021                      _("Member function \"%s\" (offset %d) is virtual "
10022                        "but the vtable offset is not specified"),
10023                      fieldname, die->offset.sect_off);
10024           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10025           TYPE_CPLUS_DYNAMIC (type) = 1;
10026         }
10027     }
10028 }
10029
10030 /* Create the vector of member function fields, and attach it to the type.  */
10031
10032 static void
10033 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
10034                                  struct dwarf2_cu *cu)
10035 {
10036   struct fnfieldlist *flp;
10037   int i;
10038
10039   if (cu->language == language_ada)
10040     error (_("unexpected member functions in Ada type"));
10041
10042   ALLOCATE_CPLUS_STRUCT_TYPE (type);
10043   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
10044     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
10045
10046   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
10047     {
10048       struct nextfnfield *nfp = flp->head;
10049       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
10050       int k;
10051
10052       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
10053       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
10054       fn_flp->fn_fields = (struct fn_field *)
10055         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
10056       for (k = flp->length; (k--, nfp); nfp = nfp->next)
10057         fn_flp->fn_fields[k] = nfp->fnfield;
10058     }
10059
10060   TYPE_NFN_FIELDS (type) = fip->nfnfields;
10061 }
10062
10063 /* Returns non-zero if NAME is the name of a vtable member in CU's
10064    language, zero otherwise.  */
10065 static int
10066 is_vtable_name (const char *name, struct dwarf2_cu *cu)
10067 {
10068   static const char vptr[] = "_vptr";
10069   static const char vtable[] = "vtable";
10070
10071   /* Look for the C++ and Java forms of the vtable.  */
10072   if ((cu->language == language_java
10073        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
10074        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
10075        && is_cplus_marker (name[sizeof (vptr) - 1])))
10076     return 1;
10077
10078   return 0;
10079 }
10080
10081 /* GCC outputs unnamed structures that are really pointers to member
10082    functions, with the ABI-specified layout.  If TYPE describes
10083    such a structure, smash it into a member function type.
10084
10085    GCC shouldn't do this; it should just output pointer to member DIEs.
10086    This is GCC PR debug/28767.  */
10087
10088 static void
10089 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
10090 {
10091   struct type *pfn_type, *domain_type, *new_type;
10092
10093   /* Check for a structure with no name and two children.  */
10094   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
10095     return;
10096
10097   /* Check for __pfn and __delta members.  */
10098   if (TYPE_FIELD_NAME (type, 0) == NULL
10099       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
10100       || TYPE_FIELD_NAME (type, 1) == NULL
10101       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
10102     return;
10103
10104   /* Find the type of the method.  */
10105   pfn_type = TYPE_FIELD_TYPE (type, 0);
10106   if (pfn_type == NULL
10107       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
10108       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
10109     return;
10110
10111   /* Look for the "this" argument.  */
10112   pfn_type = TYPE_TARGET_TYPE (pfn_type);
10113   if (TYPE_NFIELDS (pfn_type) == 0
10114       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
10115       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
10116     return;
10117
10118   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
10119   new_type = alloc_type (objfile);
10120   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
10121                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
10122                         TYPE_VARARGS (pfn_type));
10123   smash_to_methodptr_type (type, new_type);
10124 }
10125
10126 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
10127    (icc).  */
10128
10129 static int
10130 producer_is_icc (struct dwarf2_cu *cu)
10131 {
10132   if (!cu->checked_producer)
10133     check_producer (cu);
10134
10135   return cu->producer_is_icc;
10136 }
10137
10138 /* Called when we find the DIE that starts a structure or union scope
10139    (definition) to create a type for the structure or union.  Fill in
10140    the type's name and general properties; the members will not be
10141    processed until process_structure_type.
10142
10143    NOTE: we need to call these functions regardless of whether or not the
10144    DIE has a DW_AT_name attribute, since it might be an anonymous
10145    structure or union.  This gets the type entered into our set of
10146    user defined types.
10147
10148    However, if the structure is incomplete (an opaque struct/union)
10149    then suppress creating a symbol table entry for it since gdb only
10150    wants to find the one with the complete definition.  Note that if
10151    it is complete, we just call new_symbol, which does it's own
10152    checking about whether the struct/union is anonymous or not (and
10153    suppresses creating a symbol table entry itself).  */
10154
10155 static struct type *
10156 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
10157 {
10158   struct objfile *objfile = cu->objfile;
10159   struct type *type;
10160   struct attribute *attr;
10161   char *name;
10162
10163   /* If the definition of this type lives in .debug_types, read that type.
10164      Don't follow DW_AT_specification though, that will take us back up
10165      the chain and we want to go down.  */
10166   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
10167   if (attr)
10168     {
10169       struct dwarf2_cu *type_cu = cu;
10170       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
10171
10172       /* We could just recurse on read_structure_type, but we need to call
10173          get_die_type to ensure only one type for this DIE is created.
10174          This is important, for example, because for c++ classes we need
10175          TYPE_NAME set which is only done by new_symbol.  Blech.  */
10176       type = read_type_die (type_die, type_cu);
10177
10178       /* TYPE_CU may not be the same as CU.
10179          Ensure TYPE is recorded in CU's type_hash table.  */
10180       return set_die_type (die, type, cu);
10181     }
10182
10183   type = alloc_type (objfile);
10184   INIT_CPLUS_SPECIFIC (type);
10185
10186   name = dwarf2_name (die, cu);
10187   if (name != NULL)
10188     {
10189       if (cu->language == language_cplus
10190           || cu->language == language_java)
10191         {
10192           char *full_name = (char *) dwarf2_full_name (name, die, cu);
10193
10194           /* dwarf2_full_name might have already finished building the DIE's
10195              type.  If so, there is no need to continue.  */
10196           if (get_die_type (die, cu) != NULL)
10197             return get_die_type (die, cu);
10198
10199           TYPE_TAG_NAME (type) = full_name;
10200           if (die->tag == DW_TAG_structure_type
10201               || die->tag == DW_TAG_class_type)
10202             TYPE_NAME (type) = TYPE_TAG_NAME (type);
10203         }
10204       else
10205         {
10206           /* The name is already allocated along with this objfile, so
10207              we don't need to duplicate it for the type.  */
10208           TYPE_TAG_NAME (type) = (char *) name;
10209           if (die->tag == DW_TAG_class_type)
10210             TYPE_NAME (type) = TYPE_TAG_NAME (type);
10211         }
10212     }
10213
10214   if (die->tag == DW_TAG_structure_type)
10215     {
10216       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10217     }
10218   else if (die->tag == DW_TAG_union_type)
10219     {
10220       TYPE_CODE (type) = TYPE_CODE_UNION;
10221     }
10222   else
10223     {
10224       TYPE_CODE (type) = TYPE_CODE_CLASS;
10225     }
10226
10227   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
10228     TYPE_DECLARED_CLASS (type) = 1;
10229
10230   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10231   if (attr)
10232     {
10233       TYPE_LENGTH (type) = DW_UNSND (attr);
10234     }
10235   else
10236     {
10237       TYPE_LENGTH (type) = 0;
10238     }
10239
10240   if (producer_is_icc (cu))
10241     {
10242       /* ICC does not output the required DW_AT_declaration
10243          on incomplete types, but gives them a size of zero.  */
10244     }
10245   else
10246     TYPE_STUB_SUPPORTED (type) = 1;
10247
10248   if (die_is_declaration (die, cu))
10249     TYPE_STUB (type) = 1;
10250   else if (attr == NULL && die->child == NULL
10251            && producer_is_realview (cu->producer))
10252     /* RealView does not output the required DW_AT_declaration
10253        on incomplete types.  */
10254     TYPE_STUB (type) = 1;
10255
10256   /* We need to add the type field to the die immediately so we don't
10257      infinitely recurse when dealing with pointers to the structure
10258      type within the structure itself.  */
10259   set_die_type (die, type, cu);
10260
10261   /* set_die_type should be already done.  */
10262   set_descriptive_type (type, die, cu);
10263
10264   return type;
10265 }
10266
10267 /* Finish creating a structure or union type, including filling in
10268    its members and creating a symbol for it.  */
10269
10270 static void
10271 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
10272 {
10273   struct objfile *objfile = cu->objfile;
10274   struct die_info *child_die = die->child;
10275   struct type *type;
10276
10277   type = get_die_type (die, cu);
10278   if (type == NULL)
10279     type = read_structure_type (die, cu);
10280
10281   if (die->child != NULL && ! die_is_declaration (die, cu))
10282     {
10283       struct field_info fi;
10284       struct die_info *child_die;
10285       VEC (symbolp) *template_args = NULL;
10286       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
10287
10288       memset (&fi, 0, sizeof (struct field_info));
10289
10290       child_die = die->child;
10291
10292       while (child_die && child_die->tag)
10293         {
10294           if (child_die->tag == DW_TAG_member
10295               || child_die->tag == DW_TAG_variable)
10296             {
10297               /* NOTE: carlton/2002-11-05: A C++ static data member
10298                  should be a DW_TAG_member that is a declaration, but
10299                  all versions of G++ as of this writing (so through at
10300                  least 3.2.1) incorrectly generate DW_TAG_variable
10301                  tags for them instead.  */
10302               dwarf2_add_field (&fi, child_die, cu);
10303             }
10304           else if (child_die->tag == DW_TAG_subprogram)
10305             {
10306               /* C++ member function.  */
10307               dwarf2_add_member_fn (&fi, child_die, type, cu);
10308             }
10309           else if (child_die->tag == DW_TAG_inheritance)
10310             {
10311               /* C++ base class field.  */
10312               dwarf2_add_field (&fi, child_die, cu);
10313             }
10314           else if (child_die->tag == DW_TAG_typedef)
10315             dwarf2_add_typedef (&fi, child_die, cu);
10316           else if (child_die->tag == DW_TAG_template_type_param
10317                    || child_die->tag == DW_TAG_template_value_param)
10318             {
10319               struct symbol *arg = new_symbol (child_die, NULL, cu);
10320
10321               if (arg != NULL)
10322                 VEC_safe_push (symbolp, template_args, arg);
10323             }
10324
10325           child_die = sibling_die (child_die);
10326         }
10327
10328       /* Attach template arguments to type.  */
10329       if (! VEC_empty (symbolp, template_args))
10330         {
10331           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10332           TYPE_N_TEMPLATE_ARGUMENTS (type)
10333             = VEC_length (symbolp, template_args);
10334           TYPE_TEMPLATE_ARGUMENTS (type)
10335             = obstack_alloc (&objfile->objfile_obstack,
10336                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
10337                               * sizeof (struct symbol *)));
10338           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
10339                   VEC_address (symbolp, template_args),
10340                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
10341                    * sizeof (struct symbol *)));
10342           VEC_free (symbolp, template_args);
10343         }
10344
10345       /* Attach fields and member functions to the type.  */
10346       if (fi.nfields)
10347         dwarf2_attach_fields_to_type (&fi, type, cu);
10348       if (fi.nfnfields)
10349         {
10350           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
10351
10352           /* Get the type which refers to the base class (possibly this
10353              class itself) which contains the vtable pointer for the current
10354              class from the DW_AT_containing_type attribute.  This use of
10355              DW_AT_containing_type is a GNU extension.  */
10356
10357           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10358             {
10359               struct type *t = die_containing_type (die, cu);
10360
10361               TYPE_VPTR_BASETYPE (type) = t;
10362               if (type == t)
10363                 {
10364                   int i;
10365
10366                   /* Our own class provides vtbl ptr.  */
10367                   for (i = TYPE_NFIELDS (t) - 1;
10368                        i >= TYPE_N_BASECLASSES (t);
10369                        --i)
10370                     {
10371                       const char *fieldname = TYPE_FIELD_NAME (t, i);
10372
10373                       if (is_vtable_name (fieldname, cu))
10374                         {
10375                           TYPE_VPTR_FIELDNO (type) = i;
10376                           break;
10377                         }
10378                     }
10379
10380                   /* Complain if virtual function table field not found.  */
10381                   if (i < TYPE_N_BASECLASSES (t))
10382                     complaint (&symfile_complaints,
10383                                _("virtual function table pointer "
10384                                  "not found when defining class '%s'"),
10385                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
10386                                "");
10387                 }
10388               else
10389                 {
10390                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
10391                 }
10392             }
10393           else if (cu->producer
10394                    && strncmp (cu->producer,
10395                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
10396             {
10397               /* The IBM XLC compiler does not provide direct indication
10398                  of the containing type, but the vtable pointer is
10399                  always named __vfp.  */
10400
10401               int i;
10402
10403               for (i = TYPE_NFIELDS (type) - 1;
10404                    i >= TYPE_N_BASECLASSES (type);
10405                    --i)
10406                 {
10407                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
10408                     {
10409                       TYPE_VPTR_FIELDNO (type) = i;
10410                       TYPE_VPTR_BASETYPE (type) = type;
10411                       break;
10412                     }
10413                 }
10414             }
10415         }
10416
10417       /* Copy fi.typedef_field_list linked list elements content into the
10418          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
10419       if (fi.typedef_field_list)
10420         {
10421           int i = fi.typedef_field_list_count;
10422
10423           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10424           TYPE_TYPEDEF_FIELD_ARRAY (type)
10425             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
10426           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
10427
10428           /* Reverse the list order to keep the debug info elements order.  */
10429           while (--i >= 0)
10430             {
10431               struct typedef_field *dest, *src;
10432
10433               dest = &TYPE_TYPEDEF_FIELD (type, i);
10434               src = &fi.typedef_field_list->field;
10435               fi.typedef_field_list = fi.typedef_field_list->next;
10436               *dest = *src;
10437             }
10438         }
10439
10440       do_cleanups (back_to);
10441
10442       if (HAVE_CPLUS_STRUCT (type))
10443         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
10444     }
10445
10446   quirk_gcc_member_function_pointer (type, objfile);
10447
10448   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
10449      snapshots) has been known to create a die giving a declaration
10450      for a class that has, as a child, a die giving a definition for a
10451      nested class.  So we have to process our children even if the
10452      current die is a declaration.  Normally, of course, a declaration
10453      won't have any children at all.  */
10454
10455   while (child_die != NULL && child_die->tag)
10456     {
10457       if (child_die->tag == DW_TAG_member
10458           || child_die->tag == DW_TAG_variable
10459           || child_die->tag == DW_TAG_inheritance
10460           || child_die->tag == DW_TAG_template_value_param
10461           || child_die->tag == DW_TAG_template_type_param)
10462         {
10463           /* Do nothing.  */
10464         }
10465       else
10466         process_die (child_die, cu);
10467
10468       child_die = sibling_die (child_die);
10469     }
10470
10471   /* Do not consider external references.  According to the DWARF standard,
10472      these DIEs are identified by the fact that they have no byte_size
10473      attribute, and a declaration attribute.  */
10474   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
10475       || !die_is_declaration (die, cu))
10476     new_symbol (die, type, cu);
10477 }
10478
10479 /* Given a DW_AT_enumeration_type die, set its type.  We do not
10480    complete the type's fields yet, or create any symbols.  */
10481
10482 static struct type *
10483 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
10484 {
10485   struct objfile *objfile = cu->objfile;
10486   struct type *type;
10487   struct attribute *attr;
10488   const char *name;
10489
10490   /* If the definition of this type lives in .debug_types, read that type.
10491      Don't follow DW_AT_specification though, that will take us back up
10492      the chain and we want to go down.  */
10493   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
10494   if (attr)
10495     {
10496       struct dwarf2_cu *type_cu = cu;
10497       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
10498
10499       type = read_type_die (type_die, type_cu);
10500
10501       /* TYPE_CU may not be the same as CU.
10502          Ensure TYPE is recorded in CU's type_hash table.  */
10503       return set_die_type (die, type, cu);
10504     }
10505
10506   type = alloc_type (objfile);
10507
10508   TYPE_CODE (type) = TYPE_CODE_ENUM;
10509   name = dwarf2_full_name (NULL, die, cu);
10510   if (name != NULL)
10511     TYPE_TAG_NAME (type) = (char *) name;
10512
10513   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10514   if (attr)
10515     {
10516       TYPE_LENGTH (type) = DW_UNSND (attr);
10517     }
10518   else
10519     {
10520       TYPE_LENGTH (type) = 0;
10521     }
10522
10523   /* The enumeration DIE can be incomplete.  In Ada, any type can be
10524      declared as private in the package spec, and then defined only
10525      inside the package body.  Such types are known as Taft Amendment
10526      Types.  When another package uses such a type, an incomplete DIE
10527      may be generated by the compiler.  */
10528   if (die_is_declaration (die, cu))
10529     TYPE_STUB (type) = 1;
10530
10531   return set_die_type (die, type, cu);
10532 }
10533
10534 /* Given a pointer to a die which begins an enumeration, process all
10535    the dies that define the members of the enumeration, and create the
10536    symbol for the enumeration type.
10537
10538    NOTE: We reverse the order of the element list.  */
10539
10540 static void
10541 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
10542 {
10543   struct type *this_type;
10544
10545   this_type = get_die_type (die, cu);
10546   if (this_type == NULL)
10547     this_type = read_enumeration_type (die, cu);
10548
10549   if (die->child != NULL)
10550     {
10551       struct die_info *child_die;
10552       struct symbol *sym;
10553       struct field *fields = NULL;
10554       int num_fields = 0;
10555       int unsigned_enum = 1;
10556       char *name;
10557       int flag_enum = 1;
10558       ULONGEST mask = 0;
10559
10560       child_die = die->child;
10561       while (child_die && child_die->tag)
10562         {
10563           if (child_die->tag != DW_TAG_enumerator)
10564             {
10565               process_die (child_die, cu);
10566             }
10567           else
10568             {
10569               name = dwarf2_name (child_die, cu);
10570               if (name)
10571                 {
10572                   sym = new_symbol (child_die, this_type, cu);
10573                   if (SYMBOL_VALUE (sym) < 0)
10574                     {
10575                       unsigned_enum = 0;
10576                       flag_enum = 0;
10577                     }
10578                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
10579                     flag_enum = 0;
10580                   else
10581                     mask |= SYMBOL_VALUE (sym);
10582
10583                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
10584                     {
10585                       fields = (struct field *)
10586                         xrealloc (fields,
10587                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
10588                                   * sizeof (struct field));
10589                     }
10590
10591                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
10592                   FIELD_TYPE (fields[num_fields]) = NULL;
10593                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
10594                   FIELD_BITSIZE (fields[num_fields]) = 0;
10595
10596                   num_fields++;
10597                 }
10598             }
10599
10600           child_die = sibling_die (child_die);
10601         }
10602
10603       if (num_fields)
10604         {
10605           TYPE_NFIELDS (this_type) = num_fields;
10606           TYPE_FIELDS (this_type) = (struct field *)
10607             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
10608           memcpy (TYPE_FIELDS (this_type), fields,
10609                   sizeof (struct field) * num_fields);
10610           xfree (fields);
10611         }
10612       if (unsigned_enum)
10613         TYPE_UNSIGNED (this_type) = 1;
10614       if (flag_enum)
10615         TYPE_FLAG_ENUM (this_type) = 1;
10616     }
10617
10618   /* If we are reading an enum from a .debug_types unit, and the enum
10619      is a declaration, and the enum is not the signatured type in the
10620      unit, then we do not want to add a symbol for it.  Adding a
10621      symbol would in some cases obscure the true definition of the
10622      enum, giving users an incomplete type when the definition is
10623      actually available.  Note that we do not want to do this for all
10624      enums which are just declarations, because C++0x allows forward
10625      enum declarations.  */
10626   if (cu->per_cu->is_debug_types
10627       && die_is_declaration (die, cu))
10628     {
10629       struct signatured_type *sig_type;
10630
10631       sig_type
10632         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
10633                                             cu->per_cu->info_or_types_section,
10634                                             cu->per_cu->offset);
10635       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
10636       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
10637         return;
10638     }
10639
10640   new_symbol (die, this_type, cu);
10641 }
10642
10643 /* Extract all information from a DW_TAG_array_type DIE and put it in
10644    the DIE's type field.  For now, this only handles one dimensional
10645    arrays.  */
10646
10647 static struct type *
10648 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
10649 {
10650   struct objfile *objfile = cu->objfile;
10651   struct die_info *child_die;
10652   struct type *type;
10653   struct type *element_type, *range_type, *index_type;
10654   struct type **range_types = NULL;
10655   struct attribute *attr;
10656   int ndim = 0;
10657   struct cleanup *back_to;
10658   char *name;
10659
10660   element_type = die_type (die, cu);
10661
10662   /* The die_type call above may have already set the type for this DIE.  */
10663   type = get_die_type (die, cu);
10664   if (type)
10665     return type;
10666
10667   /* Irix 6.2 native cc creates array types without children for
10668      arrays with unspecified length.  */
10669   if (die->child == NULL)
10670     {
10671       index_type = objfile_type (objfile)->builtin_int;
10672       range_type = create_range_type (NULL, index_type, 0, -1);
10673       type = create_array_type (NULL, element_type, range_type);
10674       return set_die_type (die, type, cu);
10675     }
10676
10677   back_to = make_cleanup (null_cleanup, NULL);
10678   child_die = die->child;
10679   while (child_die && child_die->tag)
10680     {
10681       if (child_die->tag == DW_TAG_subrange_type)
10682         {
10683           struct type *child_type = read_type_die (child_die, cu);
10684
10685           if (child_type != NULL)
10686             {
10687               /* The range type was succesfully read.  Save it for the
10688                  array type creation.  */
10689               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
10690                 {
10691                   range_types = (struct type **)
10692                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
10693                               * sizeof (struct type *));
10694                   if (ndim == 0)
10695                     make_cleanup (free_current_contents, &range_types);
10696                 }
10697               range_types[ndim++] = child_type;
10698             }
10699         }
10700       child_die = sibling_die (child_die);
10701     }
10702
10703   /* Dwarf2 dimensions are output from left to right, create the
10704      necessary array types in backwards order.  */
10705
10706   type = element_type;
10707
10708   if (read_array_order (die, cu) == DW_ORD_col_major)
10709     {
10710       int i = 0;
10711
10712       while (i < ndim)
10713         type = create_array_type (NULL, type, range_types[i++]);
10714     }
10715   else
10716     {
10717       while (ndim-- > 0)
10718         type = create_array_type (NULL, type, range_types[ndim]);
10719     }
10720
10721   /* Understand Dwarf2 support for vector types (like they occur on
10722      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
10723      array type.  This is not part of the Dwarf2/3 standard yet, but a
10724      custom vendor extension.  The main difference between a regular
10725      array and the vector variant is that vectors are passed by value
10726      to functions.  */
10727   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
10728   if (attr)
10729     make_vector_type (type);
10730
10731   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
10732      implementation may choose to implement triple vectors using this
10733      attribute.  */
10734   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10735   if (attr)
10736     {
10737       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
10738         TYPE_LENGTH (type) = DW_UNSND (attr);
10739       else
10740         complaint (&symfile_complaints,
10741                    _("DW_AT_byte_size for array type smaller "
10742                      "than the total size of elements"));
10743     }
10744
10745   name = dwarf2_name (die, cu);
10746   if (name)
10747     TYPE_NAME (type) = name;
10748
10749   /* Install the type in the die.  */
10750   set_die_type (die, type, cu);
10751
10752   /* set_die_type should be already done.  */
10753   set_descriptive_type (type, die, cu);
10754
10755   do_cleanups (back_to);
10756
10757   return type;
10758 }
10759
10760 static enum dwarf_array_dim_ordering
10761 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
10762 {
10763   struct attribute *attr;
10764
10765   attr = dwarf2_attr (die, DW_AT_ordering, cu);
10766
10767   if (attr) return DW_SND (attr);
10768
10769   /* GNU F77 is a special case, as at 08/2004 array type info is the
10770      opposite order to the dwarf2 specification, but data is still
10771      laid out as per normal fortran.
10772
10773      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
10774      version checking.  */
10775
10776   if (cu->language == language_fortran
10777       && cu->producer && strstr (cu->producer, "GNU F77"))
10778     {
10779       return DW_ORD_row_major;
10780     }
10781
10782   switch (cu->language_defn->la_array_ordering)
10783     {
10784     case array_column_major:
10785       return DW_ORD_col_major;
10786     case array_row_major:
10787     default:
10788       return DW_ORD_row_major;
10789     };
10790 }
10791
10792 /* Extract all information from a DW_TAG_set_type DIE and put it in
10793    the DIE's type field.  */
10794
10795 static struct type *
10796 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
10797 {
10798   struct type *domain_type, *set_type;
10799   struct attribute *attr;
10800
10801   domain_type = die_type (die, cu);
10802
10803   /* The die_type call above may have already set the type for this DIE.  */
10804   set_type = get_die_type (die, cu);
10805   if (set_type)
10806     return set_type;
10807
10808   set_type = create_set_type (NULL, domain_type);
10809
10810   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10811   if (attr)
10812     TYPE_LENGTH (set_type) = DW_UNSND (attr);
10813
10814   return set_die_type (die, set_type, cu);
10815 }
10816
10817 /* First cut: install each common block member as a global variable.  */
10818
10819 static void
10820 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
10821 {
10822   struct die_info *child_die;
10823   struct attribute *attr;
10824   struct symbol *sym;
10825   CORE_ADDR base = (CORE_ADDR) 0;
10826
10827   attr = dwarf2_attr (die, DW_AT_location, cu);
10828   if (attr)
10829     {
10830       /* Support the .debug_loc offsets.  */
10831       if (attr_form_is_block (attr))
10832         {
10833           base = decode_locdesc (DW_BLOCK (attr), cu);
10834         }
10835       else if (attr_form_is_section_offset (attr))
10836         {
10837           dwarf2_complex_location_expr_complaint ();
10838         }
10839       else
10840         {
10841           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
10842                                                  "common block member");
10843         }
10844     }
10845   if (die->child != NULL)
10846     {
10847       child_die = die->child;
10848       while (child_die && child_die->tag)
10849         {
10850           LONGEST offset;
10851
10852           sym = new_symbol (child_die, NULL, cu);
10853           if (sym != NULL
10854               && handle_data_member_location (child_die, cu, &offset))
10855             {
10856               SYMBOL_VALUE_ADDRESS (sym) = base + offset;
10857               add_symbol_to_list (sym, &global_symbols);
10858             }
10859           child_die = sibling_die (child_die);
10860         }
10861     }
10862 }
10863
10864 /* Create a type for a C++ namespace.  */
10865
10866 static struct type *
10867 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
10868 {
10869   struct objfile *objfile = cu->objfile;
10870   const char *previous_prefix, *name;
10871   int is_anonymous;
10872   struct type *type;
10873
10874   /* For extensions, reuse the type of the original namespace.  */
10875   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
10876     {
10877       struct die_info *ext_die;
10878       struct dwarf2_cu *ext_cu = cu;
10879
10880       ext_die = dwarf2_extension (die, &ext_cu);
10881       type = read_type_die (ext_die, ext_cu);
10882
10883       /* EXT_CU may not be the same as CU.
10884          Ensure TYPE is recorded in CU's type_hash table.  */
10885       return set_die_type (die, type, cu);
10886     }
10887
10888   name = namespace_name (die, &is_anonymous, cu);
10889
10890   /* Now build the name of the current namespace.  */
10891
10892   previous_prefix = determine_prefix (die, cu);
10893   if (previous_prefix[0] != '\0')
10894     name = typename_concat (&objfile->objfile_obstack,
10895                             previous_prefix, name, 0, cu);
10896
10897   /* Create the type.  */
10898   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
10899                     objfile);
10900   TYPE_NAME (type) = (char *) name;
10901   TYPE_TAG_NAME (type) = TYPE_NAME (type);
10902
10903   return set_die_type (die, type, cu);
10904 }
10905
10906 /* Read a C++ namespace.  */
10907
10908 static void
10909 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
10910 {
10911   struct objfile *objfile = cu->objfile;
10912   int is_anonymous;
10913
10914   /* Add a symbol associated to this if we haven't seen the namespace
10915      before.  Also, add a using directive if it's an anonymous
10916      namespace.  */
10917
10918   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
10919     {
10920       struct type *type;
10921
10922       type = read_type_die (die, cu);
10923       new_symbol (die, type, cu);
10924
10925       namespace_name (die, &is_anonymous, cu);
10926       if (is_anonymous)
10927         {
10928           const char *previous_prefix = determine_prefix (die, cu);
10929
10930           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
10931                                   NULL, NULL, &objfile->objfile_obstack);
10932         }
10933     }
10934
10935   if (die->child != NULL)
10936     {
10937       struct die_info *child_die = die->child;
10938
10939       while (child_die && child_die->tag)
10940         {
10941           process_die (child_die, cu);
10942           child_die = sibling_die (child_die);
10943         }
10944     }
10945 }
10946
10947 /* Read a Fortran module as type.  This DIE can be only a declaration used for
10948    imported module.  Still we need that type as local Fortran "use ... only"
10949    declaration imports depend on the created type in determine_prefix.  */
10950
10951 static struct type *
10952 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
10953 {
10954   struct objfile *objfile = cu->objfile;
10955   char *module_name;
10956   struct type *type;
10957
10958   module_name = dwarf2_name (die, cu);
10959   if (!module_name)
10960     complaint (&symfile_complaints,
10961                _("DW_TAG_module has no name, offset 0x%x"),
10962                die->offset.sect_off);
10963   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
10964
10965   /* determine_prefix uses TYPE_TAG_NAME.  */
10966   TYPE_TAG_NAME (type) = TYPE_NAME (type);
10967
10968   return set_die_type (die, type, cu);
10969 }
10970
10971 /* Read a Fortran module.  */
10972
10973 static void
10974 read_module (struct die_info *die, struct dwarf2_cu *cu)
10975 {
10976   struct die_info *child_die = die->child;
10977
10978   while (child_die && child_die->tag)
10979     {
10980       process_die (child_die, cu);
10981       child_die = sibling_die (child_die);
10982     }
10983 }
10984
10985 /* Return the name of the namespace represented by DIE.  Set
10986    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
10987    namespace.  */
10988
10989 static const char *
10990 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
10991 {
10992   struct die_info *current_die;
10993   const char *name = NULL;
10994
10995   /* Loop through the extensions until we find a name.  */
10996
10997   for (current_die = die;
10998        current_die != NULL;
10999        current_die = dwarf2_extension (die, &cu))
11000     {
11001       name = dwarf2_name (current_die, cu);
11002       if (name != NULL)
11003         break;
11004     }
11005
11006   /* Is it an anonymous namespace?  */
11007
11008   *is_anonymous = (name == NULL);
11009   if (*is_anonymous)
11010     name = CP_ANONYMOUS_NAMESPACE_STR;
11011
11012   return name;
11013 }
11014
11015 /* Extract all information from a DW_TAG_pointer_type DIE and add to
11016    the user defined type vector.  */
11017
11018 static struct type *
11019 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
11020 {
11021   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
11022   struct comp_unit_head *cu_header = &cu->header;
11023   struct type *type;
11024   struct attribute *attr_byte_size;
11025   struct attribute *attr_address_class;
11026   int byte_size, addr_class;
11027   struct type *target_type;
11028
11029   target_type = die_type (die, cu);
11030
11031   /* The die_type call above may have already set the type for this DIE.  */
11032   type = get_die_type (die, cu);
11033   if (type)
11034     return type;
11035
11036   type = lookup_pointer_type (target_type);
11037
11038   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
11039   if (attr_byte_size)
11040     byte_size = DW_UNSND (attr_byte_size);
11041   else
11042     byte_size = cu_header->addr_size;
11043
11044   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
11045   if (attr_address_class)
11046     addr_class = DW_UNSND (attr_address_class);
11047   else
11048     addr_class = DW_ADDR_none;
11049
11050   /* If the pointer size or address class is different than the
11051      default, create a type variant marked as such and set the
11052      length accordingly.  */
11053   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
11054     {
11055       if (gdbarch_address_class_type_flags_p (gdbarch))
11056         {
11057           int type_flags;
11058
11059           type_flags = gdbarch_address_class_type_flags
11060                          (gdbarch, byte_size, addr_class);
11061           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
11062                       == 0);
11063           type = make_type_with_address_space (type, type_flags);
11064         }
11065       else if (TYPE_LENGTH (type) != byte_size)
11066         {
11067           complaint (&symfile_complaints,
11068                      _("invalid pointer size %d"), byte_size);
11069         }
11070       else
11071         {
11072           /* Should we also complain about unhandled address classes?  */
11073         }
11074     }
11075
11076   TYPE_LENGTH (type) = byte_size;
11077   return set_die_type (die, type, cu);
11078 }
11079
11080 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
11081    the user defined type vector.  */
11082
11083 static struct type *
11084 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
11085 {
11086   struct type *type;
11087   struct type *to_type;
11088   struct type *domain;
11089
11090   to_type = die_type (die, cu);
11091   domain = die_containing_type (die, cu);
11092
11093   /* The calls above may have already set the type for this DIE.  */
11094   type = get_die_type (die, cu);
11095   if (type)
11096     return type;
11097
11098   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
11099     type = lookup_methodptr_type (to_type);
11100   else
11101     type = lookup_memberptr_type (to_type, domain);
11102
11103   return set_die_type (die, type, cu);
11104 }
11105
11106 /* Extract all information from a DW_TAG_reference_type DIE and add to
11107    the user defined type vector.  */
11108
11109 static struct type *
11110 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
11111 {
11112   struct comp_unit_head *cu_header = &cu->header;
11113   struct type *type, *target_type;
11114   struct attribute *attr;
11115
11116   target_type = die_type (die, cu);
11117
11118   /* The die_type call above may have already set the type for this DIE.  */
11119   type = get_die_type (die, cu);
11120   if (type)
11121     return type;
11122
11123   type = lookup_reference_type (target_type);
11124   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11125   if (attr)
11126     {
11127       TYPE_LENGTH (type) = DW_UNSND (attr);
11128     }
11129   else
11130     {
11131       TYPE_LENGTH (type) = cu_header->addr_size;
11132     }
11133   return set_die_type (die, type, cu);
11134 }
11135
11136 static struct type *
11137 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
11138 {
11139   struct type *base_type, *cv_type;
11140
11141   base_type = die_type (die, cu);
11142
11143   /* The die_type call above may have already set the type for this DIE.  */
11144   cv_type = get_die_type (die, cu);
11145   if (cv_type)
11146     return cv_type;
11147
11148   /* In case the const qualifier is applied to an array type, the element type
11149      is so qualified, not the array type (section 6.7.3 of C99).  */
11150   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
11151     {
11152       struct type *el_type, *inner_array;
11153
11154       base_type = copy_type (base_type);
11155       inner_array = base_type;
11156
11157       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
11158         {
11159           TYPE_TARGET_TYPE (inner_array) =
11160             copy_type (TYPE_TARGET_TYPE (inner_array));
11161           inner_array = TYPE_TARGET_TYPE (inner_array);
11162         }
11163
11164       el_type = TYPE_TARGET_TYPE (inner_array);
11165       TYPE_TARGET_TYPE (inner_array) =
11166         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
11167
11168       return set_die_type (die, base_type, cu);
11169     }
11170
11171   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
11172   return set_die_type (die, cv_type, cu);
11173 }
11174
11175 static struct type *
11176 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
11177 {
11178   struct type *base_type, *cv_type;
11179
11180   base_type = die_type (die, cu);
11181
11182   /* The die_type call above may have already set the type for this DIE.  */
11183   cv_type = get_die_type (die, cu);
11184   if (cv_type)
11185     return cv_type;
11186
11187   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
11188   return set_die_type (die, cv_type, cu);
11189 }
11190
11191 /* Extract all information from a DW_TAG_string_type DIE and add to
11192    the user defined type vector.  It isn't really a user defined type,
11193    but it behaves like one, with other DIE's using an AT_user_def_type
11194    attribute to reference it.  */
11195
11196 static struct type *
11197 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
11198 {
11199   struct objfile *objfile = cu->objfile;
11200   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11201   struct type *type, *range_type, *index_type, *char_type;
11202   struct attribute *attr;
11203   unsigned int length;
11204
11205   attr = dwarf2_attr (die, DW_AT_string_length, cu);
11206   if (attr)
11207     {
11208       length = DW_UNSND (attr);
11209     }
11210   else
11211     {
11212       /* Check for the DW_AT_byte_size attribute.  */
11213       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11214       if (attr)
11215         {
11216           length = DW_UNSND (attr);
11217         }
11218       else
11219         {
11220           length = 1;
11221         }
11222     }
11223
11224   index_type = objfile_type (objfile)->builtin_int;
11225   range_type = create_range_type (NULL, index_type, 1, length);
11226   char_type = language_string_char_type (cu->language_defn, gdbarch);
11227   type = create_string_type (NULL, char_type, range_type);
11228
11229   return set_die_type (die, type, cu);
11230 }
11231
11232 /* Handle DIES due to C code like:
11233
11234    struct foo
11235    {
11236    int (*funcp)(int a, long l);
11237    int b;
11238    };
11239
11240    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
11241
11242 static struct type *
11243 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
11244 {
11245   struct objfile *objfile = cu->objfile;
11246   struct type *type;            /* Type that this function returns.  */
11247   struct type *ftype;           /* Function that returns above type.  */
11248   struct attribute *attr;
11249
11250   type = die_type (die, cu);
11251
11252   /* The die_type call above may have already set the type for this DIE.  */
11253   ftype = get_die_type (die, cu);
11254   if (ftype)
11255     return ftype;
11256
11257   ftype = lookup_function_type (type);
11258
11259   /* All functions in C++, Pascal and Java have prototypes.  */
11260   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
11261   if ((attr && (DW_UNSND (attr) != 0))
11262       || cu->language == language_cplus
11263       || cu->language == language_java
11264       || cu->language == language_pascal)
11265     TYPE_PROTOTYPED (ftype) = 1;
11266   else if (producer_is_realview (cu->producer))
11267     /* RealView does not emit DW_AT_prototyped.  We can not
11268        distinguish prototyped and unprototyped functions; default to
11269        prototyped, since that is more common in modern code (and
11270        RealView warns about unprototyped functions).  */
11271     TYPE_PROTOTYPED (ftype) = 1;
11272
11273   /* Store the calling convention in the type if it's available in
11274      the subroutine die.  Otherwise set the calling convention to
11275      the default value DW_CC_normal.  */
11276   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
11277   if (attr)
11278     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
11279   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
11280     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
11281   else
11282     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
11283
11284   /* We need to add the subroutine type to the die immediately so
11285      we don't infinitely recurse when dealing with parameters
11286      declared as the same subroutine type.  */
11287   set_die_type (die, ftype, cu);
11288
11289   if (die->child != NULL)
11290     {
11291       struct type *void_type = objfile_type (objfile)->builtin_void;
11292       struct die_info *child_die;
11293       int nparams, iparams;
11294
11295       /* Count the number of parameters.
11296          FIXME: GDB currently ignores vararg functions, but knows about
11297          vararg member functions.  */
11298       nparams = 0;
11299       child_die = die->child;
11300       while (child_die && child_die->tag)
11301         {
11302           if (child_die->tag == DW_TAG_formal_parameter)
11303             nparams++;
11304           else if (child_die->tag == DW_TAG_unspecified_parameters)
11305             TYPE_VARARGS (ftype) = 1;
11306           child_die = sibling_die (child_die);
11307         }
11308
11309       /* Allocate storage for parameters and fill them in.  */
11310       TYPE_NFIELDS (ftype) = nparams;
11311       TYPE_FIELDS (ftype) = (struct field *)
11312         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
11313
11314       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
11315          even if we error out during the parameters reading below.  */
11316       for (iparams = 0; iparams < nparams; iparams++)
11317         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
11318
11319       iparams = 0;
11320       child_die = die->child;
11321       while (child_die && child_die->tag)
11322         {
11323           if (child_die->tag == DW_TAG_formal_parameter)
11324             {
11325               struct type *arg_type;
11326
11327               /* DWARF version 2 has no clean way to discern C++
11328                  static and non-static member functions.  G++ helps
11329                  GDB by marking the first parameter for non-static
11330                  member functions (which is the this pointer) as
11331                  artificial.  We pass this information to
11332                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
11333
11334                  DWARF version 3 added DW_AT_object_pointer, which GCC
11335                  4.5 does not yet generate.  */
11336               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
11337               if (attr)
11338                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
11339               else
11340                 {
11341                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
11342
11343                   /* GCC/43521: In java, the formal parameter
11344                      "this" is sometimes not marked with DW_AT_artificial.  */
11345                   if (cu->language == language_java)
11346                     {
11347                       const char *name = dwarf2_name (child_die, cu);
11348
11349                       if (name && !strcmp (name, "this"))
11350                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
11351                     }
11352                 }
11353               arg_type = die_type (child_die, cu);
11354
11355               /* RealView does not mark THIS as const, which the testsuite
11356                  expects.  GCC marks THIS as const in method definitions,
11357                  but not in the class specifications (GCC PR 43053).  */
11358               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
11359                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
11360                 {
11361                   int is_this = 0;
11362                   struct dwarf2_cu *arg_cu = cu;
11363                   const char *name = dwarf2_name (child_die, cu);
11364
11365                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
11366                   if (attr)
11367                     {
11368                       /* If the compiler emits this, use it.  */
11369                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
11370                         is_this = 1;
11371                     }
11372                   else if (name && strcmp (name, "this") == 0)
11373                     /* Function definitions will have the argument names.  */
11374                     is_this = 1;
11375                   else if (name == NULL && iparams == 0)
11376                     /* Declarations may not have the names, so like
11377                        elsewhere in GDB, assume an artificial first
11378                        argument is "this".  */
11379                     is_this = 1;
11380
11381                   if (is_this)
11382                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
11383                                              arg_type, 0);
11384                 }
11385
11386               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
11387               iparams++;
11388             }
11389           child_die = sibling_die (child_die);
11390         }
11391     }
11392
11393   return ftype;
11394 }
11395
11396 static struct type *
11397 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
11398 {
11399   struct objfile *objfile = cu->objfile;
11400   const char *name = NULL;
11401   struct type *this_type, *target_type;
11402
11403   name = dwarf2_full_name (NULL, die, cu);
11404   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
11405                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
11406   TYPE_NAME (this_type) = (char *) name;
11407   set_die_type (die, this_type, cu);
11408   target_type = die_type (die, cu);
11409   if (target_type != this_type)
11410     TYPE_TARGET_TYPE (this_type) = target_type;
11411   else
11412     {
11413       /* Self-referential typedefs are, it seems, not allowed by the DWARF
11414          spec and cause infinite loops in GDB.  */
11415       complaint (&symfile_complaints,
11416                  _("Self-referential DW_TAG_typedef "
11417                    "- DIE at 0x%x [in module %s]"),
11418                  die->offset.sect_off, objfile->name);
11419       TYPE_TARGET_TYPE (this_type) = NULL;
11420     }
11421   return this_type;
11422 }
11423
11424 /* Find a representation of a given base type and install
11425    it in the TYPE field of the die.  */
11426
11427 static struct type *
11428 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
11429 {
11430   struct objfile *objfile = cu->objfile;
11431   struct type *type;
11432   struct attribute *attr;
11433   int encoding = 0, size = 0;
11434   char *name;
11435   enum type_code code = TYPE_CODE_INT;
11436   int type_flags = 0;
11437   struct type *target_type = NULL;
11438
11439   attr = dwarf2_attr (die, DW_AT_encoding, cu);
11440   if (attr)
11441     {
11442       encoding = DW_UNSND (attr);
11443     }
11444   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11445   if (attr)
11446     {
11447       size = DW_UNSND (attr);
11448     }
11449   name = dwarf2_name (die, cu);
11450   if (!name)
11451     {
11452       complaint (&symfile_complaints,
11453                  _("DW_AT_name missing from DW_TAG_base_type"));
11454     }
11455
11456   switch (encoding)
11457     {
11458       case DW_ATE_address:
11459         /* Turn DW_ATE_address into a void * pointer.  */
11460         code = TYPE_CODE_PTR;
11461         type_flags |= TYPE_FLAG_UNSIGNED;
11462         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
11463         break;
11464       case DW_ATE_boolean:
11465         code = TYPE_CODE_BOOL;
11466         type_flags |= TYPE_FLAG_UNSIGNED;
11467         break;
11468       case DW_ATE_complex_float:
11469         code = TYPE_CODE_COMPLEX;
11470         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
11471         break;
11472       case DW_ATE_decimal_float:
11473         code = TYPE_CODE_DECFLOAT;
11474         break;
11475       case DW_ATE_float:
11476         code = TYPE_CODE_FLT;
11477         break;
11478       case DW_ATE_signed:
11479         break;
11480       case DW_ATE_unsigned:
11481         type_flags |= TYPE_FLAG_UNSIGNED;
11482         if (cu->language == language_fortran
11483             && name
11484             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
11485           code = TYPE_CODE_CHAR;
11486         break;
11487       case DW_ATE_signed_char:
11488         if (cu->language == language_ada || cu->language == language_m2
11489             || cu->language == language_pascal
11490             || cu->language == language_fortran)
11491           code = TYPE_CODE_CHAR;
11492         break;
11493       case DW_ATE_unsigned_char:
11494         if (cu->language == language_ada || cu->language == language_m2
11495             || cu->language == language_pascal
11496             || cu->language == language_fortran)
11497           code = TYPE_CODE_CHAR;
11498         type_flags |= TYPE_FLAG_UNSIGNED;
11499         break;
11500       case DW_ATE_UTF:
11501         /* We just treat this as an integer and then recognize the
11502            type by name elsewhere.  */
11503         break;
11504
11505       default:
11506         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
11507                    dwarf_type_encoding_name (encoding));
11508         break;
11509     }
11510
11511   type = init_type (code, size, type_flags, NULL, objfile);
11512   TYPE_NAME (type) = name;
11513   TYPE_TARGET_TYPE (type) = target_type;
11514
11515   if (name && strcmp (name, "char") == 0)
11516     TYPE_NOSIGN (type) = 1;
11517
11518   return set_die_type (die, type, cu);
11519 }
11520
11521 /* Read the given DW_AT_subrange DIE.  */
11522
11523 static struct type *
11524 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
11525 {
11526   struct type *base_type;
11527   struct type *range_type;
11528   struct attribute *attr;
11529   LONGEST low, high;
11530   int low_default_is_valid;
11531   char *name;
11532   LONGEST negative_mask;
11533
11534   base_type = die_type (die, cu);
11535   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
11536   check_typedef (base_type);
11537
11538   /* The die_type call above may have already set the type for this DIE.  */
11539   range_type = get_die_type (die, cu);
11540   if (range_type)
11541     return range_type;
11542
11543   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
11544      omitting DW_AT_lower_bound.  */
11545   switch (cu->language)
11546     {
11547     case language_c:
11548     case language_cplus:
11549       low = 0;
11550       low_default_is_valid = 1;
11551       break;
11552     case language_fortran:
11553       low = 1;
11554       low_default_is_valid = 1;
11555       break;
11556     case language_d:
11557     case language_java:
11558     case language_objc:
11559       low = 0;
11560       low_default_is_valid = (cu->header.version >= 4);
11561       break;
11562     case language_ada:
11563     case language_m2:
11564     case language_pascal:
11565       low = 1;
11566       low_default_is_valid = (cu->header.version >= 4);
11567       break;
11568     default:
11569       low = 0;
11570       low_default_is_valid = 0;
11571       break;
11572     }
11573
11574   /* FIXME: For variable sized arrays either of these could be
11575      a variable rather than a constant value.  We'll allow it,
11576      but we don't know how to handle it.  */
11577   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
11578   if (attr)
11579     low = dwarf2_get_attr_constant_value (attr, low);
11580   else if (!low_default_is_valid)
11581     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
11582                                       "- DIE at 0x%x [in module %s]"),
11583                die->offset.sect_off, cu->objfile->name);
11584
11585   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
11586   if (attr)
11587     {
11588       if (attr_form_is_block (attr) || is_ref_attr (attr))
11589         {
11590           /* GCC encodes arrays with unspecified or dynamic length
11591              with a DW_FORM_block1 attribute or a reference attribute.
11592              FIXME: GDB does not yet know how to handle dynamic
11593              arrays properly, treat them as arrays with unspecified
11594              length for now.
11595
11596              FIXME: jimb/2003-09-22: GDB does not really know
11597              how to handle arrays of unspecified length
11598              either; we just represent them as zero-length
11599              arrays.  Choose an appropriate upper bound given
11600              the lower bound we've computed above.  */
11601           high = low - 1;
11602         }
11603       else
11604         high = dwarf2_get_attr_constant_value (attr, 1);
11605     }
11606   else
11607     {
11608       attr = dwarf2_attr (die, DW_AT_count, cu);
11609       if (attr)
11610         {
11611           int count = dwarf2_get_attr_constant_value (attr, 1);
11612           high = low + count - 1;
11613         }
11614       else
11615         {
11616           /* Unspecified array length.  */
11617           high = low - 1;
11618         }
11619     }
11620
11621   /* Dwarf-2 specifications explicitly allows to create subrange types
11622      without specifying a base type.
11623      In that case, the base type must be set to the type of
11624      the lower bound, upper bound or count, in that order, if any of these
11625      three attributes references an object that has a type.
11626      If no base type is found, the Dwarf-2 specifications say that
11627      a signed integer type of size equal to the size of an address should
11628      be used.
11629      For the following C code: `extern char gdb_int [];'
11630      GCC produces an empty range DIE.
11631      FIXME: muller/2010-05-28: Possible references to object for low bound,
11632      high bound or count are not yet handled by this code.  */
11633   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
11634     {
11635       struct objfile *objfile = cu->objfile;
11636       struct gdbarch *gdbarch = get_objfile_arch (objfile);
11637       int addr_size = gdbarch_addr_bit (gdbarch) /8;
11638       struct type *int_type = objfile_type (objfile)->builtin_int;
11639
11640       /* Test "int", "long int", and "long long int" objfile types,
11641          and select the first one having a size above or equal to the
11642          architecture address size.  */
11643       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
11644         base_type = int_type;
11645       else
11646         {
11647           int_type = objfile_type (objfile)->builtin_long;
11648           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
11649             base_type = int_type;
11650           else
11651             {
11652               int_type = objfile_type (objfile)->builtin_long_long;
11653               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
11654                 base_type = int_type;
11655             }
11656         }
11657     }
11658
11659   negative_mask =
11660     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
11661   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
11662     low |= negative_mask;
11663   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
11664     high |= negative_mask;
11665
11666   range_type = create_range_type (NULL, base_type, low, high);
11667
11668   /* Mark arrays with dynamic length at least as an array of unspecified
11669      length.  GDB could check the boundary but before it gets implemented at
11670      least allow accessing the array elements.  */
11671   if (attr && attr_form_is_block (attr))
11672     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
11673
11674   /* Ada expects an empty array on no boundary attributes.  */
11675   if (attr == NULL && cu->language != language_ada)
11676     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
11677
11678   name = dwarf2_name (die, cu);
11679   if (name)
11680     TYPE_NAME (range_type) = name;
11681
11682   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11683   if (attr)
11684     TYPE_LENGTH (range_type) = DW_UNSND (attr);
11685
11686   set_die_type (die, range_type, cu);
11687
11688   /* set_die_type should be already done.  */
11689   set_descriptive_type (range_type, die, cu);
11690
11691   return range_type;
11692 }
11693
11694 static struct type *
11695 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
11696 {
11697   struct type *type;
11698
11699   /* For now, we only support the C meaning of an unspecified type: void.  */
11700
11701   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
11702   TYPE_NAME (type) = dwarf2_name (die, cu);
11703
11704   return set_die_type (die, type, cu);
11705 }
11706
11707 /* Read a single die and all its descendents.  Set the die's sibling
11708    field to NULL; set other fields in the die correctly, and set all
11709    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
11710    location of the info_ptr after reading all of those dies.  PARENT
11711    is the parent of the die in question.  */
11712
11713 static struct die_info *
11714 read_die_and_children (const struct die_reader_specs *reader,
11715                        gdb_byte *info_ptr,
11716                        gdb_byte **new_info_ptr,
11717                        struct die_info *parent)
11718 {
11719   struct die_info *die;
11720   gdb_byte *cur_ptr;
11721   int has_children;
11722
11723   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
11724   if (die == NULL)
11725     {
11726       *new_info_ptr = cur_ptr;
11727       return NULL;
11728     }
11729   store_in_ref_table (die, reader->cu);
11730
11731   if (has_children)
11732     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
11733   else
11734     {
11735       die->child = NULL;
11736       *new_info_ptr = cur_ptr;
11737     }
11738
11739   die->sibling = NULL;
11740   die->parent = parent;
11741   return die;
11742 }
11743
11744 /* Read a die, all of its descendents, and all of its siblings; set
11745    all of the fields of all of the dies correctly.  Arguments are as
11746    in read_die_and_children.  */
11747
11748 static struct die_info *
11749 read_die_and_siblings (const struct die_reader_specs *reader,
11750                        gdb_byte *info_ptr,
11751                        gdb_byte **new_info_ptr,
11752                        struct die_info *parent)
11753 {
11754   struct die_info *first_die, *last_sibling;
11755   gdb_byte *cur_ptr;
11756
11757   cur_ptr = info_ptr;
11758   first_die = last_sibling = NULL;
11759
11760   while (1)
11761     {
11762       struct die_info *die
11763         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
11764
11765       if (die == NULL)
11766         {
11767           *new_info_ptr = cur_ptr;
11768           return first_die;
11769         }
11770
11771       if (!first_die)
11772         first_die = die;
11773       else
11774         last_sibling->sibling = die;
11775
11776       last_sibling = die;
11777     }
11778 }
11779
11780 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
11781    attributes.
11782    The caller is responsible for filling in the extra attributes
11783    and updating (*DIEP)->num_attrs.
11784    Set DIEP to point to a newly allocated die with its information,
11785    except for its child, sibling, and parent fields.
11786    Set HAS_CHILDREN to tell whether the die has children or not.  */
11787
11788 static gdb_byte *
11789 read_full_die_1 (const struct die_reader_specs *reader,
11790                  struct die_info **diep, gdb_byte *info_ptr,
11791                  int *has_children, int num_extra_attrs)
11792 {
11793   unsigned int abbrev_number, bytes_read, i;
11794   sect_offset offset;
11795   struct abbrev_info *abbrev;
11796   struct die_info *die;
11797   struct dwarf2_cu *cu = reader->cu;
11798   bfd *abfd = reader->abfd;
11799
11800   offset.sect_off = info_ptr - reader->buffer;
11801   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11802   info_ptr += bytes_read;
11803   if (!abbrev_number)
11804     {
11805       *diep = NULL;
11806       *has_children = 0;
11807       return info_ptr;
11808     }
11809
11810   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
11811   if (!abbrev)
11812     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
11813            abbrev_number,
11814            bfd_get_filename (abfd));
11815
11816   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
11817   die->offset = offset;
11818   die->tag = abbrev->tag;
11819   die->abbrev = abbrev_number;
11820
11821   /* Make the result usable.
11822      The caller needs to update num_attrs after adding the extra
11823      attributes.  */
11824   die->num_attrs = abbrev->num_attrs;
11825
11826   for (i = 0; i < abbrev->num_attrs; ++i)
11827     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
11828                                info_ptr);
11829
11830   *diep = die;
11831   *has_children = abbrev->has_children;
11832   return info_ptr;
11833 }
11834
11835 /* Read a die and all its attributes.
11836    Set DIEP to point to a newly allocated die with its information,
11837    except for its child, sibling, and parent fields.
11838    Set HAS_CHILDREN to tell whether the die has children or not.  */
11839
11840 static gdb_byte *
11841 read_full_die (const struct die_reader_specs *reader,
11842                struct die_info **diep, gdb_byte *info_ptr,
11843                int *has_children)
11844 {
11845   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
11846 }
11847 \f
11848 /* Abbreviation tables.
11849
11850    In DWARF version 2, the description of the debugging information is
11851    stored in a separate .debug_abbrev section.  Before we read any
11852    dies from a section we read in all abbreviations and install them
11853    in a hash table.  */
11854
11855 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
11856
11857 static struct abbrev_info *
11858 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
11859 {
11860   struct abbrev_info *abbrev;
11861
11862   abbrev = (struct abbrev_info *)
11863     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
11864   memset (abbrev, 0, sizeof (struct abbrev_info));
11865   return abbrev;
11866 }
11867
11868 /* Add an abbreviation to the table.  */
11869
11870 static void
11871 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
11872                          unsigned int abbrev_number,
11873                          struct abbrev_info *abbrev)
11874 {
11875   unsigned int hash_number;
11876
11877   hash_number = abbrev_number % ABBREV_HASH_SIZE;
11878   abbrev->next = abbrev_table->abbrevs[hash_number];
11879   abbrev_table->abbrevs[hash_number] = abbrev;
11880 }
11881
11882 /* Look up an abbrev in the table.
11883    Returns NULL if the abbrev is not found.  */
11884
11885 static struct abbrev_info *
11886 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
11887                             unsigned int abbrev_number)
11888 {
11889   unsigned int hash_number;
11890   struct abbrev_info *abbrev;
11891
11892   hash_number = abbrev_number % ABBREV_HASH_SIZE;
11893   abbrev = abbrev_table->abbrevs[hash_number];
11894
11895   while (abbrev)
11896     {
11897       if (abbrev->number == abbrev_number)
11898         return abbrev;
11899       abbrev = abbrev->next;
11900     }
11901   return NULL;
11902 }
11903
11904 /* Read in an abbrev table.  */
11905
11906 static struct abbrev_table *
11907 abbrev_table_read_table (struct dwarf2_section_info *section,
11908                          sect_offset offset)
11909 {
11910   struct objfile *objfile = dwarf2_per_objfile->objfile;
11911   bfd *abfd = section->asection->owner;
11912   struct abbrev_table *abbrev_table;
11913   gdb_byte *abbrev_ptr;
11914   struct abbrev_info *cur_abbrev;
11915   unsigned int abbrev_number, bytes_read, abbrev_name;
11916   unsigned int abbrev_form;
11917   struct attr_abbrev *cur_attrs;
11918   unsigned int allocated_attrs;
11919
11920   abbrev_table = XMALLOC (struct abbrev_table);
11921   abbrev_table->offset = offset;
11922   obstack_init (&abbrev_table->abbrev_obstack);
11923   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
11924                                          (ABBREV_HASH_SIZE
11925                                           * sizeof (struct abbrev_info *)));
11926   memset (abbrev_table->abbrevs, 0,
11927           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
11928
11929   dwarf2_read_section (objfile, section);
11930   abbrev_ptr = section->buffer + offset.sect_off;
11931   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11932   abbrev_ptr += bytes_read;
11933
11934   allocated_attrs = ATTR_ALLOC_CHUNK;
11935   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
11936
11937   /* Loop until we reach an abbrev number of 0.  */
11938   while (abbrev_number)
11939     {
11940       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
11941
11942       /* read in abbrev header */
11943       cur_abbrev->number = abbrev_number;
11944       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11945       abbrev_ptr += bytes_read;
11946       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
11947       abbrev_ptr += 1;
11948
11949       /* now read in declarations */
11950       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11951       abbrev_ptr += bytes_read;
11952       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11953       abbrev_ptr += bytes_read;
11954       while (abbrev_name)
11955         {
11956           if (cur_abbrev->num_attrs == allocated_attrs)
11957             {
11958               allocated_attrs += ATTR_ALLOC_CHUNK;
11959               cur_attrs
11960                 = xrealloc (cur_attrs, (allocated_attrs
11961                                         * sizeof (struct attr_abbrev)));
11962             }
11963
11964           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
11965           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
11966           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11967           abbrev_ptr += bytes_read;
11968           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11969           abbrev_ptr += bytes_read;
11970         }
11971
11972       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
11973                                          (cur_abbrev->num_attrs
11974                                           * sizeof (struct attr_abbrev)));
11975       memcpy (cur_abbrev->attrs, cur_attrs,
11976               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
11977
11978       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
11979
11980       /* Get next abbreviation.
11981          Under Irix6 the abbreviations for a compilation unit are not
11982          always properly terminated with an abbrev number of 0.
11983          Exit loop if we encounter an abbreviation which we have
11984          already read (which means we are about to read the abbreviations
11985          for the next compile unit) or if the end of the abbreviation
11986          table is reached.  */
11987       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
11988         break;
11989       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
11990       abbrev_ptr += bytes_read;
11991       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
11992         break;
11993     }
11994
11995   xfree (cur_attrs);
11996   return abbrev_table;
11997 }
11998
11999 /* Free the resources held by ABBREV_TABLE.  */
12000
12001 static void
12002 abbrev_table_free (struct abbrev_table *abbrev_table)
12003 {
12004   obstack_free (&abbrev_table->abbrev_obstack, NULL);
12005   xfree (abbrev_table);
12006 }
12007
12008 /* Same as abbrev_table_free but as a cleanup.
12009    We pass in a pointer to the pointer to the table so that we can
12010    set the pointer to NULL when we're done.  It also simplifies
12011    build_type_unit_groups.  */
12012
12013 static void
12014 abbrev_table_free_cleanup (void *table_ptr)
12015 {
12016   struct abbrev_table **abbrev_table_ptr = table_ptr;
12017
12018   if (*abbrev_table_ptr != NULL)
12019     abbrev_table_free (*abbrev_table_ptr);
12020   *abbrev_table_ptr = NULL;
12021 }
12022
12023 /* Read the abbrev table for CU from ABBREV_SECTION.  */
12024
12025 static void
12026 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
12027                      struct dwarf2_section_info *abbrev_section)
12028 {
12029   cu->abbrev_table =
12030     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
12031 }
12032
12033 /* Release the memory used by the abbrev table for a compilation unit.  */
12034
12035 static void
12036 dwarf2_free_abbrev_table (void *ptr_to_cu)
12037 {
12038   struct dwarf2_cu *cu = ptr_to_cu;
12039
12040   abbrev_table_free (cu->abbrev_table);
12041   /* Set this to NULL so that we SEGV if we try to read it later,
12042      and also because free_comp_unit verifies this is NULL.  */
12043   cu->abbrev_table = NULL;
12044 }
12045 \f
12046 /* Returns nonzero if TAG represents a type that we might generate a partial
12047    symbol for.  */
12048
12049 static int
12050 is_type_tag_for_partial (int tag)
12051 {
12052   switch (tag)
12053     {
12054 #if 0
12055     /* Some types that would be reasonable to generate partial symbols for,
12056        that we don't at present.  */
12057     case DW_TAG_array_type:
12058     case DW_TAG_file_type:
12059     case DW_TAG_ptr_to_member_type:
12060     case DW_TAG_set_type:
12061     case DW_TAG_string_type:
12062     case DW_TAG_subroutine_type:
12063 #endif
12064     case DW_TAG_base_type:
12065     case DW_TAG_class_type:
12066     case DW_TAG_interface_type:
12067     case DW_TAG_enumeration_type:
12068     case DW_TAG_structure_type:
12069     case DW_TAG_subrange_type:
12070     case DW_TAG_typedef:
12071     case DW_TAG_union_type:
12072       return 1;
12073     default:
12074       return 0;
12075     }
12076 }
12077
12078 /* Load all DIEs that are interesting for partial symbols into memory.  */
12079
12080 static struct partial_die_info *
12081 load_partial_dies (const struct die_reader_specs *reader,
12082                    gdb_byte *info_ptr, int building_psymtab)
12083 {
12084   struct dwarf2_cu *cu = reader->cu;
12085   struct objfile *objfile = cu->objfile;
12086   struct partial_die_info *part_die;
12087   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
12088   struct abbrev_info *abbrev;
12089   unsigned int bytes_read;
12090   unsigned int load_all = 0;
12091   int nesting_level = 1;
12092
12093   parent_die = NULL;
12094   last_die = NULL;
12095
12096   gdb_assert (cu->per_cu != NULL);
12097   if (cu->per_cu->load_all_dies)
12098     load_all = 1;
12099
12100   cu->partial_dies
12101     = htab_create_alloc_ex (cu->header.length / 12,
12102                             partial_die_hash,
12103                             partial_die_eq,
12104                             NULL,
12105                             &cu->comp_unit_obstack,
12106                             hashtab_obstack_allocate,
12107                             dummy_obstack_deallocate);
12108
12109   part_die = obstack_alloc (&cu->comp_unit_obstack,
12110                             sizeof (struct partial_die_info));
12111
12112   while (1)
12113     {
12114       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
12115
12116       /* A NULL abbrev means the end of a series of children.  */
12117       if (abbrev == NULL)
12118         {
12119           if (--nesting_level == 0)
12120             {
12121               /* PART_DIE was probably the last thing allocated on the
12122                  comp_unit_obstack, so we could call obstack_free
12123                  here.  We don't do that because the waste is small,
12124                  and will be cleaned up when we're done with this
12125                  compilation unit.  This way, we're also more robust
12126                  against other users of the comp_unit_obstack.  */
12127               return first_die;
12128             }
12129           info_ptr += bytes_read;
12130           last_die = parent_die;
12131           parent_die = parent_die->die_parent;
12132           continue;
12133         }
12134
12135       /* Check for template arguments.  We never save these; if
12136          they're seen, we just mark the parent, and go on our way.  */
12137       if (parent_die != NULL
12138           && cu->language == language_cplus
12139           && (abbrev->tag == DW_TAG_template_type_param
12140               || abbrev->tag == DW_TAG_template_value_param))
12141         {
12142           parent_die->has_template_arguments = 1;
12143
12144           if (!load_all)
12145             {
12146               /* We don't need a partial DIE for the template argument.  */
12147               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
12148               continue;
12149             }
12150         }
12151
12152       /* We only recurse into c++ subprograms looking for template arguments.
12153          Skip their other children.  */
12154       if (!load_all
12155           && cu->language == language_cplus
12156           && parent_die != NULL
12157           && parent_die->tag == DW_TAG_subprogram)
12158         {
12159           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
12160           continue;
12161         }
12162
12163       /* Check whether this DIE is interesting enough to save.  Normally
12164          we would not be interested in members here, but there may be
12165          later variables referencing them via DW_AT_specification (for
12166          static members).  */
12167       if (!load_all
12168           && !is_type_tag_for_partial (abbrev->tag)
12169           && abbrev->tag != DW_TAG_constant
12170           && abbrev->tag != DW_TAG_enumerator
12171           && abbrev->tag != DW_TAG_subprogram
12172           && abbrev->tag != DW_TAG_lexical_block
12173           && abbrev->tag != DW_TAG_variable
12174           && abbrev->tag != DW_TAG_namespace
12175           && abbrev->tag != DW_TAG_module
12176           && abbrev->tag != DW_TAG_member
12177           && abbrev->tag != DW_TAG_imported_unit)
12178         {
12179           /* Otherwise we skip to the next sibling, if any.  */
12180           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
12181           continue;
12182         }
12183
12184       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
12185                                    info_ptr);
12186
12187       /* This two-pass algorithm for processing partial symbols has a
12188          high cost in cache pressure.  Thus, handle some simple cases
12189          here which cover the majority of C partial symbols.  DIEs
12190          which neither have specification tags in them, nor could have
12191          specification tags elsewhere pointing at them, can simply be
12192          processed and discarded.
12193
12194          This segment is also optional; scan_partial_symbols and
12195          add_partial_symbol will handle these DIEs if we chain
12196          them in normally.  When compilers which do not emit large
12197          quantities of duplicate debug information are more common,
12198          this code can probably be removed.  */
12199
12200       /* Any complete simple types at the top level (pretty much all
12201          of them, for a language without namespaces), can be processed
12202          directly.  */
12203       if (parent_die == NULL
12204           && part_die->has_specification == 0
12205           && part_die->is_declaration == 0
12206           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
12207               || part_die->tag == DW_TAG_base_type
12208               || part_die->tag == DW_TAG_subrange_type))
12209         {
12210           if (building_psymtab && part_die->name != NULL)
12211             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
12212                                  VAR_DOMAIN, LOC_TYPEDEF,
12213                                  &objfile->static_psymbols,
12214                                  0, (CORE_ADDR) 0, cu->language, objfile);
12215           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
12216           continue;
12217         }
12218
12219       /* The exception for DW_TAG_typedef with has_children above is
12220          a workaround of GCC PR debug/47510.  In the case of this complaint
12221          type_name_no_tag_or_error will error on such types later.
12222
12223          GDB skipped children of DW_TAG_typedef by the shortcut above and then
12224          it could not find the child DIEs referenced later, this is checked
12225          above.  In correct DWARF DW_TAG_typedef should have no children.  */
12226
12227       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
12228         complaint (&symfile_complaints,
12229                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
12230                      "- DIE at 0x%x [in module %s]"),
12231                    part_die->offset.sect_off, objfile->name);
12232
12233       /* If we're at the second level, and we're an enumerator, and
12234          our parent has no specification (meaning possibly lives in a
12235          namespace elsewhere), then we can add the partial symbol now
12236          instead of queueing it.  */
12237       if (part_die->tag == DW_TAG_enumerator
12238           && parent_die != NULL
12239           && parent_die->die_parent == NULL
12240           && parent_die->tag == DW_TAG_enumeration_type
12241           && parent_die->has_specification == 0)
12242         {
12243           if (part_die->name == NULL)
12244             complaint (&symfile_complaints,
12245                        _("malformed enumerator DIE ignored"));
12246           else if (building_psymtab)
12247             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
12248                                  VAR_DOMAIN, LOC_CONST,
12249                                  (cu->language == language_cplus
12250                                   || cu->language == language_java)
12251                                  ? &objfile->global_psymbols
12252                                  : &objfile->static_psymbols,
12253                                  0, (CORE_ADDR) 0, cu->language, objfile);
12254
12255           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
12256           continue;
12257         }
12258
12259       /* We'll save this DIE so link it in.  */
12260       part_die->die_parent = parent_die;
12261       part_die->die_sibling = NULL;
12262       part_die->die_child = NULL;
12263
12264       if (last_die && last_die == parent_die)
12265         last_die->die_child = part_die;
12266       else if (last_die)
12267         last_die->die_sibling = part_die;
12268
12269       last_die = part_die;
12270
12271       if (first_die == NULL)
12272         first_die = part_die;
12273
12274       /* Maybe add the DIE to the hash table.  Not all DIEs that we
12275          find interesting need to be in the hash table, because we
12276          also have the parent/sibling/child chains; only those that we
12277          might refer to by offset later during partial symbol reading.
12278
12279          For now this means things that might have be the target of a
12280          DW_AT_specification, DW_AT_abstract_origin, or
12281          DW_AT_extension.  DW_AT_extension will refer only to
12282          namespaces; DW_AT_abstract_origin refers to functions (and
12283          many things under the function DIE, but we do not recurse
12284          into function DIEs during partial symbol reading) and
12285          possibly variables as well; DW_AT_specification refers to
12286          declarations.  Declarations ought to have the DW_AT_declaration
12287          flag.  It happens that GCC forgets to put it in sometimes, but
12288          only for functions, not for types.
12289
12290          Adding more things than necessary to the hash table is harmless
12291          except for the performance cost.  Adding too few will result in
12292          wasted time in find_partial_die, when we reread the compilation
12293          unit with load_all_dies set.  */
12294
12295       if (load_all
12296           || abbrev->tag == DW_TAG_constant
12297           || abbrev->tag == DW_TAG_subprogram
12298           || abbrev->tag == DW_TAG_variable
12299           || abbrev->tag == DW_TAG_namespace
12300           || part_die->is_declaration)
12301         {
12302           void **slot;
12303
12304           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
12305                                            part_die->offset.sect_off, INSERT);
12306           *slot = part_die;
12307         }
12308
12309       part_die = obstack_alloc (&cu->comp_unit_obstack,
12310                                 sizeof (struct partial_die_info));
12311
12312       /* For some DIEs we want to follow their children (if any).  For C
12313          we have no reason to follow the children of structures; for other
12314          languages we have to, so that we can get at method physnames
12315          to infer fully qualified class names, for DW_AT_specification,
12316          and for C++ template arguments.  For C++, we also look one level
12317          inside functions to find template arguments (if the name of the
12318          function does not already contain the template arguments).
12319
12320          For Ada, we need to scan the children of subprograms and lexical
12321          blocks as well because Ada allows the definition of nested
12322          entities that could be interesting for the debugger, such as
12323          nested subprograms for instance.  */
12324       if (last_die->has_children
12325           && (load_all
12326               || last_die->tag == DW_TAG_namespace
12327               || last_die->tag == DW_TAG_module
12328               || last_die->tag == DW_TAG_enumeration_type
12329               || (cu->language == language_cplus
12330                   && last_die->tag == DW_TAG_subprogram
12331                   && (last_die->name == NULL
12332                       || strchr (last_die->name, '<') == NULL))
12333               || (cu->language != language_c
12334                   && (last_die->tag == DW_TAG_class_type
12335                       || last_die->tag == DW_TAG_interface_type
12336                       || last_die->tag == DW_TAG_structure_type
12337                       || last_die->tag == DW_TAG_union_type))
12338               || (cu->language == language_ada
12339                   && (last_die->tag == DW_TAG_subprogram
12340                       || last_die->tag == DW_TAG_lexical_block))))
12341         {
12342           nesting_level++;
12343           parent_die = last_die;
12344           continue;
12345         }
12346
12347       /* Otherwise we skip to the next sibling, if any.  */
12348       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
12349
12350       /* Back to the top, do it again.  */
12351     }
12352 }
12353
12354 /* Read a minimal amount of information into the minimal die structure.  */
12355
12356 static gdb_byte *
12357 read_partial_die (const struct die_reader_specs *reader,
12358                   struct partial_die_info *part_die,
12359                   struct abbrev_info *abbrev, unsigned int abbrev_len,
12360                   gdb_byte *info_ptr)
12361 {
12362   struct dwarf2_cu *cu = reader->cu;
12363   struct objfile *objfile = cu->objfile;
12364   gdb_byte *buffer = reader->buffer;
12365   unsigned int i;
12366   struct attribute attr;
12367   int has_low_pc_attr = 0;
12368   int has_high_pc_attr = 0;
12369   int high_pc_relative = 0;
12370
12371   memset (part_die, 0, sizeof (struct partial_die_info));
12372
12373   part_die->offset.sect_off = info_ptr - buffer;
12374
12375   info_ptr += abbrev_len;
12376
12377   if (abbrev == NULL)
12378     return info_ptr;
12379
12380   part_die->tag = abbrev->tag;
12381   part_die->has_children = abbrev->has_children;
12382
12383   for (i = 0; i < abbrev->num_attrs; ++i)
12384     {
12385       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
12386
12387       /* Store the data if it is of an attribute we want to keep in a
12388          partial symbol table.  */
12389       switch (attr.name)
12390         {
12391         case DW_AT_name:
12392           switch (part_die->tag)
12393             {
12394             case DW_TAG_compile_unit:
12395             case DW_TAG_partial_unit:
12396             case DW_TAG_type_unit:
12397               /* Compilation units have a DW_AT_name that is a filename, not
12398                  a source language identifier.  */
12399             case DW_TAG_enumeration_type:
12400             case DW_TAG_enumerator:
12401               /* These tags always have simple identifiers already; no need
12402                  to canonicalize them.  */
12403               part_die->name = DW_STRING (&attr);
12404               break;
12405             default:
12406               part_die->name
12407                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
12408                                             &objfile->objfile_obstack);
12409               break;
12410             }
12411           break;
12412         case DW_AT_linkage_name:
12413         case DW_AT_MIPS_linkage_name:
12414           /* Note that both forms of linkage name might appear.  We
12415              assume they will be the same, and we only store the last
12416              one we see.  */
12417           if (cu->language == language_ada)
12418             part_die->name = DW_STRING (&attr);
12419           part_die->linkage_name = DW_STRING (&attr);
12420           break;
12421         case DW_AT_low_pc:
12422           has_low_pc_attr = 1;
12423           part_die->lowpc = DW_ADDR (&attr);
12424           break;
12425         case DW_AT_high_pc:
12426           has_high_pc_attr = 1;
12427           if (attr.form == DW_FORM_addr
12428               || attr.form == DW_FORM_GNU_addr_index)
12429             part_die->highpc = DW_ADDR (&attr);
12430           else
12431             {
12432               high_pc_relative = 1;
12433               part_die->highpc = DW_UNSND (&attr);
12434             }
12435           break;
12436         case DW_AT_location:
12437           /* Support the .debug_loc offsets.  */
12438           if (attr_form_is_block (&attr))
12439             {
12440                part_die->d.locdesc = DW_BLOCK (&attr);
12441             }
12442           else if (attr_form_is_section_offset (&attr))
12443             {
12444               dwarf2_complex_location_expr_complaint ();
12445             }
12446           else
12447             {
12448               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12449                                                      "partial symbol information");
12450             }
12451           break;
12452         case DW_AT_external:
12453           part_die->is_external = DW_UNSND (&attr);
12454           break;
12455         case DW_AT_declaration:
12456           part_die->is_declaration = DW_UNSND (&attr);
12457           break;
12458         case DW_AT_type:
12459           part_die->has_type = 1;
12460           break;
12461         case DW_AT_abstract_origin:
12462         case DW_AT_specification:
12463         case DW_AT_extension:
12464           part_die->has_specification = 1;
12465           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
12466           break;
12467         case DW_AT_sibling:
12468           /* Ignore absolute siblings, they might point outside of
12469              the current compile unit.  */
12470           if (attr.form == DW_FORM_ref_addr)
12471             complaint (&symfile_complaints,
12472                        _("ignoring absolute DW_AT_sibling"));
12473           else
12474             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
12475           break;
12476         case DW_AT_byte_size:
12477           part_die->has_byte_size = 1;
12478           break;
12479         case DW_AT_calling_convention:
12480           /* DWARF doesn't provide a way to identify a program's source-level
12481              entry point.  DW_AT_calling_convention attributes are only meant
12482              to describe functions' calling conventions.
12483
12484              However, because it's a necessary piece of information in
12485              Fortran, and because DW_CC_program is the only piece of debugging
12486              information whose definition refers to a 'main program' at all,
12487              several compilers have begun marking Fortran main programs with
12488              DW_CC_program --- even when those functions use the standard
12489              calling conventions.
12490
12491              So until DWARF specifies a way to provide this information and
12492              compilers pick up the new representation, we'll support this
12493              practice.  */
12494           if (DW_UNSND (&attr) == DW_CC_program
12495               && cu->language == language_fortran)
12496             {
12497               set_main_name (part_die->name);
12498
12499               /* As this DIE has a static linkage the name would be difficult
12500                  to look up later.  */
12501               language_of_main = language_fortran;
12502             }
12503           break;
12504         case DW_AT_inline:
12505           if (DW_UNSND (&attr) == DW_INL_inlined
12506               || DW_UNSND (&attr) == DW_INL_declared_inlined)
12507             part_die->may_be_inlined = 1;
12508           break;
12509
12510         case DW_AT_import:
12511           if (part_die->tag == DW_TAG_imported_unit)
12512             part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
12513           break;
12514
12515         default:
12516           break;
12517         }
12518     }
12519
12520   if (high_pc_relative)
12521     part_die->highpc += part_die->lowpc;
12522
12523   if (has_low_pc_attr && has_high_pc_attr)
12524     {
12525       /* When using the GNU linker, .gnu.linkonce. sections are used to
12526          eliminate duplicate copies of functions and vtables and such.
12527          The linker will arbitrarily choose one and discard the others.
12528          The AT_*_pc values for such functions refer to local labels in
12529          these sections.  If the section from that file was discarded, the
12530          labels are not in the output, so the relocs get a value of 0.
12531          If this is a discarded function, mark the pc bounds as invalid,
12532          so that GDB will ignore it.  */
12533       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
12534         {
12535           struct gdbarch *gdbarch = get_objfile_arch (objfile);
12536
12537           complaint (&symfile_complaints,
12538                      _("DW_AT_low_pc %s is zero "
12539                        "for DIE at 0x%x [in module %s]"),
12540                      paddress (gdbarch, part_die->lowpc),
12541                      part_die->offset.sect_off, objfile->name);
12542         }
12543       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
12544       else if (part_die->lowpc >= part_die->highpc)
12545         {
12546           struct gdbarch *gdbarch = get_objfile_arch (objfile);
12547
12548           complaint (&symfile_complaints,
12549                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
12550                        "for DIE at 0x%x [in module %s]"),
12551                      paddress (gdbarch, part_die->lowpc),
12552                      paddress (gdbarch, part_die->highpc),
12553                      part_die->offset.sect_off, objfile->name);
12554         }
12555       else
12556         part_die->has_pc_info = 1;
12557     }
12558
12559   return info_ptr;
12560 }
12561
12562 /* Find a cached partial DIE at OFFSET in CU.  */
12563
12564 static struct partial_die_info *
12565 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
12566 {
12567   struct partial_die_info *lookup_die = NULL;
12568   struct partial_die_info part_die;
12569
12570   part_die.offset = offset;
12571   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
12572                                     offset.sect_off);
12573
12574   return lookup_die;
12575 }
12576
12577 /* Find a partial DIE at OFFSET, which may or may not be in CU,
12578    except in the case of .debug_types DIEs which do not reference
12579    outside their CU (they do however referencing other types via
12580    DW_FORM_ref_sig8).  */
12581
12582 static struct partial_die_info *
12583 find_partial_die (sect_offset offset, struct dwarf2_cu *cu)
12584 {
12585   struct objfile *objfile = cu->objfile;
12586   struct dwarf2_per_cu_data *per_cu = NULL;
12587   struct partial_die_info *pd = NULL;
12588
12589   if (offset_in_cu_p (&cu->header, offset))
12590     {
12591       pd = find_partial_die_in_comp_unit (offset, cu);
12592       if (pd != NULL)
12593         return pd;
12594       /* We missed recording what we needed.
12595          Load all dies and try again.  */
12596       per_cu = cu->per_cu;
12597     }
12598   else
12599     {
12600       /* TUs don't reference other CUs/TUs (except via type signatures).  */
12601       if (cu->per_cu->is_debug_types)
12602         {
12603           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
12604                    " external reference to offset 0x%lx [in module %s].\n"),
12605                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
12606                  bfd_get_filename (objfile->obfd));
12607         }
12608       per_cu = dwarf2_find_containing_comp_unit (offset, objfile);
12609
12610       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
12611         load_partial_comp_unit (per_cu);
12612
12613       per_cu->cu->last_used = 0;
12614       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
12615     }
12616
12617   /* If we didn't find it, and not all dies have been loaded,
12618      load them all and try again.  */
12619
12620   if (pd == NULL && per_cu->load_all_dies == 0)
12621     {
12622       per_cu->load_all_dies = 1;
12623
12624       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
12625          THIS_CU->cu may already be in use.  So we can't just free it and
12626          replace its DIEs with the ones we read in.  Instead, we leave those
12627          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
12628          and clobber THIS_CU->cu->partial_dies with the hash table for the new
12629          set.  */
12630       load_partial_comp_unit (per_cu);
12631
12632       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
12633     }
12634
12635   if (pd == NULL)
12636     internal_error (__FILE__, __LINE__,
12637                     _("could not find partial DIE 0x%x "
12638                       "in cache [from module %s]\n"),
12639                     offset.sect_off, bfd_get_filename (objfile->obfd));
12640   return pd;
12641 }
12642
12643 /* See if we can figure out if the class lives in a namespace.  We do
12644    this by looking for a member function; its demangled name will
12645    contain namespace info, if there is any.  */
12646
12647 static void
12648 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
12649                                   struct dwarf2_cu *cu)
12650 {
12651   /* NOTE: carlton/2003-10-07: Getting the info this way changes
12652      what template types look like, because the demangler
12653      frequently doesn't give the same name as the debug info.  We
12654      could fix this by only using the demangled name to get the
12655      prefix (but see comment in read_structure_type).  */
12656
12657   struct partial_die_info *real_pdi;
12658   struct partial_die_info *child_pdi;
12659
12660   /* If this DIE (this DIE's specification, if any) has a parent, then
12661      we should not do this.  We'll prepend the parent's fully qualified
12662      name when we create the partial symbol.  */
12663
12664   real_pdi = struct_pdi;
12665   while (real_pdi->has_specification)
12666     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
12667
12668   if (real_pdi->die_parent != NULL)
12669     return;
12670
12671   for (child_pdi = struct_pdi->die_child;
12672        child_pdi != NULL;
12673        child_pdi = child_pdi->die_sibling)
12674     {
12675       if (child_pdi->tag == DW_TAG_subprogram
12676           && child_pdi->linkage_name != NULL)
12677         {
12678           char *actual_class_name
12679             = language_class_name_from_physname (cu->language_defn,
12680                                                  child_pdi->linkage_name);
12681           if (actual_class_name != NULL)
12682             {
12683               struct_pdi->name
12684                 = obsavestring (actual_class_name,
12685                                 strlen (actual_class_name),
12686                                 &cu->objfile->objfile_obstack);
12687               xfree (actual_class_name);
12688             }
12689           break;
12690         }
12691     }
12692 }
12693
12694 /* Adjust PART_DIE before generating a symbol for it.  This function
12695    may set the is_external flag or change the DIE's name.  */
12696
12697 static void
12698 fixup_partial_die (struct partial_die_info *part_die,
12699                    struct dwarf2_cu *cu)
12700 {
12701   /* Once we've fixed up a die, there's no point in doing so again.
12702      This also avoids a memory leak if we were to call
12703      guess_partial_die_structure_name multiple times.  */
12704   if (part_die->fixup_called)
12705     return;
12706
12707   /* If we found a reference attribute and the DIE has no name, try
12708      to find a name in the referred to DIE.  */
12709
12710   if (part_die->name == NULL && part_die->has_specification)
12711     {
12712       struct partial_die_info *spec_die;
12713
12714       spec_die = find_partial_die (part_die->spec_offset, cu);
12715
12716       fixup_partial_die (spec_die, cu);
12717
12718       if (spec_die->name)
12719         {
12720           part_die->name = spec_die->name;
12721
12722           /* Copy DW_AT_external attribute if it is set.  */
12723           if (spec_die->is_external)
12724             part_die->is_external = spec_die->is_external;
12725         }
12726     }
12727
12728   /* Set default names for some unnamed DIEs.  */
12729
12730   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
12731     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
12732
12733   /* If there is no parent die to provide a namespace, and there are
12734      children, see if we can determine the namespace from their linkage
12735      name.  */
12736   if (cu->language == language_cplus
12737       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
12738       && part_die->die_parent == NULL
12739       && part_die->has_children
12740       && (part_die->tag == DW_TAG_class_type
12741           || part_die->tag == DW_TAG_structure_type
12742           || part_die->tag == DW_TAG_union_type))
12743     guess_partial_die_structure_name (part_die, cu);
12744
12745   /* GCC might emit a nameless struct or union that has a linkage
12746      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
12747   if (part_die->name == NULL
12748       && (part_die->tag == DW_TAG_class_type
12749           || part_die->tag == DW_TAG_interface_type
12750           || part_die->tag == DW_TAG_structure_type
12751           || part_die->tag == DW_TAG_union_type)
12752       && part_die->linkage_name != NULL)
12753     {
12754       char *demangled;
12755
12756       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
12757       if (demangled)
12758         {
12759           const char *base;
12760
12761           /* Strip any leading namespaces/classes, keep only the base name.
12762              DW_AT_name for named DIEs does not contain the prefixes.  */
12763           base = strrchr (demangled, ':');
12764           if (base && base > demangled && base[-1] == ':')
12765             base++;
12766           else
12767             base = demangled;
12768
12769           part_die->name = obsavestring (base, strlen (base),
12770                                          &cu->objfile->objfile_obstack);
12771           xfree (demangled);
12772         }
12773     }
12774
12775   part_die->fixup_called = 1;
12776 }
12777
12778 /* Read an attribute value described by an attribute form.  */
12779
12780 static gdb_byte *
12781 read_attribute_value (const struct die_reader_specs *reader,
12782                       struct attribute *attr, unsigned form,
12783                       gdb_byte *info_ptr)
12784 {
12785   struct dwarf2_cu *cu = reader->cu;
12786   bfd *abfd = reader->abfd;
12787   struct comp_unit_head *cu_header = &cu->header;
12788   unsigned int bytes_read;
12789   struct dwarf_block *blk;
12790
12791   attr->form = form;
12792   switch (form)
12793     {
12794     case DW_FORM_ref_addr:
12795       if (cu->header.version == 2)
12796         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
12797       else
12798         DW_UNSND (attr) = read_offset (abfd, info_ptr,
12799                                        &cu->header, &bytes_read);
12800       info_ptr += bytes_read;
12801       break;
12802     case DW_FORM_addr:
12803       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
12804       info_ptr += bytes_read;
12805       break;
12806     case DW_FORM_block2:
12807       blk = dwarf_alloc_block (cu);
12808       blk->size = read_2_bytes (abfd, info_ptr);
12809       info_ptr += 2;
12810       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12811       info_ptr += blk->size;
12812       DW_BLOCK (attr) = blk;
12813       break;
12814     case DW_FORM_block4:
12815       blk = dwarf_alloc_block (cu);
12816       blk->size = read_4_bytes (abfd, info_ptr);
12817       info_ptr += 4;
12818       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12819       info_ptr += blk->size;
12820       DW_BLOCK (attr) = blk;
12821       break;
12822     case DW_FORM_data2:
12823       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
12824       info_ptr += 2;
12825       break;
12826     case DW_FORM_data4:
12827       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
12828       info_ptr += 4;
12829       break;
12830     case DW_FORM_data8:
12831       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
12832       info_ptr += 8;
12833       break;
12834     case DW_FORM_sec_offset:
12835       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
12836       info_ptr += bytes_read;
12837       break;
12838     case DW_FORM_string:
12839       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
12840       DW_STRING_IS_CANONICAL (attr) = 0;
12841       info_ptr += bytes_read;
12842       break;
12843     case DW_FORM_strp:
12844       DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
12845                                                &bytes_read);
12846       DW_STRING_IS_CANONICAL (attr) = 0;
12847       info_ptr += bytes_read;
12848       break;
12849     case DW_FORM_exprloc:
12850     case DW_FORM_block:
12851       blk = dwarf_alloc_block (cu);
12852       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12853       info_ptr += bytes_read;
12854       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12855       info_ptr += blk->size;
12856       DW_BLOCK (attr) = blk;
12857       break;
12858     case DW_FORM_block1:
12859       blk = dwarf_alloc_block (cu);
12860       blk->size = read_1_byte (abfd, info_ptr);
12861       info_ptr += 1;
12862       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
12863       info_ptr += blk->size;
12864       DW_BLOCK (attr) = blk;
12865       break;
12866     case DW_FORM_data1:
12867       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
12868       info_ptr += 1;
12869       break;
12870     case DW_FORM_flag:
12871       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
12872       info_ptr += 1;
12873       break;
12874     case DW_FORM_flag_present:
12875       DW_UNSND (attr) = 1;
12876       break;
12877     case DW_FORM_sdata:
12878       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
12879       info_ptr += bytes_read;
12880       break;
12881     case DW_FORM_udata:
12882       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12883       info_ptr += bytes_read;
12884       break;
12885     case DW_FORM_ref1:
12886       DW_UNSND (attr) = (cu->header.offset.sect_off
12887                          + read_1_byte (abfd, info_ptr));
12888       info_ptr += 1;
12889       break;
12890     case DW_FORM_ref2:
12891       DW_UNSND (attr) = (cu->header.offset.sect_off
12892                          + read_2_bytes (abfd, info_ptr));
12893       info_ptr += 2;
12894       break;
12895     case DW_FORM_ref4:
12896       DW_UNSND (attr) = (cu->header.offset.sect_off
12897                          + read_4_bytes (abfd, info_ptr));
12898       info_ptr += 4;
12899       break;
12900     case DW_FORM_ref8:
12901       DW_UNSND (attr) = (cu->header.offset.sect_off
12902                          + read_8_bytes (abfd, info_ptr));
12903       info_ptr += 8;
12904       break;
12905     case DW_FORM_ref_sig8:
12906       /* Convert the signature to something we can record in DW_UNSND
12907          for later lookup.
12908          NOTE: This is NULL if the type wasn't found.  */
12909       DW_SIGNATURED_TYPE (attr) =
12910         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
12911       info_ptr += 8;
12912       break;
12913     case DW_FORM_ref_udata:
12914       DW_UNSND (attr) = (cu->header.offset.sect_off
12915                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
12916       info_ptr += bytes_read;
12917       break;
12918     case DW_FORM_indirect:
12919       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12920       info_ptr += bytes_read;
12921       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
12922       break;
12923     case DW_FORM_GNU_addr_index:
12924       if (reader->dwo_file == NULL)
12925         {
12926           /* For now flag a hard error.
12927              Later we can turn this into a complaint.  */
12928           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
12929                  dwarf_form_name (form),
12930                  bfd_get_filename (abfd));
12931         }
12932       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
12933       info_ptr += bytes_read;
12934       break;
12935     case DW_FORM_GNU_str_index:
12936       if (reader->dwo_file == NULL)
12937         {
12938           /* For now flag a hard error.
12939              Later we can turn this into a complaint if warranted.  */
12940           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
12941                  dwarf_form_name (form),
12942                  bfd_get_filename (abfd));
12943         }
12944       {
12945         ULONGEST str_index =
12946           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12947
12948         DW_STRING (attr) = read_str_index (reader, cu, str_index);
12949         DW_STRING_IS_CANONICAL (attr) = 0;
12950         info_ptr += bytes_read;
12951       }
12952       break;
12953     default:
12954       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
12955              dwarf_form_name (form),
12956              bfd_get_filename (abfd));
12957     }
12958
12959   /* We have seen instances where the compiler tried to emit a byte
12960      size attribute of -1 which ended up being encoded as an unsigned
12961      0xffffffff.  Although 0xffffffff is technically a valid size value,
12962      an object of this size seems pretty unlikely so we can relatively
12963      safely treat these cases as if the size attribute was invalid and
12964      treat them as zero by default.  */
12965   if (attr->name == DW_AT_byte_size
12966       && form == DW_FORM_data4
12967       && DW_UNSND (attr) >= 0xffffffff)
12968     {
12969       complaint
12970         (&symfile_complaints,
12971          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
12972          hex_string (DW_UNSND (attr)));
12973       DW_UNSND (attr) = 0;
12974     }
12975
12976   return info_ptr;
12977 }
12978
12979 /* Read an attribute described by an abbreviated attribute.  */
12980
12981 static gdb_byte *
12982 read_attribute (const struct die_reader_specs *reader,
12983                 struct attribute *attr, struct attr_abbrev *abbrev,
12984                 gdb_byte *info_ptr)
12985 {
12986   attr->name = abbrev->name;
12987   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
12988 }
12989
12990 /* Read dwarf information from a buffer.  */
12991
12992 static unsigned int
12993 read_1_byte (bfd *abfd, gdb_byte *buf)
12994 {
12995   return bfd_get_8 (abfd, buf);
12996 }
12997
12998 static int
12999 read_1_signed_byte (bfd *abfd, gdb_byte *buf)
13000 {
13001   return bfd_get_signed_8 (abfd, buf);
13002 }
13003
13004 static unsigned int
13005 read_2_bytes (bfd *abfd, gdb_byte *buf)
13006 {
13007   return bfd_get_16 (abfd, buf);
13008 }
13009
13010 static int
13011 read_2_signed_bytes (bfd *abfd, gdb_byte *buf)
13012 {
13013   return bfd_get_signed_16 (abfd, buf);
13014 }
13015
13016 static unsigned int
13017 read_4_bytes (bfd *abfd, gdb_byte *buf)
13018 {
13019   return bfd_get_32 (abfd, buf);
13020 }
13021
13022 static int
13023 read_4_signed_bytes (bfd *abfd, gdb_byte *buf)
13024 {
13025   return bfd_get_signed_32 (abfd, buf);
13026 }
13027
13028 static ULONGEST
13029 read_8_bytes (bfd *abfd, gdb_byte *buf)
13030 {
13031   return bfd_get_64 (abfd, buf);
13032 }
13033
13034 static CORE_ADDR
13035 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
13036               unsigned int *bytes_read)
13037 {
13038   struct comp_unit_head *cu_header = &cu->header;
13039   CORE_ADDR retval = 0;
13040
13041   if (cu_header->signed_addr_p)
13042     {
13043       switch (cu_header->addr_size)
13044         {
13045         case 2:
13046           retval = bfd_get_signed_16 (abfd, buf);
13047           break;
13048         case 4:
13049           retval = bfd_get_signed_32 (abfd, buf);
13050           break;
13051         case 8:
13052           retval = bfd_get_signed_64 (abfd, buf);
13053           break;
13054         default:
13055           internal_error (__FILE__, __LINE__,
13056                           _("read_address: bad switch, signed [in module %s]"),
13057                           bfd_get_filename (abfd));
13058         }
13059     }
13060   else
13061     {
13062       switch (cu_header->addr_size)
13063         {
13064         case 2:
13065           retval = bfd_get_16 (abfd, buf);
13066           break;
13067         case 4:
13068           retval = bfd_get_32 (abfd, buf);
13069           break;
13070         case 8:
13071           retval = bfd_get_64 (abfd, buf);
13072           break;
13073         default:
13074           internal_error (__FILE__, __LINE__,
13075                           _("read_address: bad switch, "
13076                             "unsigned [in module %s]"),
13077                           bfd_get_filename (abfd));
13078         }
13079     }
13080
13081   *bytes_read = cu_header->addr_size;
13082   return retval;
13083 }
13084
13085 /* Read the initial length from a section.  The (draft) DWARF 3
13086    specification allows the initial length to take up either 4 bytes
13087    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
13088    bytes describe the length and all offsets will be 8 bytes in length
13089    instead of 4.
13090
13091    An older, non-standard 64-bit format is also handled by this
13092    function.  The older format in question stores the initial length
13093    as an 8-byte quantity without an escape value.  Lengths greater
13094    than 2^32 aren't very common which means that the initial 4 bytes
13095    is almost always zero.  Since a length value of zero doesn't make
13096    sense for the 32-bit format, this initial zero can be considered to
13097    be an escape value which indicates the presence of the older 64-bit
13098    format.  As written, the code can't detect (old format) lengths
13099    greater than 4GB.  If it becomes necessary to handle lengths
13100    somewhat larger than 4GB, we could allow other small values (such
13101    as the non-sensical values of 1, 2, and 3) to also be used as
13102    escape values indicating the presence of the old format.
13103
13104    The value returned via bytes_read should be used to increment the
13105    relevant pointer after calling read_initial_length().
13106
13107    [ Note:  read_initial_length() and read_offset() are based on the
13108      document entitled "DWARF Debugging Information Format", revision
13109      3, draft 8, dated November 19, 2001.  This document was obtained
13110      from:
13111
13112         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
13113
13114      This document is only a draft and is subject to change.  (So beware.)
13115
13116      Details regarding the older, non-standard 64-bit format were
13117      determined empirically by examining 64-bit ELF files produced by
13118      the SGI toolchain on an IRIX 6.5 machine.
13119
13120      - Kevin, July 16, 2002
13121    ] */
13122
13123 static LONGEST
13124 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
13125 {
13126   LONGEST length = bfd_get_32 (abfd, buf);
13127
13128   if (length == 0xffffffff)
13129     {
13130       length = bfd_get_64 (abfd, buf + 4);
13131       *bytes_read = 12;
13132     }
13133   else if (length == 0)
13134     {
13135       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
13136       length = bfd_get_64 (abfd, buf);
13137       *bytes_read = 8;
13138     }
13139   else
13140     {
13141       *bytes_read = 4;
13142     }
13143
13144   return length;
13145 }
13146
13147 /* Cover function for read_initial_length.
13148    Returns the length of the object at BUF, and stores the size of the
13149    initial length in *BYTES_READ and stores the size that offsets will be in
13150    *OFFSET_SIZE.
13151    If the initial length size is not equivalent to that specified in
13152    CU_HEADER then issue a complaint.
13153    This is useful when reading non-comp-unit headers.  */
13154
13155 static LONGEST
13156 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
13157                                         const struct comp_unit_head *cu_header,
13158                                         unsigned int *bytes_read,
13159                                         unsigned int *offset_size)
13160 {
13161   LONGEST length = read_initial_length (abfd, buf, bytes_read);
13162
13163   gdb_assert (cu_header->initial_length_size == 4
13164               || cu_header->initial_length_size == 8
13165               || cu_header->initial_length_size == 12);
13166
13167   if (cu_header->initial_length_size != *bytes_read)
13168     complaint (&symfile_complaints,
13169                _("intermixed 32-bit and 64-bit DWARF sections"));
13170
13171   *offset_size = (*bytes_read == 4) ? 4 : 8;
13172   return length;
13173 }
13174
13175 /* Read an offset from the data stream.  The size of the offset is
13176    given by cu_header->offset_size.  */
13177
13178 static LONGEST
13179 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
13180              unsigned int *bytes_read)
13181 {
13182   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
13183
13184   *bytes_read = cu_header->offset_size;
13185   return offset;
13186 }
13187
13188 /* Read an offset from the data stream.  */
13189
13190 static LONGEST
13191 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
13192 {
13193   LONGEST retval = 0;
13194
13195   switch (offset_size)
13196     {
13197     case 4:
13198       retval = bfd_get_32 (abfd, buf);
13199       break;
13200     case 8:
13201       retval = bfd_get_64 (abfd, buf);
13202       break;
13203     default:
13204       internal_error (__FILE__, __LINE__,
13205                       _("read_offset_1: bad switch [in module %s]"),
13206                       bfd_get_filename (abfd));
13207     }
13208
13209   return retval;
13210 }
13211
13212 static gdb_byte *
13213 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
13214 {
13215   /* If the size of a host char is 8 bits, we can return a pointer
13216      to the buffer, otherwise we have to copy the data to a buffer
13217      allocated on the temporary obstack.  */
13218   gdb_assert (HOST_CHAR_BIT == 8);
13219   return buf;
13220 }
13221
13222 static char *
13223 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
13224 {
13225   /* If the size of a host char is 8 bits, we can return a pointer
13226      to the string, otherwise we have to copy the string to a buffer
13227      allocated on the temporary obstack.  */
13228   gdb_assert (HOST_CHAR_BIT == 8);
13229   if (*buf == '\0')
13230     {
13231       *bytes_read_ptr = 1;
13232       return NULL;
13233     }
13234   *bytes_read_ptr = strlen ((char *) buf) + 1;
13235   return (char *) buf;
13236 }
13237
13238 static char *
13239 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
13240 {
13241   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
13242   if (dwarf2_per_objfile->str.buffer == NULL)
13243     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
13244            bfd_get_filename (abfd));
13245   if (str_offset >= dwarf2_per_objfile->str.size)
13246     error (_("DW_FORM_strp pointing outside of "
13247              ".debug_str section [in module %s]"),
13248            bfd_get_filename (abfd));
13249   gdb_assert (HOST_CHAR_BIT == 8);
13250   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
13251     return NULL;
13252   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
13253 }
13254
13255 static char *
13256 read_indirect_string (bfd *abfd, gdb_byte *buf,
13257                       const struct comp_unit_head *cu_header,
13258                       unsigned int *bytes_read_ptr)
13259 {
13260   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
13261
13262   return read_indirect_string_at_offset (abfd, str_offset);
13263 }
13264
13265 static ULONGEST
13266 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
13267 {
13268   ULONGEST result;
13269   unsigned int num_read;
13270   int i, shift;
13271   unsigned char byte;
13272
13273   result = 0;
13274   shift = 0;
13275   num_read = 0;
13276   i = 0;
13277   while (1)
13278     {
13279       byte = bfd_get_8 (abfd, buf);
13280       buf++;
13281       num_read++;
13282       result |= ((ULONGEST) (byte & 127) << shift);
13283       if ((byte & 128) == 0)
13284         {
13285           break;
13286         }
13287       shift += 7;
13288     }
13289   *bytes_read_ptr = num_read;
13290   return result;
13291 }
13292
13293 static LONGEST
13294 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
13295 {
13296   LONGEST result;
13297   int i, shift, num_read;
13298   unsigned char byte;
13299
13300   result = 0;
13301   shift = 0;
13302   num_read = 0;
13303   i = 0;
13304   while (1)
13305     {
13306       byte = bfd_get_8 (abfd, buf);
13307       buf++;
13308       num_read++;
13309       result |= ((LONGEST) (byte & 127) << shift);
13310       shift += 7;
13311       if ((byte & 128) == 0)
13312         {
13313           break;
13314         }
13315     }
13316   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
13317     result |= -(((LONGEST) 1) << shift);
13318   *bytes_read_ptr = num_read;
13319   return result;
13320 }
13321
13322 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
13323    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
13324    ADDR_SIZE is the size of addresses from the CU header.  */
13325
13326 static CORE_ADDR
13327 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
13328 {
13329   struct objfile *objfile = dwarf2_per_objfile->objfile;
13330   bfd *abfd = objfile->obfd;
13331   const gdb_byte *info_ptr;
13332
13333   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
13334   if (dwarf2_per_objfile->addr.buffer == NULL)
13335     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
13336            objfile->name);
13337   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
13338     error (_("DW_FORM_addr_index pointing outside of "
13339              ".debug_addr section [in module %s]"),
13340            objfile->name);
13341   info_ptr = (dwarf2_per_objfile->addr.buffer
13342               + addr_base + addr_index * addr_size);
13343   if (addr_size == 4)
13344     return bfd_get_32 (abfd, info_ptr);
13345   else
13346     return bfd_get_64 (abfd, info_ptr);
13347 }
13348
13349 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
13350
13351 static CORE_ADDR
13352 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
13353 {
13354   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
13355 }
13356
13357 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
13358
13359 static CORE_ADDR
13360 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
13361                              unsigned int *bytes_read)
13362 {
13363   bfd *abfd = cu->objfile->obfd;
13364   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
13365
13366   return read_addr_index (cu, addr_index);
13367 }
13368
13369 /* Data structure to pass results from dwarf2_read_addr_index_reader
13370    back to dwarf2_read_addr_index.  */
13371
13372 struct dwarf2_read_addr_index_data
13373 {
13374   ULONGEST addr_base;
13375   int addr_size;
13376 };
13377
13378 /* die_reader_func for dwarf2_read_addr_index.  */
13379
13380 static void
13381 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
13382                                gdb_byte *info_ptr,
13383                                struct die_info *comp_unit_die,
13384                                int has_children,
13385                                void *data)
13386 {
13387   struct dwarf2_cu *cu = reader->cu;
13388   struct dwarf2_read_addr_index_data *aidata =
13389     (struct dwarf2_read_addr_index_data *) data;
13390
13391   aidata->addr_base = cu->addr_base;
13392   aidata->addr_size = cu->header.addr_size;
13393 }
13394
13395 /* Given an index in .debug_addr, fetch the value.
13396    NOTE: This can be called during dwarf expression evaluation,
13397    long after the debug information has been read, and thus per_cu->cu
13398    may no longer exist.  */
13399
13400 CORE_ADDR
13401 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
13402                         unsigned int addr_index)
13403 {
13404   struct objfile *objfile = per_cu->objfile;
13405   struct dwarf2_cu *cu = per_cu->cu;
13406   ULONGEST addr_base;
13407   int addr_size;
13408
13409   /* This is intended to be called from outside this file.  */
13410   dw2_setup (objfile);
13411
13412   /* We need addr_base and addr_size.
13413      If we don't have PER_CU->cu, we have to get it.
13414      Nasty, but the alternative is storing the needed info in PER_CU,
13415      which at this point doesn't seem justified: it's not clear how frequently
13416      it would get used and it would increase the size of every PER_CU.
13417      Entry points like dwarf2_per_cu_addr_size do a similar thing
13418      so we're not in uncharted territory here.
13419      Alas we need to be a bit more complicated as addr_base is contained
13420      in the DIE.
13421
13422      We don't need to read the entire CU(/TU).
13423      We just need the header and top level die.
13424      IWBN to use the aging mechanism to let us lazily later discard the CU.
13425      See however init_cutu_and_read_dies_simple.  */
13426
13427   if (cu != NULL)
13428     {
13429       addr_base = cu->addr_base;
13430       addr_size = cu->header.addr_size;
13431     }
13432   else
13433     {
13434       struct dwarf2_read_addr_index_data aidata;
13435
13436       init_cutu_and_read_dies_simple (per_cu, dwarf2_read_addr_index_reader,
13437                                       &aidata);
13438       addr_base = aidata.addr_base;
13439       addr_size = aidata.addr_size;
13440     }
13441
13442   return read_addr_index_1 (addr_index, addr_base, addr_size);
13443 }
13444
13445 /* Given a DW_AT_str_index, fetch the string.  */
13446
13447 static char *
13448 read_str_index (const struct die_reader_specs *reader,
13449                 struct dwarf2_cu *cu, ULONGEST str_index)
13450 {
13451   struct objfile *objfile = dwarf2_per_objfile->objfile;
13452   const char *dwo_name = objfile->name;
13453   bfd *abfd = objfile->obfd;
13454   struct dwo_sections *sections = &reader->dwo_file->sections;
13455   gdb_byte *info_ptr;
13456   ULONGEST str_offset;
13457
13458   dwarf2_read_section (objfile, &sections->str);
13459   dwarf2_read_section (objfile, &sections->str_offsets);
13460   if (sections->str.buffer == NULL)
13461     error (_("DW_FORM_str_index used without .debug_str.dwo section"
13462              " in CU at offset 0x%lx [in module %s]"),
13463            (long) cu->header.offset.sect_off, dwo_name);
13464   if (sections->str_offsets.buffer == NULL)
13465     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
13466              " in CU at offset 0x%lx [in module %s]"),
13467            (long) cu->header.offset.sect_off, dwo_name);
13468   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
13469     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
13470              " section in CU at offset 0x%lx [in module %s]"),
13471            (long) cu->header.offset.sect_off, dwo_name);
13472   info_ptr = (sections->str_offsets.buffer
13473               + str_index * cu->header.offset_size);
13474   if (cu->header.offset_size == 4)
13475     str_offset = bfd_get_32 (abfd, info_ptr);
13476   else
13477     str_offset = bfd_get_64 (abfd, info_ptr);
13478   if (str_offset >= sections->str.size)
13479     error (_("Offset from DW_FORM_str_index pointing outside of"
13480              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
13481            (long) cu->header.offset.sect_off, dwo_name);
13482   return (char *) (sections->str.buffer + str_offset);
13483 }
13484
13485 /* Return the length of an LEB128 number in BUF.  */
13486
13487 static int
13488 leb128_size (const gdb_byte *buf)
13489 {
13490   const gdb_byte *begin = buf;
13491   gdb_byte byte;
13492
13493   while (1)
13494     {
13495       byte = *buf++;
13496       if ((byte & 128) == 0)
13497         return buf - begin;
13498     }
13499 }
13500
13501 static void
13502 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
13503 {
13504   switch (lang)
13505     {
13506     case DW_LANG_C89:
13507     case DW_LANG_C99:
13508     case DW_LANG_C:
13509       cu->language = language_c;
13510       break;
13511     case DW_LANG_C_plus_plus:
13512       cu->language = language_cplus;
13513       break;
13514     case DW_LANG_D:
13515       cu->language = language_d;
13516       break;
13517     case DW_LANG_Fortran77:
13518     case DW_LANG_Fortran90:
13519     case DW_LANG_Fortran95:
13520       cu->language = language_fortran;
13521       break;
13522     case DW_LANG_Go:
13523       cu->language = language_go;
13524       break;
13525     case DW_LANG_Mips_Assembler:
13526       cu->language = language_asm;
13527       break;
13528     case DW_LANG_Java:
13529       cu->language = language_java;
13530       break;
13531     case DW_LANG_Ada83:
13532     case DW_LANG_Ada95:
13533       cu->language = language_ada;
13534       break;
13535     case DW_LANG_Modula2:
13536       cu->language = language_m2;
13537       break;
13538     case DW_LANG_Pascal83:
13539       cu->language = language_pascal;
13540       break;
13541     case DW_LANG_ObjC:
13542       cu->language = language_objc;
13543       break;
13544     case DW_LANG_Cobol74:
13545     case DW_LANG_Cobol85:
13546     default:
13547       cu->language = language_minimal;
13548       break;
13549     }
13550   cu->language_defn = language_def (cu->language);
13551 }
13552
13553 /* Return the named attribute or NULL if not there.  */
13554
13555 static struct attribute *
13556 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
13557 {
13558   for (;;)
13559     {
13560       unsigned int i;
13561       struct attribute *spec = NULL;
13562
13563       for (i = 0; i < die->num_attrs; ++i)
13564         {
13565           if (die->attrs[i].name == name)
13566             return &die->attrs[i];
13567           if (die->attrs[i].name == DW_AT_specification
13568               || die->attrs[i].name == DW_AT_abstract_origin)
13569             spec = &die->attrs[i];
13570         }
13571
13572       if (!spec)
13573         break;
13574
13575       die = follow_die_ref (die, spec, &cu);
13576     }
13577
13578   return NULL;
13579 }
13580
13581 /* Return the named attribute or NULL if not there,
13582    but do not follow DW_AT_specification, etc.
13583    This is for use in contexts where we're reading .debug_types dies.
13584    Following DW_AT_specification, DW_AT_abstract_origin will take us
13585    back up the chain, and we want to go down.  */
13586
13587 static struct attribute *
13588 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
13589 {
13590   unsigned int i;
13591
13592   for (i = 0; i < die->num_attrs; ++i)
13593     if (die->attrs[i].name == name)
13594       return &die->attrs[i];
13595
13596   return NULL;
13597 }
13598
13599 /* Return non-zero iff the attribute NAME is defined for the given DIE,
13600    and holds a non-zero value.  This function should only be used for
13601    DW_FORM_flag or DW_FORM_flag_present attributes.  */
13602
13603 static int
13604 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
13605 {
13606   struct attribute *attr = dwarf2_attr (die, name, cu);
13607
13608   return (attr && DW_UNSND (attr));
13609 }
13610
13611 static int
13612 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
13613 {
13614   /* A DIE is a declaration if it has a DW_AT_declaration attribute
13615      which value is non-zero.  However, we have to be careful with
13616      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
13617      (via dwarf2_flag_true_p) follows this attribute.  So we may
13618      end up accidently finding a declaration attribute that belongs
13619      to a different DIE referenced by the specification attribute,
13620      even though the given DIE does not have a declaration attribute.  */
13621   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
13622           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
13623 }
13624
13625 /* Return the die giving the specification for DIE, if there is
13626    one.  *SPEC_CU is the CU containing DIE on input, and the CU
13627    containing the return value on output.  If there is no
13628    specification, but there is an abstract origin, that is
13629    returned.  */
13630
13631 static struct die_info *
13632 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
13633 {
13634   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
13635                                              *spec_cu);
13636
13637   if (spec_attr == NULL)
13638     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
13639
13640   if (spec_attr == NULL)
13641     return NULL;
13642   else
13643     return follow_die_ref (die, spec_attr, spec_cu);
13644 }
13645
13646 /* Free the line_header structure *LH, and any arrays and strings it
13647    refers to.
13648    NOTE: This is also used as a "cleanup" function.  */
13649
13650 static void
13651 free_line_header (struct line_header *lh)
13652 {
13653   if (lh->standard_opcode_lengths)
13654     xfree (lh->standard_opcode_lengths);
13655
13656   /* Remember that all the lh->file_names[i].name pointers are
13657      pointers into debug_line_buffer, and don't need to be freed.  */
13658   if (lh->file_names)
13659     xfree (lh->file_names);
13660
13661   /* Similarly for the include directory names.  */
13662   if (lh->include_dirs)
13663     xfree (lh->include_dirs);
13664
13665   xfree (lh);
13666 }
13667
13668 /* Add an entry to LH's include directory table.  */
13669
13670 static void
13671 add_include_dir (struct line_header *lh, char *include_dir)
13672 {
13673   /* Grow the array if necessary.  */
13674   if (lh->include_dirs_size == 0)
13675     {
13676       lh->include_dirs_size = 1; /* for testing */
13677       lh->include_dirs = xmalloc (lh->include_dirs_size
13678                                   * sizeof (*lh->include_dirs));
13679     }
13680   else if (lh->num_include_dirs >= lh->include_dirs_size)
13681     {
13682       lh->include_dirs_size *= 2;
13683       lh->include_dirs = xrealloc (lh->include_dirs,
13684                                    (lh->include_dirs_size
13685                                     * sizeof (*lh->include_dirs)));
13686     }
13687
13688   lh->include_dirs[lh->num_include_dirs++] = include_dir;
13689 }
13690
13691 /* Add an entry to LH's file name table.  */
13692
13693 static void
13694 add_file_name (struct line_header *lh,
13695                char *name,
13696                unsigned int dir_index,
13697                unsigned int mod_time,
13698                unsigned int length)
13699 {
13700   struct file_entry *fe;
13701
13702   /* Grow the array if necessary.  */
13703   if (lh->file_names_size == 0)
13704     {
13705       lh->file_names_size = 1; /* for testing */
13706       lh->file_names = xmalloc (lh->file_names_size
13707                                 * sizeof (*lh->file_names));
13708     }
13709   else if (lh->num_file_names >= lh->file_names_size)
13710     {
13711       lh->file_names_size *= 2;
13712       lh->file_names = xrealloc (lh->file_names,
13713                                  (lh->file_names_size
13714                                   * sizeof (*lh->file_names)));
13715     }
13716
13717   fe = &lh->file_names[lh->num_file_names++];
13718   fe->name = name;
13719   fe->dir_index = dir_index;
13720   fe->mod_time = mod_time;
13721   fe->length = length;
13722   fe->included_p = 0;
13723   fe->symtab = NULL;
13724 }
13725
13726 /* Read the statement program header starting at OFFSET in
13727    .debug_line, or .debug_line.dwo.  Return a pointer
13728    to a struct line_header, allocated using xmalloc.
13729
13730    NOTE: the strings in the include directory and file name tables of
13731    the returned object point into the dwarf line section buffer,
13732    and must not be freed.  */
13733
13734 static struct line_header *
13735 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
13736 {
13737   struct cleanup *back_to;
13738   struct line_header *lh;
13739   gdb_byte *line_ptr;
13740   unsigned int bytes_read, offset_size;
13741   int i;
13742   char *cur_dir, *cur_file;
13743   struct dwarf2_section_info *section;
13744   bfd *abfd;
13745
13746   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
13747      DWO file.  */
13748   if (cu->dwo_unit && cu->per_cu->is_debug_types)
13749     section = &cu->dwo_unit->dwo_file->sections.line;
13750   else
13751     section = &dwarf2_per_objfile->line;
13752
13753   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
13754   if (section->buffer == NULL)
13755     {
13756       if (cu->dwo_unit && cu->per_cu->is_debug_types)
13757         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
13758       else
13759         complaint (&symfile_complaints, _("missing .debug_line section"));
13760       return 0;
13761     }
13762
13763   /* We can't do this until we know the section is non-empty.
13764      Only then do we know we have such a section.  */
13765   abfd = section->asection->owner;
13766
13767   /* Make sure that at least there's room for the total_length field.
13768      That could be 12 bytes long, but we're just going to fudge that.  */
13769   if (offset + 4 >= section->size)
13770     {
13771       dwarf2_statement_list_fits_in_line_number_section_complaint ();
13772       return 0;
13773     }
13774
13775   lh = xmalloc (sizeof (*lh));
13776   memset (lh, 0, sizeof (*lh));
13777   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
13778                           (void *) lh);
13779
13780   line_ptr = section->buffer + offset;
13781
13782   /* Read in the header.  */
13783   lh->total_length =
13784     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
13785                                             &bytes_read, &offset_size);
13786   line_ptr += bytes_read;
13787   if (line_ptr + lh->total_length > (section->buffer + section->size))
13788     {
13789       dwarf2_statement_list_fits_in_line_number_section_complaint ();
13790       return 0;
13791     }
13792   lh->statement_program_end = line_ptr + lh->total_length;
13793   lh->version = read_2_bytes (abfd, line_ptr);
13794   line_ptr += 2;
13795   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
13796   line_ptr += offset_size;
13797   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
13798   line_ptr += 1;
13799   if (lh->version >= 4)
13800     {
13801       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
13802       line_ptr += 1;
13803     }
13804   else
13805     lh->maximum_ops_per_instruction = 1;
13806
13807   if (lh->maximum_ops_per_instruction == 0)
13808     {
13809       lh->maximum_ops_per_instruction = 1;
13810       complaint (&symfile_complaints,
13811                  _("invalid maximum_ops_per_instruction "
13812                    "in `.debug_line' section"));
13813     }
13814
13815   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
13816   line_ptr += 1;
13817   lh->line_base = read_1_signed_byte (abfd, line_ptr);
13818   line_ptr += 1;
13819   lh->line_range = read_1_byte (abfd, line_ptr);
13820   line_ptr += 1;
13821   lh->opcode_base = read_1_byte (abfd, line_ptr);
13822   line_ptr += 1;
13823   lh->standard_opcode_lengths
13824     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
13825
13826   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
13827   for (i = 1; i < lh->opcode_base; ++i)
13828     {
13829       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
13830       line_ptr += 1;
13831     }
13832
13833   /* Read directory table.  */
13834   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
13835     {
13836       line_ptr += bytes_read;
13837       add_include_dir (lh, cur_dir);
13838     }
13839   line_ptr += bytes_read;
13840
13841   /* Read file name table.  */
13842   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
13843     {
13844       unsigned int dir_index, mod_time, length;
13845
13846       line_ptr += bytes_read;
13847       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13848       line_ptr += bytes_read;
13849       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13850       line_ptr += bytes_read;
13851       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13852       line_ptr += bytes_read;
13853
13854       add_file_name (lh, cur_file, dir_index, mod_time, length);
13855     }
13856   line_ptr += bytes_read;
13857   lh->statement_program_start = line_ptr;
13858
13859   if (line_ptr > (section->buffer + section->size))
13860     complaint (&symfile_complaints,
13861                _("line number info header doesn't "
13862                  "fit in `.debug_line' section"));
13863
13864   discard_cleanups (back_to);
13865   return lh;
13866 }
13867
13868 /* Subroutine of dwarf_decode_lines to simplify it.
13869    Return the file name of the psymtab for included file FILE_INDEX
13870    in line header LH of PST.
13871    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
13872    If space for the result is malloc'd, it will be freed by a cleanup.
13873    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
13874
13875 static char *
13876 psymtab_include_file_name (const struct line_header *lh, int file_index,
13877                            const struct partial_symtab *pst,
13878                            const char *comp_dir)
13879 {
13880   const struct file_entry fe = lh->file_names [file_index];
13881   char *include_name = fe.name;
13882   char *include_name_to_compare = include_name;
13883   char *dir_name = NULL;
13884   const char *pst_filename;
13885   char *copied_name = NULL;
13886   int file_is_pst;
13887
13888   if (fe.dir_index)
13889     dir_name = lh->include_dirs[fe.dir_index - 1];
13890
13891   if (!IS_ABSOLUTE_PATH (include_name)
13892       && (dir_name != NULL || comp_dir != NULL))
13893     {
13894       /* Avoid creating a duplicate psymtab for PST.
13895          We do this by comparing INCLUDE_NAME and PST_FILENAME.
13896          Before we do the comparison, however, we need to account
13897          for DIR_NAME and COMP_DIR.
13898          First prepend dir_name (if non-NULL).  If we still don't
13899          have an absolute path prepend comp_dir (if non-NULL).
13900          However, the directory we record in the include-file's
13901          psymtab does not contain COMP_DIR (to match the
13902          corresponding symtab(s)).
13903
13904          Example:
13905
13906          bash$ cd /tmp
13907          bash$ gcc -g ./hello.c
13908          include_name = "hello.c"
13909          dir_name = "."
13910          DW_AT_comp_dir = comp_dir = "/tmp"
13911          DW_AT_name = "./hello.c"  */
13912
13913       if (dir_name != NULL)
13914         {
13915           include_name = concat (dir_name, SLASH_STRING,
13916                                  include_name, (char *)NULL);
13917           include_name_to_compare = include_name;
13918           make_cleanup (xfree, include_name);
13919         }
13920       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
13921         {
13922           include_name_to_compare = concat (comp_dir, SLASH_STRING,
13923                                             include_name, (char *)NULL);
13924         }
13925     }
13926
13927   pst_filename = pst->filename;
13928   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
13929     {
13930       copied_name = concat (pst->dirname, SLASH_STRING,
13931                             pst_filename, (char *)NULL);
13932       pst_filename = copied_name;
13933     }
13934
13935   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
13936
13937   if (include_name_to_compare != include_name)
13938     xfree (include_name_to_compare);
13939   if (copied_name != NULL)
13940     xfree (copied_name);
13941
13942   if (file_is_pst)
13943     return NULL;
13944   return include_name;
13945 }
13946
13947 /* Ignore this record_line request.  */
13948
13949 static void
13950 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
13951 {
13952   return;
13953 }
13954
13955 /* Subroutine of dwarf_decode_lines to simplify it.
13956    Process the line number information in LH.  */
13957
13958 static void
13959 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
13960                       struct dwarf2_cu *cu, struct partial_symtab *pst)
13961 {
13962   gdb_byte *line_ptr, *extended_end;
13963   gdb_byte *line_end;
13964   unsigned int bytes_read, extended_len;
13965   unsigned char op_code, extended_op, adj_opcode;
13966   CORE_ADDR baseaddr;
13967   struct objfile *objfile = cu->objfile;
13968   bfd *abfd = objfile->obfd;
13969   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13970   const int decode_for_pst_p = (pst != NULL);
13971   struct subfile *last_subfile = NULL;
13972   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
13973     = record_line;
13974
13975   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13976
13977   line_ptr = lh->statement_program_start;
13978   line_end = lh->statement_program_end;
13979
13980   /* Read the statement sequences until there's nothing left.  */
13981   while (line_ptr < line_end)
13982     {
13983       /* state machine registers  */
13984       CORE_ADDR address = 0;
13985       unsigned int file = 1;
13986       unsigned int line = 1;
13987       unsigned int column = 0;
13988       int is_stmt = lh->default_is_stmt;
13989       int basic_block = 0;
13990       int end_sequence = 0;
13991       CORE_ADDR addr;
13992       unsigned char op_index = 0;
13993
13994       if (!decode_for_pst_p && lh->num_file_names >= file)
13995         {
13996           /* Start a subfile for the current file of the state machine.  */
13997           /* lh->include_dirs and lh->file_names are 0-based, but the
13998              directory and file name numbers in the statement program
13999              are 1-based.  */
14000           struct file_entry *fe = &lh->file_names[file - 1];
14001           char *dir = NULL;
14002
14003           if (fe->dir_index)
14004             dir = lh->include_dirs[fe->dir_index - 1];
14005
14006           dwarf2_start_subfile (fe->name, dir, comp_dir);
14007         }
14008
14009       /* Decode the table.  */
14010       while (!end_sequence)
14011         {
14012           op_code = read_1_byte (abfd, line_ptr);
14013           line_ptr += 1;
14014           if (line_ptr > line_end)
14015             {
14016               dwarf2_debug_line_missing_end_sequence_complaint ();
14017               break;
14018             }
14019
14020           if (op_code >= lh->opcode_base)
14021             {
14022               /* Special operand.  */
14023               adj_opcode = op_code - lh->opcode_base;
14024               address += (((op_index + (adj_opcode / lh->line_range))
14025                            / lh->maximum_ops_per_instruction)
14026                           * lh->minimum_instruction_length);
14027               op_index = ((op_index + (adj_opcode / lh->line_range))
14028                           % lh->maximum_ops_per_instruction);
14029               line += lh->line_base + (adj_opcode % lh->line_range);
14030               if (lh->num_file_names < file || file == 0)
14031                 dwarf2_debug_line_missing_file_complaint ();
14032               /* For now we ignore lines not starting on an
14033                  instruction boundary.  */
14034               else if (op_index == 0)
14035                 {
14036                   lh->file_names[file - 1].included_p = 1;
14037                   if (!decode_for_pst_p && is_stmt)
14038                     {
14039                       if (last_subfile != current_subfile)
14040                         {
14041                           addr = gdbarch_addr_bits_remove (gdbarch, address);
14042                           if (last_subfile)
14043                             (*p_record_line) (last_subfile, 0, addr);
14044                           last_subfile = current_subfile;
14045                         }
14046                       /* Append row to matrix using current values.  */
14047                       addr = gdbarch_addr_bits_remove (gdbarch, address);
14048                       (*p_record_line) (current_subfile, line, addr);
14049                     }
14050                 }
14051               basic_block = 0;
14052             }
14053           else switch (op_code)
14054             {
14055             case DW_LNS_extended_op:
14056               extended_len = read_unsigned_leb128 (abfd, line_ptr,
14057                                                    &bytes_read);
14058               line_ptr += bytes_read;
14059               extended_end = line_ptr + extended_len;
14060               extended_op = read_1_byte (abfd, line_ptr);
14061               line_ptr += 1;
14062               switch (extended_op)
14063                 {
14064                 case DW_LNE_end_sequence:
14065                   p_record_line = record_line;
14066                   end_sequence = 1;
14067                   break;
14068                 case DW_LNE_set_address:
14069                   address = read_address (abfd, line_ptr, cu, &bytes_read);
14070
14071                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
14072                     {
14073                       /* This line table is for a function which has been
14074                          GCd by the linker.  Ignore it.  PR gdb/12528 */
14075
14076                       long line_offset
14077                         = line_ptr - dwarf2_per_objfile->line.buffer;
14078
14079                       complaint (&symfile_complaints,
14080                                  _(".debug_line address at offset 0x%lx is 0 "
14081                                    "[in module %s]"),
14082                                  line_offset, objfile->name);
14083                       p_record_line = noop_record_line;
14084                     }
14085
14086                   op_index = 0;
14087                   line_ptr += bytes_read;
14088                   address += baseaddr;
14089                   break;
14090                 case DW_LNE_define_file:
14091                   {
14092                     char *cur_file;
14093                     unsigned int dir_index, mod_time, length;
14094
14095                     cur_file = read_direct_string (abfd, line_ptr,
14096                                                    &bytes_read);
14097                     line_ptr += bytes_read;
14098                     dir_index =
14099                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14100                     line_ptr += bytes_read;
14101                     mod_time =
14102                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14103                     line_ptr += bytes_read;
14104                     length =
14105                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14106                     line_ptr += bytes_read;
14107                     add_file_name (lh, cur_file, dir_index, mod_time, length);
14108                   }
14109                   break;
14110                 case DW_LNE_set_discriminator:
14111                   /* The discriminator is not interesting to the debugger;
14112                      just ignore it.  */
14113                   line_ptr = extended_end;
14114                   break;
14115                 default:
14116                   complaint (&symfile_complaints,
14117                              _("mangled .debug_line section"));
14118                   return;
14119                 }
14120               /* Make sure that we parsed the extended op correctly.  If e.g.
14121                  we expected a different address size than the producer used,
14122                  we may have read the wrong number of bytes.  */
14123               if (line_ptr != extended_end)
14124                 {
14125                   complaint (&symfile_complaints,
14126                              _("mangled .debug_line section"));
14127                   return;
14128                 }
14129               break;
14130             case DW_LNS_copy:
14131               if (lh->num_file_names < file || file == 0)
14132                 dwarf2_debug_line_missing_file_complaint ();
14133               else
14134                 {
14135                   lh->file_names[file - 1].included_p = 1;
14136                   if (!decode_for_pst_p && is_stmt)
14137                     {
14138                       if (last_subfile != current_subfile)
14139                         {
14140                           addr = gdbarch_addr_bits_remove (gdbarch, address);
14141                           if (last_subfile)
14142                             (*p_record_line) (last_subfile, 0, addr);
14143                           last_subfile = current_subfile;
14144                         }
14145                       addr = gdbarch_addr_bits_remove (gdbarch, address);
14146                       (*p_record_line) (current_subfile, line, addr);
14147                     }
14148                 }
14149               basic_block = 0;
14150               break;
14151             case DW_LNS_advance_pc:
14152               {
14153                 CORE_ADDR adjust
14154                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14155
14156                 address += (((op_index + adjust)
14157                              / lh->maximum_ops_per_instruction)
14158                             * lh->minimum_instruction_length);
14159                 op_index = ((op_index + adjust)
14160                             % lh->maximum_ops_per_instruction);
14161                 line_ptr += bytes_read;
14162               }
14163               break;
14164             case DW_LNS_advance_line:
14165               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
14166               line_ptr += bytes_read;
14167               break;
14168             case DW_LNS_set_file:
14169               {
14170                 /* The arrays lh->include_dirs and lh->file_names are
14171                    0-based, but the directory and file name numbers in
14172                    the statement program are 1-based.  */
14173                 struct file_entry *fe;
14174                 char *dir = NULL;
14175
14176                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14177                 line_ptr += bytes_read;
14178                 if (lh->num_file_names < file || file == 0)
14179                   dwarf2_debug_line_missing_file_complaint ();
14180                 else
14181                   {
14182                     fe = &lh->file_names[file - 1];
14183                     if (fe->dir_index)
14184                       dir = lh->include_dirs[fe->dir_index - 1];
14185                     if (!decode_for_pst_p)
14186                       {
14187                         last_subfile = current_subfile;
14188                         dwarf2_start_subfile (fe->name, dir, comp_dir);
14189                       }
14190                   }
14191               }
14192               break;
14193             case DW_LNS_set_column:
14194               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14195               line_ptr += bytes_read;
14196               break;
14197             case DW_LNS_negate_stmt:
14198               is_stmt = (!is_stmt);
14199               break;
14200             case DW_LNS_set_basic_block:
14201               basic_block = 1;
14202               break;
14203             /* Add to the address register of the state machine the
14204                address increment value corresponding to special opcode
14205                255.  I.e., this value is scaled by the minimum
14206                instruction length since special opcode 255 would have
14207                scaled the increment.  */
14208             case DW_LNS_const_add_pc:
14209               {
14210                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
14211
14212                 address += (((op_index + adjust)
14213                              / lh->maximum_ops_per_instruction)
14214                             * lh->minimum_instruction_length);
14215                 op_index = ((op_index + adjust)
14216                             % lh->maximum_ops_per_instruction);
14217               }
14218               break;
14219             case DW_LNS_fixed_advance_pc:
14220               address += read_2_bytes (abfd, line_ptr);
14221               op_index = 0;
14222               line_ptr += 2;
14223               break;
14224             default:
14225               {
14226                 /* Unknown standard opcode, ignore it.  */
14227                 int i;
14228
14229                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
14230                   {
14231                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14232                     line_ptr += bytes_read;
14233                   }
14234               }
14235             }
14236         }
14237       if (lh->num_file_names < file || file == 0)
14238         dwarf2_debug_line_missing_file_complaint ();
14239       else
14240         {
14241           lh->file_names[file - 1].included_p = 1;
14242           if (!decode_for_pst_p)
14243             {
14244               addr = gdbarch_addr_bits_remove (gdbarch, address);
14245               (*p_record_line) (current_subfile, 0, addr);
14246             }
14247         }
14248     }
14249 }
14250
14251 /* Decode the Line Number Program (LNP) for the given line_header
14252    structure and CU.  The actual information extracted and the type
14253    of structures created from the LNP depends on the value of PST.
14254
14255    1. If PST is NULL, then this procedure uses the data from the program
14256       to create all necessary symbol tables, and their linetables.
14257
14258    2. If PST is not NULL, this procedure reads the program to determine
14259       the list of files included by the unit represented by PST, and
14260       builds all the associated partial symbol tables.
14261
14262    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
14263    It is used for relative paths in the line table.
14264    NOTE: When processing partial symtabs (pst != NULL),
14265    comp_dir == pst->dirname.
14266
14267    NOTE: It is important that psymtabs have the same file name (via strcmp)
14268    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
14269    symtab we don't use it in the name of the psymtabs we create.
14270    E.g. expand_line_sal requires this when finding psymtabs to expand.
14271    A good testcase for this is mb-inline.exp.  */
14272
14273 static void
14274 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
14275                     struct dwarf2_cu *cu, struct partial_symtab *pst,
14276                     int want_line_info)
14277 {
14278   struct objfile *objfile = cu->objfile;
14279   const int decode_for_pst_p = (pst != NULL);
14280   struct subfile *first_subfile = current_subfile;
14281
14282   if (want_line_info)
14283     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
14284
14285   if (decode_for_pst_p)
14286     {
14287       int file_index;
14288
14289       /* Now that we're done scanning the Line Header Program, we can
14290          create the psymtab of each included file.  */
14291       for (file_index = 0; file_index < lh->num_file_names; file_index++)
14292         if (lh->file_names[file_index].included_p == 1)
14293           {
14294             char *include_name =
14295               psymtab_include_file_name (lh, file_index, pst, comp_dir);
14296             if (include_name != NULL)
14297               dwarf2_create_include_psymtab (include_name, pst, objfile);
14298           }
14299     }
14300   else
14301     {
14302       /* Make sure a symtab is created for every file, even files
14303          which contain only variables (i.e. no code with associated
14304          line numbers).  */
14305       int i;
14306
14307       for (i = 0; i < lh->num_file_names; i++)
14308         {
14309           char *dir = NULL;
14310           struct file_entry *fe;
14311
14312           fe = &lh->file_names[i];
14313           if (fe->dir_index)
14314             dir = lh->include_dirs[fe->dir_index - 1];
14315           dwarf2_start_subfile (fe->name, dir, comp_dir);
14316
14317           /* Skip the main file; we don't need it, and it must be
14318              allocated last, so that it will show up before the
14319              non-primary symtabs in the objfile's symtab list.  */
14320           if (current_subfile == first_subfile)
14321             continue;
14322
14323           if (current_subfile->symtab == NULL)
14324             current_subfile->symtab = allocate_symtab (current_subfile->name,
14325                                                        objfile);
14326           fe->symtab = current_subfile->symtab;
14327         }
14328     }
14329 }
14330
14331 /* Start a subfile for DWARF.  FILENAME is the name of the file and
14332    DIRNAME the name of the source directory which contains FILENAME
14333    or NULL if not known.  COMP_DIR is the compilation directory for the
14334    linetable's compilation unit or NULL if not known.
14335    This routine tries to keep line numbers from identical absolute and
14336    relative file names in a common subfile.
14337
14338    Using the `list' example from the GDB testsuite, which resides in
14339    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
14340    of /srcdir/list0.c yields the following debugging information for list0.c:
14341
14342    DW_AT_name:          /srcdir/list0.c
14343    DW_AT_comp_dir:              /compdir
14344    files.files[0].name: list0.h
14345    files.files[0].dir:  /srcdir
14346    files.files[1].name: list0.c
14347    files.files[1].dir:  /srcdir
14348
14349    The line number information for list0.c has to end up in a single
14350    subfile, so that `break /srcdir/list0.c:1' works as expected.
14351    start_subfile will ensure that this happens provided that we pass the
14352    concatenation of files.files[1].dir and files.files[1].name as the
14353    subfile's name.  */
14354
14355 static void
14356 dwarf2_start_subfile (char *filename, const char *dirname,
14357                       const char *comp_dir)
14358 {
14359   char *fullname;
14360
14361   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
14362      `start_symtab' will always pass the contents of DW_AT_comp_dir as
14363      second argument to start_subfile.  To be consistent, we do the
14364      same here.  In order not to lose the line information directory,
14365      we concatenate it to the filename when it makes sense.
14366      Note that the Dwarf3 standard says (speaking of filenames in line
14367      information): ``The directory index is ignored for file names
14368      that represent full path names''.  Thus ignoring dirname in the
14369      `else' branch below isn't an issue.  */
14370
14371   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
14372     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
14373   else
14374     fullname = filename;
14375
14376   start_subfile (fullname, comp_dir);
14377
14378   if (fullname != filename)
14379     xfree (fullname);
14380 }
14381
14382 /* Start a symtab for DWARF.
14383    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
14384
14385 static void
14386 dwarf2_start_symtab (struct dwarf2_cu *cu,
14387                      char *name, char *comp_dir, CORE_ADDR low_pc)
14388 {
14389   start_symtab (name, comp_dir, low_pc);
14390   record_debugformat ("DWARF 2");
14391   record_producer (cu->producer);
14392
14393   /* We assume that we're processing GCC output.  */
14394   processing_gcc_compilation = 2;
14395
14396   processing_has_namespace_info = 0;
14397 }
14398
14399 static void
14400 var_decode_location (struct attribute *attr, struct symbol *sym,
14401                      struct dwarf2_cu *cu)
14402 {
14403   struct objfile *objfile = cu->objfile;
14404   struct comp_unit_head *cu_header = &cu->header;
14405
14406   /* NOTE drow/2003-01-30: There used to be a comment and some special
14407      code here to turn a symbol with DW_AT_external and a
14408      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
14409      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
14410      with some versions of binutils) where shared libraries could have
14411      relocations against symbols in their debug information - the
14412      minimal symbol would have the right address, but the debug info
14413      would not.  It's no longer necessary, because we will explicitly
14414      apply relocations when we read in the debug information now.  */
14415
14416   /* A DW_AT_location attribute with no contents indicates that a
14417      variable has been optimized away.  */
14418   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
14419     {
14420       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
14421       return;
14422     }
14423
14424   /* Handle one degenerate form of location expression specially, to
14425      preserve GDB's previous behavior when section offsets are
14426      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
14427      then mark this symbol as LOC_STATIC.  */
14428
14429   if (attr_form_is_block (attr)
14430       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
14431            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
14432           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
14433               && (DW_BLOCK (attr)->size
14434                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
14435     {
14436       unsigned int dummy;
14437
14438       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
14439         SYMBOL_VALUE_ADDRESS (sym) =
14440           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
14441       else
14442         SYMBOL_VALUE_ADDRESS (sym) =
14443           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
14444       SYMBOL_CLASS (sym) = LOC_STATIC;
14445       fixup_symbol_section (sym, objfile);
14446       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
14447                                               SYMBOL_SECTION (sym));
14448       return;
14449     }
14450
14451   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
14452      expression evaluator, and use LOC_COMPUTED only when necessary
14453      (i.e. when the value of a register or memory location is
14454      referenced, or a thread-local block, etc.).  Then again, it might
14455      not be worthwhile.  I'm assuming that it isn't unless performance
14456      or memory numbers show me otherwise.  */
14457
14458   dwarf2_symbol_mark_computed (attr, sym, cu);
14459   SYMBOL_CLASS (sym) = LOC_COMPUTED;
14460
14461   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
14462     cu->has_loclist = 1;
14463 }
14464
14465 /* Given a pointer to a DWARF information entry, figure out if we need
14466    to make a symbol table entry for it, and if so, create a new entry
14467    and return a pointer to it.
14468    If TYPE is NULL, determine symbol type from the die, otherwise
14469    used the passed type.
14470    If SPACE is not NULL, use it to hold the new symbol.  If it is
14471    NULL, allocate a new symbol on the objfile's obstack.  */
14472
14473 static struct symbol *
14474 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
14475                  struct symbol *space)
14476 {
14477   struct objfile *objfile = cu->objfile;
14478   struct symbol *sym = NULL;
14479   char *name;
14480   struct attribute *attr = NULL;
14481   struct attribute *attr2 = NULL;
14482   CORE_ADDR baseaddr;
14483   struct pending **list_to_add = NULL;
14484
14485   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
14486
14487   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14488
14489   name = dwarf2_name (die, cu);
14490   if (name)
14491     {
14492       const char *linkagename;
14493       int suppress_add = 0;
14494
14495       if (space)
14496         sym = space;
14497       else
14498         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
14499       OBJSTAT (objfile, n_syms++);
14500
14501       /* Cache this symbol's name and the name's demangled form (if any).  */
14502       SYMBOL_SET_LANGUAGE (sym, cu->language);
14503       linkagename = dwarf2_physname (name, die, cu);
14504       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
14505
14506       /* Fortran does not have mangling standard and the mangling does differ
14507          between gfortran, iFort etc.  */
14508       if (cu->language == language_fortran
14509           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
14510         symbol_set_demangled_name (&(sym->ginfo),
14511                                    (char *) dwarf2_full_name (name, die, cu),
14512                                    NULL);
14513
14514       /* Default assumptions.
14515          Use the passed type or decode it from the die.  */
14516       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
14517       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
14518       if (type != NULL)
14519         SYMBOL_TYPE (sym) = type;
14520       else
14521         SYMBOL_TYPE (sym) = die_type (die, cu);
14522       attr = dwarf2_attr (die,
14523                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
14524                           cu);
14525       if (attr)
14526         {
14527           SYMBOL_LINE (sym) = DW_UNSND (attr);
14528         }
14529
14530       attr = dwarf2_attr (die,
14531                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
14532                           cu);
14533       if (attr)
14534         {
14535           int file_index = DW_UNSND (attr);
14536
14537           if (cu->line_header == NULL
14538               || file_index > cu->line_header->num_file_names)
14539             complaint (&symfile_complaints,
14540                        _("file index out of range"));
14541           else if (file_index > 0)
14542             {
14543               struct file_entry *fe;
14544
14545               fe = &cu->line_header->file_names[file_index - 1];
14546               SYMBOL_SYMTAB (sym) = fe->symtab;
14547             }
14548         }
14549
14550       switch (die->tag)
14551         {
14552         case DW_TAG_label:
14553           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14554           if (attr)
14555             {
14556               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
14557             }
14558           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
14559           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
14560           SYMBOL_CLASS (sym) = LOC_LABEL;
14561           add_symbol_to_list (sym, cu->list_in_scope);
14562           break;
14563         case DW_TAG_subprogram:
14564           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
14565              finish_block.  */
14566           SYMBOL_CLASS (sym) = LOC_BLOCK;
14567           attr2 = dwarf2_attr (die, DW_AT_external, cu);
14568           if ((attr2 && (DW_UNSND (attr2) != 0))
14569               || cu->language == language_ada)
14570             {
14571               /* Subprograms marked external are stored as a global symbol.
14572                  Ada subprograms, whether marked external or not, are always
14573                  stored as a global symbol, because we want to be able to
14574                  access them globally.  For instance, we want to be able
14575                  to break on a nested subprogram without having to
14576                  specify the context.  */
14577               list_to_add = &global_symbols;
14578             }
14579           else
14580             {
14581               list_to_add = cu->list_in_scope;
14582             }
14583           break;
14584         case DW_TAG_inlined_subroutine:
14585           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
14586              finish_block.  */
14587           SYMBOL_CLASS (sym) = LOC_BLOCK;
14588           SYMBOL_INLINED (sym) = 1;
14589           list_to_add = cu->list_in_scope;
14590           break;
14591         case DW_TAG_template_value_param:
14592           suppress_add = 1;
14593           /* Fall through.  */
14594         case DW_TAG_constant:
14595         case DW_TAG_variable:
14596         case DW_TAG_member:
14597           /* Compilation with minimal debug info may result in
14598              variables with missing type entries.  Change the
14599              misleading `void' type to something sensible.  */
14600           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
14601             SYMBOL_TYPE (sym)
14602               = objfile_type (objfile)->nodebug_data_symbol;
14603
14604           attr = dwarf2_attr (die, DW_AT_const_value, cu);
14605           /* In the case of DW_TAG_member, we should only be called for
14606              static const members.  */
14607           if (die->tag == DW_TAG_member)
14608             {
14609               /* dwarf2_add_field uses die_is_declaration,
14610                  so we do the same.  */
14611               gdb_assert (die_is_declaration (die, cu));
14612               gdb_assert (attr);
14613             }
14614           if (attr)
14615             {
14616               dwarf2_const_value (attr, sym, cu);
14617               attr2 = dwarf2_attr (die, DW_AT_external, cu);
14618               if (!suppress_add)
14619                 {
14620                   if (attr2 && (DW_UNSND (attr2) != 0))
14621                     list_to_add = &global_symbols;
14622                   else
14623                     list_to_add = cu->list_in_scope;
14624                 }
14625               break;
14626             }
14627           attr = dwarf2_attr (die, DW_AT_location, cu);
14628           if (attr)
14629             {
14630               var_decode_location (attr, sym, cu);
14631               attr2 = dwarf2_attr (die, DW_AT_external, cu);
14632               if (SYMBOL_CLASS (sym) == LOC_STATIC
14633                   && SYMBOL_VALUE_ADDRESS (sym) == 0
14634                   && !dwarf2_per_objfile->has_section_at_zero)
14635                 {
14636                   /* When a static variable is eliminated by the linker,
14637                      the corresponding debug information is not stripped
14638                      out, but the variable address is set to null;
14639                      do not add such variables into symbol table.  */
14640                 }
14641               else if (attr2 && (DW_UNSND (attr2) != 0))
14642                 {
14643                   /* Workaround gfortran PR debug/40040 - it uses
14644                      DW_AT_location for variables in -fPIC libraries which may
14645                      get overriden by other libraries/executable and get
14646                      a different address.  Resolve it by the minimal symbol
14647                      which may come from inferior's executable using copy
14648                      relocation.  Make this workaround only for gfortran as for
14649                      other compilers GDB cannot guess the minimal symbol
14650                      Fortran mangling kind.  */
14651                   if (cu->language == language_fortran && die->parent
14652                       && die->parent->tag == DW_TAG_module
14653                       && cu->producer
14654                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
14655                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
14656
14657                   /* A variable with DW_AT_external is never static,
14658                      but it may be block-scoped.  */
14659                   list_to_add = (cu->list_in_scope == &file_symbols
14660                                  ? &global_symbols : cu->list_in_scope);
14661                 }
14662               else
14663                 list_to_add = cu->list_in_scope;
14664             }
14665           else
14666             {
14667               /* We do not know the address of this symbol.
14668                  If it is an external symbol and we have type information
14669                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
14670                  The address of the variable will then be determined from
14671                  the minimal symbol table whenever the variable is
14672                  referenced.  */
14673               attr2 = dwarf2_attr (die, DW_AT_external, cu);
14674               if (attr2 && (DW_UNSND (attr2) != 0)
14675                   && dwarf2_attr (die, DW_AT_type, cu) != NULL)
14676                 {
14677                   /* A variable with DW_AT_external is never static, but it
14678                      may be block-scoped.  */
14679                   list_to_add = (cu->list_in_scope == &file_symbols
14680                                  ? &global_symbols : cu->list_in_scope);
14681
14682                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
14683                 }
14684               else if (!die_is_declaration (die, cu))
14685                 {
14686                   /* Use the default LOC_OPTIMIZED_OUT class.  */
14687                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
14688                   if (!suppress_add)
14689                     list_to_add = cu->list_in_scope;
14690                 }
14691             }
14692           break;
14693         case DW_TAG_formal_parameter:
14694           /* If we are inside a function, mark this as an argument.  If
14695              not, we might be looking at an argument to an inlined function
14696              when we do not have enough information to show inlined frames;
14697              pretend it's a local variable in that case so that the user can
14698              still see it.  */
14699           if (context_stack_depth > 0
14700               && context_stack[context_stack_depth - 1].name != NULL)
14701             SYMBOL_IS_ARGUMENT (sym) = 1;
14702           attr = dwarf2_attr (die, DW_AT_location, cu);
14703           if (attr)
14704             {
14705               var_decode_location (attr, sym, cu);
14706             }
14707           attr = dwarf2_attr (die, DW_AT_const_value, cu);
14708           if (attr)
14709             {
14710               dwarf2_const_value (attr, sym, cu);
14711             }
14712
14713           list_to_add = cu->list_in_scope;
14714           break;
14715         case DW_TAG_unspecified_parameters:
14716           /* From varargs functions; gdb doesn't seem to have any
14717              interest in this information, so just ignore it for now.
14718              (FIXME?) */
14719           break;
14720         case DW_TAG_template_type_param:
14721           suppress_add = 1;
14722           /* Fall through.  */
14723         case DW_TAG_class_type:
14724         case DW_TAG_interface_type:
14725         case DW_TAG_structure_type:
14726         case DW_TAG_union_type:
14727         case DW_TAG_set_type:
14728         case DW_TAG_enumeration_type:
14729           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14730           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
14731
14732           {
14733             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
14734                really ever be static objects: otherwise, if you try
14735                to, say, break of a class's method and you're in a file
14736                which doesn't mention that class, it won't work unless
14737                the check for all static symbols in lookup_symbol_aux
14738                saves you.  See the OtherFileClass tests in
14739                gdb.c++/namespace.exp.  */
14740
14741             if (!suppress_add)
14742               {
14743                 list_to_add = (cu->list_in_scope == &file_symbols
14744                                && (cu->language == language_cplus
14745                                    || cu->language == language_java)
14746                                ? &global_symbols : cu->list_in_scope);
14747
14748                 /* The semantics of C++ state that "struct foo {
14749                    ... }" also defines a typedef for "foo".  A Java
14750                    class declaration also defines a typedef for the
14751                    class.  */
14752                 if (cu->language == language_cplus
14753                     || cu->language == language_java
14754                     || cu->language == language_ada)
14755                   {
14756                     /* The symbol's name is already allocated along
14757                        with this objfile, so we don't need to
14758                        duplicate it for the type.  */
14759                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
14760                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
14761                   }
14762               }
14763           }
14764           break;
14765         case DW_TAG_typedef:
14766           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14767           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
14768           list_to_add = cu->list_in_scope;
14769           break;
14770         case DW_TAG_base_type:
14771         case DW_TAG_subrange_type:
14772           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14773           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
14774           list_to_add = cu->list_in_scope;
14775           break;
14776         case DW_TAG_enumerator:
14777           attr = dwarf2_attr (die, DW_AT_const_value, cu);
14778           if (attr)
14779             {
14780               dwarf2_const_value (attr, sym, cu);
14781             }
14782           {
14783             /* NOTE: carlton/2003-11-10: See comment above in the
14784                DW_TAG_class_type, etc. block.  */
14785
14786             list_to_add = (cu->list_in_scope == &file_symbols
14787                            && (cu->language == language_cplus
14788                                || cu->language == language_java)
14789                            ? &global_symbols : cu->list_in_scope);
14790           }
14791           break;
14792         case DW_TAG_namespace:
14793           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
14794           list_to_add = &global_symbols;
14795           break;
14796         default:
14797           /* Not a tag we recognize.  Hopefully we aren't processing
14798              trash data, but since we must specifically ignore things
14799              we don't recognize, there is nothing else we should do at
14800              this point.  */
14801           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
14802                      dwarf_tag_name (die->tag));
14803           break;
14804         }
14805
14806       if (suppress_add)
14807         {
14808           sym->hash_next = objfile->template_symbols;
14809           objfile->template_symbols = sym;
14810           list_to_add = NULL;
14811         }
14812
14813       if (list_to_add != NULL)
14814         add_symbol_to_list (sym, list_to_add);
14815
14816       /* For the benefit of old versions of GCC, check for anonymous
14817          namespaces based on the demangled name.  */
14818       if (!processing_has_namespace_info
14819           && cu->language == language_cplus)
14820         cp_scan_for_anonymous_namespaces (sym, objfile);
14821     }
14822   return (sym);
14823 }
14824
14825 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
14826
14827 static struct symbol *
14828 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
14829 {
14830   return new_symbol_full (die, type, cu, NULL);
14831 }
14832
14833 /* Given an attr with a DW_FORM_dataN value in host byte order,
14834    zero-extend it as appropriate for the symbol's type.  The DWARF
14835    standard (v4) is not entirely clear about the meaning of using
14836    DW_FORM_dataN for a constant with a signed type, where the type is
14837    wider than the data.  The conclusion of a discussion on the DWARF
14838    list was that this is unspecified.  We choose to always zero-extend
14839    because that is the interpretation long in use by GCC.  */
14840
14841 static gdb_byte *
14842 dwarf2_const_value_data (struct attribute *attr, struct type *type,
14843                          const char *name, struct obstack *obstack,
14844                          struct dwarf2_cu *cu, LONGEST *value, int bits)
14845 {
14846   struct objfile *objfile = cu->objfile;
14847   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
14848                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
14849   LONGEST l = DW_UNSND (attr);
14850
14851   if (bits < sizeof (*value) * 8)
14852     {
14853       l &= ((LONGEST) 1 << bits) - 1;
14854       *value = l;
14855     }
14856   else if (bits == sizeof (*value) * 8)
14857     *value = l;
14858   else
14859     {
14860       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
14861       store_unsigned_integer (bytes, bits / 8, byte_order, l);
14862       return bytes;
14863     }
14864
14865   return NULL;
14866 }
14867
14868 /* Read a constant value from an attribute.  Either set *VALUE, or if
14869    the value does not fit in *VALUE, set *BYTES - either already
14870    allocated on the objfile obstack, or newly allocated on OBSTACK,
14871    or, set *BATON, if we translated the constant to a location
14872    expression.  */
14873
14874 static void
14875 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
14876                          const char *name, struct obstack *obstack,
14877                          struct dwarf2_cu *cu,
14878                          LONGEST *value, gdb_byte **bytes,
14879                          struct dwarf2_locexpr_baton **baton)
14880 {
14881   struct objfile *objfile = cu->objfile;
14882   struct comp_unit_head *cu_header = &cu->header;
14883   struct dwarf_block *blk;
14884   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
14885                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
14886
14887   *value = 0;
14888   *bytes = NULL;
14889   *baton = NULL;
14890
14891   switch (attr->form)
14892     {
14893     case DW_FORM_addr:
14894     case DW_FORM_GNU_addr_index:
14895       {
14896         gdb_byte *data;
14897
14898         if (TYPE_LENGTH (type) != cu_header->addr_size)
14899           dwarf2_const_value_length_mismatch_complaint (name,
14900                                                         cu_header->addr_size,
14901                                                         TYPE_LENGTH (type));
14902         /* Symbols of this form are reasonably rare, so we just
14903            piggyback on the existing location code rather than writing
14904            a new implementation of symbol_computed_ops.  */
14905         *baton = obstack_alloc (&objfile->objfile_obstack,
14906                                 sizeof (struct dwarf2_locexpr_baton));
14907         (*baton)->per_cu = cu->per_cu;
14908         gdb_assert ((*baton)->per_cu);
14909
14910         (*baton)->size = 2 + cu_header->addr_size;
14911         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
14912         (*baton)->data = data;
14913
14914         data[0] = DW_OP_addr;
14915         store_unsigned_integer (&data[1], cu_header->addr_size,
14916                                 byte_order, DW_ADDR (attr));
14917         data[cu_header->addr_size + 1] = DW_OP_stack_value;
14918       }
14919       break;
14920     case DW_FORM_string:
14921     case DW_FORM_strp:
14922     case DW_FORM_GNU_str_index:
14923       /* DW_STRING is already allocated on the objfile obstack, point
14924          directly to it.  */
14925       *bytes = (gdb_byte *) DW_STRING (attr);
14926       break;
14927     case DW_FORM_block1:
14928     case DW_FORM_block2:
14929     case DW_FORM_block4:
14930     case DW_FORM_block:
14931     case DW_FORM_exprloc:
14932       blk = DW_BLOCK (attr);
14933       if (TYPE_LENGTH (type) != blk->size)
14934         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
14935                                                       TYPE_LENGTH (type));
14936       *bytes = blk->data;
14937       break;
14938
14939       /* The DW_AT_const_value attributes are supposed to carry the
14940          symbol's value "represented as it would be on the target
14941          architecture."  By the time we get here, it's already been
14942          converted to host endianness, so we just need to sign- or
14943          zero-extend it as appropriate.  */
14944     case DW_FORM_data1:
14945       *bytes = dwarf2_const_value_data (attr, type, name,
14946                                         obstack, cu, value, 8);
14947       break;
14948     case DW_FORM_data2:
14949       *bytes = dwarf2_const_value_data (attr, type, name,
14950                                         obstack, cu, value, 16);
14951       break;
14952     case DW_FORM_data4:
14953       *bytes = dwarf2_const_value_data (attr, type, name,
14954                                         obstack, cu, value, 32);
14955       break;
14956     case DW_FORM_data8:
14957       *bytes = dwarf2_const_value_data (attr, type, name,
14958                                         obstack, cu, value, 64);
14959       break;
14960
14961     case DW_FORM_sdata:
14962       *value = DW_SND (attr);
14963       break;
14964
14965     case DW_FORM_udata:
14966       *value = DW_UNSND (attr);
14967       break;
14968
14969     default:
14970       complaint (&symfile_complaints,
14971                  _("unsupported const value attribute form: '%s'"),
14972                  dwarf_form_name (attr->form));
14973       *value = 0;
14974       break;
14975     }
14976 }
14977
14978
14979 /* Copy constant value from an attribute to a symbol.  */
14980
14981 static void
14982 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
14983                     struct dwarf2_cu *cu)
14984 {
14985   struct objfile *objfile = cu->objfile;
14986   struct comp_unit_head *cu_header = &cu->header;
14987   LONGEST value;
14988   gdb_byte *bytes;
14989   struct dwarf2_locexpr_baton *baton;
14990
14991   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
14992                            SYMBOL_PRINT_NAME (sym),
14993                            &objfile->objfile_obstack, cu,
14994                            &value, &bytes, &baton);
14995
14996   if (baton != NULL)
14997     {
14998       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
14999       SYMBOL_LOCATION_BATON (sym) = baton;
15000       SYMBOL_CLASS (sym) = LOC_COMPUTED;
15001     }
15002   else if (bytes != NULL)
15003      {
15004       SYMBOL_VALUE_BYTES (sym) = bytes;
15005       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
15006     }
15007   else
15008     {
15009       SYMBOL_VALUE (sym) = value;
15010       SYMBOL_CLASS (sym) = LOC_CONST;
15011     }
15012 }
15013
15014 /* Return the type of the die in question using its DW_AT_type attribute.  */
15015
15016 static struct type *
15017 die_type (struct die_info *die, struct dwarf2_cu *cu)
15018 {
15019   struct attribute *type_attr;
15020
15021   type_attr = dwarf2_attr (die, DW_AT_type, cu);
15022   if (!type_attr)
15023     {
15024       /* A missing DW_AT_type represents a void type.  */
15025       return objfile_type (cu->objfile)->builtin_void;
15026     }
15027
15028   return lookup_die_type (die, type_attr, cu);
15029 }
15030
15031 /* True iff CU's producer generates GNAT Ada auxiliary information
15032    that allows to find parallel types through that information instead
15033    of having to do expensive parallel lookups by type name.  */
15034
15035 static int
15036 need_gnat_info (struct dwarf2_cu *cu)
15037 {
15038   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
15039      of GNAT produces this auxiliary information, without any indication
15040      that it is produced.  Part of enhancing the FSF version of GNAT
15041      to produce that information will be to put in place an indicator
15042      that we can use in order to determine whether the descriptive type
15043      info is available or not.  One suggestion that has been made is
15044      to use a new attribute, attached to the CU die.  For now, assume
15045      that the descriptive type info is not available.  */
15046   return 0;
15047 }
15048
15049 /* Return the auxiliary type of the die in question using its
15050    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
15051    attribute is not present.  */
15052
15053 static struct type *
15054 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
15055 {
15056   struct attribute *type_attr;
15057
15058   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
15059   if (!type_attr)
15060     return NULL;
15061
15062   return lookup_die_type (die, type_attr, cu);
15063 }
15064
15065 /* If DIE has a descriptive_type attribute, then set the TYPE's
15066    descriptive type accordingly.  */
15067
15068 static void
15069 set_descriptive_type (struct type *type, struct die_info *die,
15070                       struct dwarf2_cu *cu)
15071 {
15072   struct type *descriptive_type = die_descriptive_type (die, cu);
15073
15074   if (descriptive_type)
15075     {
15076       ALLOCATE_GNAT_AUX_TYPE (type);
15077       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
15078     }
15079 }
15080
15081 /* Return the containing type of the die in question using its
15082    DW_AT_containing_type attribute.  */
15083
15084 static struct type *
15085 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
15086 {
15087   struct attribute *type_attr;
15088
15089   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
15090   if (!type_attr)
15091     error (_("Dwarf Error: Problem turning containing type into gdb type "
15092              "[in module %s]"), cu->objfile->name);
15093
15094   return lookup_die_type (die, type_attr, cu);
15095 }
15096
15097 /* Look up the type of DIE in CU using its type attribute ATTR.
15098    If there is no type substitute an error marker.  */
15099
15100 static struct type *
15101 lookup_die_type (struct die_info *die, struct attribute *attr,
15102                  struct dwarf2_cu *cu)
15103 {
15104   struct objfile *objfile = cu->objfile;
15105   struct type *this_type;
15106
15107   /* First see if we have it cached.  */
15108
15109   if (is_ref_attr (attr))
15110     {
15111       sect_offset offset = dwarf2_get_ref_die_offset (attr);
15112
15113       this_type = get_die_type_at_offset (offset, cu->per_cu);
15114     }
15115   else if (attr->form == DW_FORM_ref_sig8)
15116     {
15117       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
15118
15119       /* sig_type will be NULL if the signatured type is missing from
15120          the debug info.  */
15121       if (sig_type == NULL)
15122         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
15123                  "at 0x%x [in module %s]"),
15124                die->offset.sect_off, objfile->name);
15125
15126       gdb_assert (sig_type->per_cu.is_debug_types);
15127       /* If we haven't filled in type_offset_in_section yet, then we
15128          haven't read the type in yet.  */
15129       this_type = NULL;
15130       if (sig_type->type_offset_in_section.sect_off != 0)
15131         {
15132           this_type =
15133             get_die_type_at_offset (sig_type->type_offset_in_section,
15134                                     &sig_type->per_cu);
15135         }
15136     }
15137   else
15138     {
15139       dump_die_for_error (die);
15140       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
15141              dwarf_attr_name (attr->name), objfile->name);
15142     }
15143
15144   /* If not cached we need to read it in.  */
15145
15146   if (this_type == NULL)
15147     {
15148       struct die_info *type_die;
15149       struct dwarf2_cu *type_cu = cu;
15150
15151       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
15152       /* If we found the type now, it's probably because the type came
15153          from an inter-CU reference and the type's CU got expanded before
15154          ours.  */
15155       this_type = get_die_type (type_die, type_cu);
15156       if (this_type == NULL)
15157         this_type = read_type_die_1 (type_die, type_cu);
15158     }
15159
15160   /* If we still don't have a type use an error marker.  */
15161
15162   if (this_type == NULL)
15163     {
15164       char *message, *saved;
15165
15166       /* read_type_die already issued a complaint.  */
15167       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
15168                             objfile->name,
15169                             cu->header.offset.sect_off,
15170                             die->offset.sect_off);
15171       saved = obstack_copy0 (&objfile->objfile_obstack,
15172                              message, strlen (message));
15173       xfree (message);
15174
15175       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
15176     }
15177
15178   return this_type;
15179 }
15180
15181 /* Return the type in DIE, CU.
15182    Returns NULL for invalid types.
15183
15184    This first does a lookup in the appropriate type_hash table,
15185    and only reads the die in if necessary.
15186
15187    NOTE: This can be called when reading in partial or full symbols.  */
15188
15189 static struct type *
15190 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
15191 {
15192   struct type *this_type;
15193
15194   this_type = get_die_type (die, cu);
15195   if (this_type)
15196     return this_type;
15197
15198   return read_type_die_1 (die, cu);
15199 }
15200
15201 /* Read the type in DIE, CU.
15202    Returns NULL for invalid types.  */
15203
15204 static struct type *
15205 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
15206 {
15207   struct type *this_type = NULL;
15208
15209   switch (die->tag)
15210     {
15211     case DW_TAG_class_type:
15212     case DW_TAG_interface_type:
15213     case DW_TAG_structure_type:
15214     case DW_TAG_union_type:
15215       this_type = read_structure_type (die, cu);
15216       break;
15217     case DW_TAG_enumeration_type:
15218       this_type = read_enumeration_type (die, cu);
15219       break;
15220     case DW_TAG_subprogram:
15221     case DW_TAG_subroutine_type:
15222     case DW_TAG_inlined_subroutine:
15223       this_type = read_subroutine_type (die, cu);
15224       break;
15225     case DW_TAG_array_type:
15226       this_type = read_array_type (die, cu);
15227       break;
15228     case DW_TAG_set_type:
15229       this_type = read_set_type (die, cu);
15230       break;
15231     case DW_TAG_pointer_type:
15232       this_type = read_tag_pointer_type (die, cu);
15233       break;
15234     case DW_TAG_ptr_to_member_type:
15235       this_type = read_tag_ptr_to_member_type (die, cu);
15236       break;
15237     case DW_TAG_reference_type:
15238       this_type = read_tag_reference_type (die, cu);
15239       break;
15240     case DW_TAG_const_type:
15241       this_type = read_tag_const_type (die, cu);
15242       break;
15243     case DW_TAG_volatile_type:
15244       this_type = read_tag_volatile_type (die, cu);
15245       break;
15246     case DW_TAG_string_type:
15247       this_type = read_tag_string_type (die, cu);
15248       break;
15249     case DW_TAG_typedef:
15250       this_type = read_typedef (die, cu);
15251       break;
15252     case DW_TAG_subrange_type:
15253       this_type = read_subrange_type (die, cu);
15254       break;
15255     case DW_TAG_base_type:
15256       this_type = read_base_type (die, cu);
15257       break;
15258     case DW_TAG_unspecified_type:
15259       this_type = read_unspecified_type (die, cu);
15260       break;
15261     case DW_TAG_namespace:
15262       this_type = read_namespace_type (die, cu);
15263       break;
15264     case DW_TAG_module:
15265       this_type = read_module_type (die, cu);
15266       break;
15267     default:
15268       complaint (&symfile_complaints,
15269                  _("unexpected tag in read_type_die: '%s'"),
15270                  dwarf_tag_name (die->tag));
15271       break;
15272     }
15273
15274   return this_type;
15275 }
15276
15277 /* See if we can figure out if the class lives in a namespace.  We do
15278    this by looking for a member function; its demangled name will
15279    contain namespace info, if there is any.
15280    Return the computed name or NULL.
15281    Space for the result is allocated on the objfile's obstack.
15282    This is the full-die version of guess_partial_die_structure_name.
15283    In this case we know DIE has no useful parent.  */
15284
15285 static char *
15286 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
15287 {
15288   struct die_info *spec_die;
15289   struct dwarf2_cu *spec_cu;
15290   struct die_info *child;
15291
15292   spec_cu = cu;
15293   spec_die = die_specification (die, &spec_cu);
15294   if (spec_die != NULL)
15295     {
15296       die = spec_die;
15297       cu = spec_cu;
15298     }
15299
15300   for (child = die->child;
15301        child != NULL;
15302        child = child->sibling)
15303     {
15304       if (child->tag == DW_TAG_subprogram)
15305         {
15306           struct attribute *attr;
15307
15308           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
15309           if (attr == NULL)
15310             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
15311           if (attr != NULL)
15312             {
15313               char *actual_name
15314                 = language_class_name_from_physname (cu->language_defn,
15315                                                      DW_STRING (attr));
15316               char *name = NULL;
15317
15318               if (actual_name != NULL)
15319                 {
15320                   char *die_name = dwarf2_name (die, cu);
15321
15322                   if (die_name != NULL
15323                       && strcmp (die_name, actual_name) != 0)
15324                     {
15325                       /* Strip off the class name from the full name.
15326                          We want the prefix.  */
15327                       int die_name_len = strlen (die_name);
15328                       int actual_name_len = strlen (actual_name);
15329
15330                       /* Test for '::' as a sanity check.  */
15331                       if (actual_name_len > die_name_len + 2
15332                           && actual_name[actual_name_len
15333                                          - die_name_len - 1] == ':')
15334                         name =
15335                           obsavestring (actual_name,
15336                                         actual_name_len - die_name_len - 2,
15337                                         &cu->objfile->objfile_obstack);
15338                     }
15339                 }
15340               xfree (actual_name);
15341               return name;
15342             }
15343         }
15344     }
15345
15346   return NULL;
15347 }
15348
15349 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
15350    prefix part in such case.  See
15351    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15352
15353 static char *
15354 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
15355 {
15356   struct attribute *attr;
15357   char *base;
15358
15359   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
15360       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
15361     return NULL;
15362
15363   attr = dwarf2_attr (die, DW_AT_name, cu);
15364   if (attr != NULL && DW_STRING (attr) != NULL)
15365     return NULL;
15366
15367   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
15368   if (attr == NULL)
15369     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
15370   if (attr == NULL || DW_STRING (attr) == NULL)
15371     return NULL;
15372
15373   /* dwarf2_name had to be already called.  */
15374   gdb_assert (DW_STRING_IS_CANONICAL (attr));
15375
15376   /* Strip the base name, keep any leading namespaces/classes.  */
15377   base = strrchr (DW_STRING (attr), ':');
15378   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
15379     return "";
15380
15381   return obsavestring (DW_STRING (attr), &base[-1] - DW_STRING (attr),
15382                        &cu->objfile->objfile_obstack);
15383 }
15384
15385 /* Return the name of the namespace/class that DIE is defined within,
15386    or "" if we can't tell.  The caller should not xfree the result.
15387
15388    For example, if we're within the method foo() in the following
15389    code:
15390
15391    namespace N {
15392      class C {
15393        void foo () {
15394        }
15395      };
15396    }
15397
15398    then determine_prefix on foo's die will return "N::C".  */
15399
15400 static const char *
15401 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
15402 {
15403   struct die_info *parent, *spec_die;
15404   struct dwarf2_cu *spec_cu;
15405   struct type *parent_type;
15406   char *retval;
15407
15408   if (cu->language != language_cplus && cu->language != language_java
15409       && cu->language != language_fortran)
15410     return "";
15411
15412   retval = anonymous_struct_prefix (die, cu);
15413   if (retval)
15414     return retval;
15415
15416   /* We have to be careful in the presence of DW_AT_specification.
15417      For example, with GCC 3.4, given the code
15418
15419      namespace N {
15420        void foo() {
15421          // Definition of N::foo.
15422        }
15423      }
15424
15425      then we'll have a tree of DIEs like this:
15426
15427      1: DW_TAG_compile_unit
15428        2: DW_TAG_namespace        // N
15429          3: DW_TAG_subprogram     // declaration of N::foo
15430        4: DW_TAG_subprogram       // definition of N::foo
15431             DW_AT_specification   // refers to die #3
15432
15433      Thus, when processing die #4, we have to pretend that we're in
15434      the context of its DW_AT_specification, namely the contex of die
15435      #3.  */
15436   spec_cu = cu;
15437   spec_die = die_specification (die, &spec_cu);
15438   if (spec_die == NULL)
15439     parent = die->parent;
15440   else
15441     {
15442       parent = spec_die->parent;
15443       cu = spec_cu;
15444     }
15445
15446   if (parent == NULL)
15447     return "";
15448   else if (parent->building_fullname)
15449     {
15450       const char *name;
15451       const char *parent_name;
15452
15453       /* It has been seen on RealView 2.2 built binaries,
15454          DW_TAG_template_type_param types actually _defined_ as
15455          children of the parent class:
15456
15457          enum E {};
15458          template class <class Enum> Class{};
15459          Class<enum E> class_e;
15460
15461          1: DW_TAG_class_type (Class)
15462            2: DW_TAG_enumeration_type (E)
15463              3: DW_TAG_enumerator (enum1:0)
15464              3: DW_TAG_enumerator (enum2:1)
15465              ...
15466            2: DW_TAG_template_type_param
15467               DW_AT_type  DW_FORM_ref_udata (E)
15468
15469          Besides being broken debug info, it can put GDB into an
15470          infinite loop.  Consider:
15471
15472          When we're building the full name for Class<E>, we'll start
15473          at Class, and go look over its template type parameters,
15474          finding E.  We'll then try to build the full name of E, and
15475          reach here.  We're now trying to build the full name of E,
15476          and look over the parent DIE for containing scope.  In the
15477          broken case, if we followed the parent DIE of E, we'd again
15478          find Class, and once again go look at its template type
15479          arguments, etc., etc.  Simply don't consider such parent die
15480          as source-level parent of this die (it can't be, the language
15481          doesn't allow it), and break the loop here.  */
15482       name = dwarf2_name (die, cu);
15483       parent_name = dwarf2_name (parent, cu);
15484       complaint (&symfile_complaints,
15485                  _("template param type '%s' defined within parent '%s'"),
15486                  name ? name : "<unknown>",
15487                  parent_name ? parent_name : "<unknown>");
15488       return "";
15489     }
15490   else
15491     switch (parent->tag)
15492       {
15493       case DW_TAG_namespace:
15494         parent_type = read_type_die (parent, cu);
15495         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
15496            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
15497            Work around this problem here.  */
15498         if (cu->language == language_cplus
15499             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
15500           return "";
15501         /* We give a name to even anonymous namespaces.  */
15502         return TYPE_TAG_NAME (parent_type);
15503       case DW_TAG_class_type:
15504       case DW_TAG_interface_type:
15505       case DW_TAG_structure_type:
15506       case DW_TAG_union_type:
15507       case DW_TAG_module:
15508         parent_type = read_type_die (parent, cu);
15509         if (TYPE_TAG_NAME (parent_type) != NULL)
15510           return TYPE_TAG_NAME (parent_type);
15511         else
15512           /* An anonymous structure is only allowed non-static data
15513              members; no typedefs, no member functions, et cetera.
15514              So it does not need a prefix.  */
15515           return "";
15516       case DW_TAG_compile_unit:
15517       case DW_TAG_partial_unit:
15518         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
15519         if (cu->language == language_cplus
15520             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15521             && die->child != NULL
15522             && (die->tag == DW_TAG_class_type
15523                 || die->tag == DW_TAG_structure_type
15524                 || die->tag == DW_TAG_union_type))
15525           {
15526             char *name = guess_full_die_structure_name (die, cu);
15527             if (name != NULL)
15528               return name;
15529           }
15530         return "";
15531       default:
15532         return determine_prefix (parent, cu);
15533       }
15534 }
15535
15536 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
15537    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
15538    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
15539    an obconcat, otherwise allocate storage for the result.  The CU argument is
15540    used to determine the language and hence, the appropriate separator.  */
15541
15542 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
15543
15544 static char *
15545 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
15546                  int physname, struct dwarf2_cu *cu)
15547 {
15548   const char *lead = "";
15549   const char *sep;
15550
15551   if (suffix == NULL || suffix[0] == '\0'
15552       || prefix == NULL || prefix[0] == '\0')
15553     sep = "";
15554   else if (cu->language == language_java)
15555     sep = ".";
15556   else if (cu->language == language_fortran && physname)
15557     {
15558       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
15559          DW_AT_MIPS_linkage_name is preferred and used instead.  */
15560
15561       lead = "__";
15562       sep = "_MOD_";
15563     }
15564   else
15565     sep = "::";
15566
15567   if (prefix == NULL)
15568     prefix = "";
15569   if (suffix == NULL)
15570     suffix = "";
15571
15572   if (obs == NULL)
15573     {
15574       char *retval
15575         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
15576
15577       strcpy (retval, lead);
15578       strcat (retval, prefix);
15579       strcat (retval, sep);
15580       strcat (retval, suffix);
15581       return retval;
15582     }
15583   else
15584     {
15585       /* We have an obstack.  */
15586       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
15587     }
15588 }
15589
15590 /* Return sibling of die, NULL if no sibling.  */
15591
15592 static struct die_info *
15593 sibling_die (struct die_info *die)
15594 {
15595   return die->sibling;
15596 }
15597
15598 /* Get name of a die, return NULL if not found.  */
15599
15600 static char *
15601 dwarf2_canonicalize_name (char *name, struct dwarf2_cu *cu,
15602                           struct obstack *obstack)
15603 {
15604   if (name && cu->language == language_cplus)
15605     {
15606       char *canon_name = cp_canonicalize_string (name);
15607
15608       if (canon_name != NULL)
15609         {
15610           if (strcmp (canon_name, name) != 0)
15611             name = obsavestring (canon_name, strlen (canon_name),
15612                                  obstack);
15613           xfree (canon_name);
15614         }
15615     }
15616
15617   return name;
15618 }
15619
15620 /* Get name of a die, return NULL if not found.  */
15621
15622 static char *
15623 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
15624 {
15625   struct attribute *attr;
15626
15627   attr = dwarf2_attr (die, DW_AT_name, cu);
15628   if ((!attr || !DW_STRING (attr))
15629       && die->tag != DW_TAG_class_type
15630       && die->tag != DW_TAG_interface_type
15631       && die->tag != DW_TAG_structure_type
15632       && die->tag != DW_TAG_union_type)
15633     return NULL;
15634
15635   switch (die->tag)
15636     {
15637     case DW_TAG_compile_unit:
15638     case DW_TAG_partial_unit:
15639       /* Compilation units have a DW_AT_name that is a filename, not
15640          a source language identifier.  */
15641     case DW_TAG_enumeration_type:
15642     case DW_TAG_enumerator:
15643       /* These tags always have simple identifiers already; no need
15644          to canonicalize them.  */
15645       return DW_STRING (attr);
15646
15647     case DW_TAG_subprogram:
15648       /* Java constructors will all be named "<init>", so return
15649          the class name when we see this special case.  */
15650       if (cu->language == language_java
15651           && DW_STRING (attr) != NULL
15652           && strcmp (DW_STRING (attr), "<init>") == 0)
15653         {
15654           struct dwarf2_cu *spec_cu = cu;
15655           struct die_info *spec_die;
15656
15657           /* GCJ will output '<init>' for Java constructor names.
15658              For this special case, return the name of the parent class.  */
15659
15660           /* GCJ may output suprogram DIEs with AT_specification set.
15661              If so, use the name of the specified DIE.  */
15662           spec_die = die_specification (die, &spec_cu);
15663           if (spec_die != NULL)
15664             return dwarf2_name (spec_die, spec_cu);
15665
15666           do
15667             {
15668               die = die->parent;
15669               if (die->tag == DW_TAG_class_type)
15670                 return dwarf2_name (die, cu);
15671             }
15672           while (die->tag != DW_TAG_compile_unit
15673                  && die->tag != DW_TAG_partial_unit);
15674         }
15675       break;
15676
15677     case DW_TAG_class_type:
15678     case DW_TAG_interface_type:
15679     case DW_TAG_structure_type:
15680     case DW_TAG_union_type:
15681       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
15682          structures or unions.  These were of the form "._%d" in GCC 4.1,
15683          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
15684          and GCC 4.4.  We work around this problem by ignoring these.  */
15685       if (attr && DW_STRING (attr)
15686           && (strncmp (DW_STRING (attr), "._", 2) == 0
15687               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
15688         return NULL;
15689
15690       /* GCC might emit a nameless typedef that has a linkage name.  See
15691          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15692       if (!attr || DW_STRING (attr) == NULL)
15693         {
15694           char *demangled = NULL;
15695
15696           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
15697           if (attr == NULL)
15698             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
15699
15700           if (attr == NULL || DW_STRING (attr) == NULL)
15701             return NULL;
15702
15703           /* Avoid demangling DW_STRING (attr) the second time on a second
15704              call for the same DIE.  */
15705           if (!DW_STRING_IS_CANONICAL (attr))
15706             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
15707
15708           if (demangled)
15709             {
15710               char *base;
15711
15712               /* FIXME: we already did this for the partial symbol... */
15713               DW_STRING (attr) = obsavestring (demangled, strlen (demangled),
15714                                                &cu->objfile->objfile_obstack);
15715               DW_STRING_IS_CANONICAL (attr) = 1;
15716               xfree (demangled);
15717
15718               /* Strip any leading namespaces/classes, keep only the base name.
15719                  DW_AT_name for named DIEs does not contain the prefixes.  */
15720               base = strrchr (DW_STRING (attr), ':');
15721               if (base && base > DW_STRING (attr) && base[-1] == ':')
15722                 return &base[1];
15723               else
15724                 return DW_STRING (attr);
15725             }
15726         }
15727       break;
15728
15729     default:
15730       break;
15731     }
15732
15733   if (!DW_STRING_IS_CANONICAL (attr))
15734     {
15735       DW_STRING (attr)
15736         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
15737                                     &cu->objfile->objfile_obstack);
15738       DW_STRING_IS_CANONICAL (attr) = 1;
15739     }
15740   return DW_STRING (attr);
15741 }
15742
15743 /* Return the die that this die in an extension of, or NULL if there
15744    is none.  *EXT_CU is the CU containing DIE on input, and the CU
15745    containing the return value on output.  */
15746
15747 static struct die_info *
15748 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
15749 {
15750   struct attribute *attr;
15751
15752   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
15753   if (attr == NULL)
15754     return NULL;
15755
15756   return follow_die_ref (die, attr, ext_cu);
15757 }
15758
15759 /* Convert a DIE tag into its string name.  */
15760
15761 static const char *
15762 dwarf_tag_name (unsigned tag)
15763 {
15764   const char *name = get_DW_TAG_name (tag);
15765
15766   if (name == NULL)
15767     return "DW_TAG_<unknown>";
15768
15769   return name;
15770 }
15771
15772 /* Convert a DWARF attribute code into its string name.  */
15773
15774 static const char *
15775 dwarf_attr_name (unsigned attr)
15776 {
15777   const char *name;
15778
15779 #ifdef MIPS /* collides with DW_AT_HP_block_index */
15780   if (attr == DW_AT_MIPS_fde)
15781     return "DW_AT_MIPS_fde";
15782 #else
15783   if (attr == DW_AT_HP_block_index)
15784     return "DW_AT_HP_block_index";
15785 #endif
15786
15787   name = get_DW_AT_name (attr);
15788
15789   if (name == NULL)
15790     return "DW_AT_<unknown>";
15791
15792   return name;
15793 }
15794
15795 /* Convert a DWARF value form code into its string name.  */
15796
15797 static const char *
15798 dwarf_form_name (unsigned form)
15799 {
15800   const char *name = get_DW_FORM_name (form);
15801
15802   if (name == NULL)
15803     return "DW_FORM_<unknown>";
15804
15805   return name;
15806 }
15807
15808 static char *
15809 dwarf_bool_name (unsigned mybool)
15810 {
15811   if (mybool)
15812     return "TRUE";
15813   else
15814     return "FALSE";
15815 }
15816
15817 /* Convert a DWARF type code into its string name.  */
15818
15819 static const char *
15820 dwarf_type_encoding_name (unsigned enc)
15821 {
15822   const char *name = get_DW_ATE_name (enc);
15823
15824   if (name == NULL)
15825     return "DW_ATE_<unknown>";
15826
15827   return name;
15828 }
15829
15830 static void
15831 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
15832 {
15833   unsigned int i;
15834
15835   print_spaces (indent, f);
15836   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
15837            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
15838
15839   if (die->parent != NULL)
15840     {
15841       print_spaces (indent, f);
15842       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
15843                           die->parent->offset.sect_off);
15844     }
15845
15846   print_spaces (indent, f);
15847   fprintf_unfiltered (f, "  has children: %s\n",
15848            dwarf_bool_name (die->child != NULL));
15849
15850   print_spaces (indent, f);
15851   fprintf_unfiltered (f, "  attributes:\n");
15852
15853   for (i = 0; i < die->num_attrs; ++i)
15854     {
15855       print_spaces (indent, f);
15856       fprintf_unfiltered (f, "    %s (%s) ",
15857                dwarf_attr_name (die->attrs[i].name),
15858                dwarf_form_name (die->attrs[i].form));
15859
15860       switch (die->attrs[i].form)
15861         {
15862         case DW_FORM_addr:
15863         case DW_FORM_GNU_addr_index:
15864           fprintf_unfiltered (f, "address: ");
15865           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
15866           break;
15867         case DW_FORM_block2:
15868         case DW_FORM_block4:
15869         case DW_FORM_block:
15870         case DW_FORM_block1:
15871           fprintf_unfiltered (f, "block: size %d",
15872                               DW_BLOCK (&die->attrs[i])->size);
15873           break;
15874         case DW_FORM_exprloc:
15875           fprintf_unfiltered (f, "expression: size %u",
15876                               DW_BLOCK (&die->attrs[i])->size);
15877           break;
15878         case DW_FORM_ref_addr:
15879           fprintf_unfiltered (f, "ref address: ");
15880           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
15881           break;
15882         case DW_FORM_ref1:
15883         case DW_FORM_ref2:
15884         case DW_FORM_ref4:
15885         case DW_FORM_ref8:
15886         case DW_FORM_ref_udata:
15887           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
15888                               (long) (DW_UNSND (&die->attrs[i])));
15889           break;
15890         case DW_FORM_data1:
15891         case DW_FORM_data2:
15892         case DW_FORM_data4:
15893         case DW_FORM_data8:
15894         case DW_FORM_udata:
15895         case DW_FORM_sdata:
15896           fprintf_unfiltered (f, "constant: %s",
15897                               pulongest (DW_UNSND (&die->attrs[i])));
15898           break;
15899         case DW_FORM_sec_offset:
15900           fprintf_unfiltered (f, "section offset: %s",
15901                               pulongest (DW_UNSND (&die->attrs[i])));
15902           break;
15903         case DW_FORM_ref_sig8:
15904           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
15905             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
15906                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
15907           else
15908             fprintf_unfiltered (f, "signatured type, offset: unknown");
15909           break;
15910         case DW_FORM_string:
15911         case DW_FORM_strp:
15912         case DW_FORM_GNU_str_index:
15913           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
15914                    DW_STRING (&die->attrs[i])
15915                    ? DW_STRING (&die->attrs[i]) : "",
15916                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
15917           break;
15918         case DW_FORM_flag:
15919           if (DW_UNSND (&die->attrs[i]))
15920             fprintf_unfiltered (f, "flag: TRUE");
15921           else
15922             fprintf_unfiltered (f, "flag: FALSE");
15923           break;
15924         case DW_FORM_flag_present:
15925           fprintf_unfiltered (f, "flag: TRUE");
15926           break;
15927         case DW_FORM_indirect:
15928           /* The reader will have reduced the indirect form to
15929              the "base form" so this form should not occur.  */
15930           fprintf_unfiltered (f, 
15931                               "unexpected attribute form: DW_FORM_indirect");
15932           break;
15933         default:
15934           fprintf_unfiltered (f, "unsupported attribute form: %d.",
15935                    die->attrs[i].form);
15936           break;
15937         }
15938       fprintf_unfiltered (f, "\n");
15939     }
15940 }
15941
15942 static void
15943 dump_die_for_error (struct die_info *die)
15944 {
15945   dump_die_shallow (gdb_stderr, 0, die);
15946 }
15947
15948 static void
15949 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
15950 {
15951   int indent = level * 4;
15952
15953   gdb_assert (die != NULL);
15954
15955   if (level >= max_level)
15956     return;
15957
15958   dump_die_shallow (f, indent, die);
15959
15960   if (die->child != NULL)
15961     {
15962       print_spaces (indent, f);
15963       fprintf_unfiltered (f, "  Children:");
15964       if (level + 1 < max_level)
15965         {
15966           fprintf_unfiltered (f, "\n");
15967           dump_die_1 (f, level + 1, max_level, die->child);
15968         }
15969       else
15970         {
15971           fprintf_unfiltered (f,
15972                               " [not printed, max nesting level reached]\n");
15973         }
15974     }
15975
15976   if (die->sibling != NULL && level > 0)
15977     {
15978       dump_die_1 (f, level, max_level, die->sibling);
15979     }
15980 }
15981
15982 /* This is called from the pdie macro in gdbinit.in.
15983    It's not static so gcc will keep a copy callable from gdb.  */
15984
15985 void
15986 dump_die (struct die_info *die, int max_level)
15987 {
15988   dump_die_1 (gdb_stdlog, 0, max_level, die);
15989 }
15990
15991 static void
15992 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
15993 {
15994   void **slot;
15995
15996   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
15997                                    INSERT);
15998
15999   *slot = die;
16000 }
16001
16002 /* DW_ADDR is always stored already as sect_offset; despite for the forms
16003    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
16004
16005 static int
16006 is_ref_attr (struct attribute *attr)
16007 {
16008   switch (attr->form)
16009     {
16010     case DW_FORM_ref_addr:
16011     case DW_FORM_ref1:
16012     case DW_FORM_ref2:
16013     case DW_FORM_ref4:
16014     case DW_FORM_ref8:
16015     case DW_FORM_ref_udata:
16016       return 1;
16017     default:
16018       return 0;
16019     }
16020 }
16021
16022 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
16023    required kind.  */
16024
16025 static sect_offset
16026 dwarf2_get_ref_die_offset (struct attribute *attr)
16027 {
16028   sect_offset retval = { DW_UNSND (attr) };
16029
16030   if (is_ref_attr (attr))
16031     return retval;
16032
16033   retval.sect_off = 0;
16034   complaint (&symfile_complaints,
16035              _("unsupported die ref attribute form: '%s'"),
16036              dwarf_form_name (attr->form));
16037   return retval;
16038 }
16039
16040 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
16041  * the value held by the attribute is not constant.  */
16042
16043 static LONGEST
16044 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
16045 {
16046   if (attr->form == DW_FORM_sdata)
16047     return DW_SND (attr);
16048   else if (attr->form == DW_FORM_udata
16049            || attr->form == DW_FORM_data1
16050            || attr->form == DW_FORM_data2
16051            || attr->form == DW_FORM_data4
16052            || attr->form == DW_FORM_data8)
16053     return DW_UNSND (attr);
16054   else
16055     {
16056       complaint (&symfile_complaints,
16057                  _("Attribute value is not a constant (%s)"),
16058                  dwarf_form_name (attr->form));
16059       return default_value;
16060     }
16061 }
16062
16063 /* Follow reference or signature attribute ATTR of SRC_DIE.
16064    On entry *REF_CU is the CU of SRC_DIE.
16065    On exit *REF_CU is the CU of the result.  */
16066
16067 static struct die_info *
16068 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
16069                        struct dwarf2_cu **ref_cu)
16070 {
16071   struct die_info *die;
16072
16073   if (is_ref_attr (attr))
16074     die = follow_die_ref (src_die, attr, ref_cu);
16075   else if (attr->form == DW_FORM_ref_sig8)
16076     die = follow_die_sig (src_die, attr, ref_cu);
16077   else
16078     {
16079       dump_die_for_error (src_die);
16080       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
16081              (*ref_cu)->objfile->name);
16082     }
16083
16084   return die;
16085 }
16086
16087 /* Follow reference OFFSET.
16088    On entry *REF_CU is the CU of the source die referencing OFFSET.
16089    On exit *REF_CU is the CU of the result.
16090    Returns NULL if OFFSET is invalid.  */
16091
16092 static struct die_info *
16093 follow_die_offset (sect_offset offset, struct dwarf2_cu **ref_cu)
16094 {
16095   struct die_info temp_die;
16096   struct dwarf2_cu *target_cu, *cu = *ref_cu;
16097
16098   gdb_assert (cu->per_cu != NULL);
16099
16100   target_cu = cu;
16101
16102   if (cu->per_cu->is_debug_types)
16103     {
16104       /* .debug_types CUs cannot reference anything outside their CU.
16105          If they need to, they have to reference a signatured type via
16106          DW_FORM_ref_sig8.  */
16107       if (! offset_in_cu_p (&cu->header, offset))
16108         return NULL;
16109     }
16110   else if (! offset_in_cu_p (&cu->header, offset))
16111     {
16112       struct dwarf2_per_cu_data *per_cu;
16113
16114       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
16115
16116       /* If necessary, add it to the queue and load its DIEs.  */
16117       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
16118         load_full_comp_unit (per_cu, cu->language);
16119
16120       target_cu = per_cu->cu;
16121     }
16122   else if (cu->dies == NULL)
16123     {
16124       /* We're loading full DIEs during partial symbol reading.  */
16125       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
16126       load_full_comp_unit (cu->per_cu, language_minimal);
16127     }
16128
16129   *ref_cu = target_cu;
16130   temp_die.offset = offset;
16131   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
16132 }
16133
16134 /* Follow reference attribute ATTR of SRC_DIE.
16135    On entry *REF_CU is the CU of SRC_DIE.
16136    On exit *REF_CU is the CU of the result.  */
16137
16138 static struct die_info *
16139 follow_die_ref (struct die_info *src_die, struct attribute *attr,
16140                 struct dwarf2_cu **ref_cu)
16141 {
16142   sect_offset offset = dwarf2_get_ref_die_offset (attr);
16143   struct dwarf2_cu *cu = *ref_cu;
16144   struct die_info *die;
16145
16146   die = follow_die_offset (offset, ref_cu);
16147   if (!die)
16148     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
16149            "at 0x%x [in module %s]"),
16150            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
16151
16152   return die;
16153 }
16154
16155 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
16156    Returned value is intended for DW_OP_call*.  Returned
16157    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
16158
16159 struct dwarf2_locexpr_baton
16160 dwarf2_fetch_die_location_block (cu_offset offset_in_cu,
16161                                  struct dwarf2_per_cu_data *per_cu,
16162                                  CORE_ADDR (*get_frame_pc) (void *baton),
16163                                  void *baton)
16164 {
16165   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
16166   struct dwarf2_cu *cu;
16167   struct die_info *die;
16168   struct attribute *attr;
16169   struct dwarf2_locexpr_baton retval;
16170
16171   dw2_setup (per_cu->objfile);
16172
16173   if (per_cu->cu == NULL)
16174     load_cu (per_cu);
16175   cu = per_cu->cu;
16176
16177   die = follow_die_offset (offset, &cu);
16178   if (!die)
16179     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
16180            offset.sect_off, per_cu->objfile->name);
16181
16182   attr = dwarf2_attr (die, DW_AT_location, cu);
16183   if (!attr)
16184     {
16185       /* DWARF: "If there is no such attribute, then there is no effect.".
16186          DATA is ignored if SIZE is 0.  */
16187
16188       retval.data = NULL;
16189       retval.size = 0;
16190     }
16191   else if (attr_form_is_section_offset (attr))
16192     {
16193       struct dwarf2_loclist_baton loclist_baton;
16194       CORE_ADDR pc = (*get_frame_pc) (baton);
16195       size_t size;
16196
16197       fill_in_loclist_baton (cu, &loclist_baton, attr);
16198
16199       retval.data = dwarf2_find_location_expression (&loclist_baton,
16200                                                      &size, pc);
16201       retval.size = size;
16202     }
16203   else
16204     {
16205       if (!attr_form_is_block (attr))
16206         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
16207                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
16208                offset.sect_off, per_cu->objfile->name);
16209
16210       retval.data = DW_BLOCK (attr)->data;
16211       retval.size = DW_BLOCK (attr)->size;
16212     }
16213   retval.per_cu = cu->per_cu;
16214
16215   age_cached_comp_units ();
16216
16217   return retval;
16218 }
16219
16220 /* Return the type of the DIE at DIE_OFFSET in the CU named by
16221    PER_CU.  */
16222
16223 struct type *
16224 dwarf2_get_die_type (cu_offset die_offset,
16225                      struct dwarf2_per_cu_data *per_cu)
16226 {
16227   sect_offset die_offset_sect;
16228
16229   dw2_setup (per_cu->objfile);
16230
16231   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
16232   return get_die_type_at_offset (die_offset_sect, per_cu);
16233 }
16234
16235 /* Follow the signature attribute ATTR in SRC_DIE.
16236    On entry *REF_CU is the CU of SRC_DIE.
16237    On exit *REF_CU is the CU of the result.  */
16238
16239 static struct die_info *
16240 follow_die_sig (struct die_info *src_die, struct attribute *attr,
16241                 struct dwarf2_cu **ref_cu)
16242 {
16243   struct objfile *objfile = (*ref_cu)->objfile;
16244   struct die_info temp_die;
16245   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16246   struct dwarf2_cu *sig_cu;
16247   struct die_info *die;
16248
16249   /* sig_type will be NULL if the signatured type is missing from
16250      the debug info.  */
16251   if (sig_type == NULL)
16252     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16253              "at 0x%x [in module %s]"),
16254            src_die->offset.sect_off, objfile->name);
16255
16256   /* If necessary, add it to the queue and load its DIEs.  */
16257
16258   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
16259     read_signatured_type (sig_type);
16260
16261   gdb_assert (sig_type->per_cu.cu != NULL);
16262
16263   sig_cu = sig_type->per_cu.cu;
16264   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
16265   temp_die.offset = sig_type->type_offset_in_section;
16266   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
16267                              temp_die.offset.sect_off);
16268   if (die)
16269     {
16270       *ref_cu = sig_cu;
16271       return die;
16272     }
16273
16274   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
16275          "from DIE at 0x%x [in module %s]"),
16276          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
16277 }
16278
16279 /* Given an offset of a signatured type, return its signatured_type.  */
16280
16281 static struct signatured_type *
16282 lookup_signatured_type_at_offset (struct objfile *objfile,
16283                                   struct dwarf2_section_info *section,
16284                                   sect_offset offset)
16285 {
16286   gdb_byte *info_ptr = section->buffer + offset.sect_off;
16287   unsigned int length, initial_length_size;
16288   unsigned int sig_offset;
16289   struct signatured_type find_entry, *sig_type;
16290
16291   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
16292   sig_offset = (initial_length_size
16293                 + 2 /*version*/
16294                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
16295                 + 1 /*address_size*/);
16296   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
16297   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
16298
16299   /* This is only used to lookup previously recorded types.
16300      If we didn't find it, it's our bug.  */
16301   gdb_assert (sig_type != NULL);
16302   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
16303
16304   return sig_type;
16305 }
16306
16307 /* Load the DIEs associated with type unit PER_CU into memory.  */
16308
16309 static void
16310 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
16311 {
16312   struct signatured_type *sig_type;
16313
16314   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
16315   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
16316
16317   /* We have the per_cu, but we need the signatured_type.
16318      Fortunately this is an easy translation.  */
16319   gdb_assert (per_cu->is_debug_types);
16320   sig_type = (struct signatured_type *) per_cu;
16321
16322   gdb_assert (per_cu->cu == NULL);
16323
16324   read_signatured_type (sig_type);
16325
16326   gdb_assert (per_cu->cu != NULL);
16327 }
16328
16329 /* die_reader_func for read_signatured_type.
16330    This is identical to load_full_comp_unit_reader,
16331    but is kept separate for now.  */
16332
16333 static void
16334 read_signatured_type_reader (const struct die_reader_specs *reader,
16335                              gdb_byte *info_ptr,
16336                              struct die_info *comp_unit_die,
16337                              int has_children,
16338                              void *data)
16339 {
16340   struct dwarf2_cu *cu = reader->cu;
16341
16342   gdb_assert (cu->die_hash == NULL);
16343   cu->die_hash =
16344     htab_create_alloc_ex (cu->header.length / 12,
16345                           die_hash,
16346                           die_eq,
16347                           NULL,
16348                           &cu->comp_unit_obstack,
16349                           hashtab_obstack_allocate,
16350                           dummy_obstack_deallocate);
16351
16352   if (has_children)
16353     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
16354                                                   &info_ptr, comp_unit_die);
16355   cu->dies = comp_unit_die;
16356   /* comp_unit_die is not stored in die_hash, no need.  */
16357
16358   /* We try not to read any attributes in this function, because not
16359      all CUs needed for references have been loaded yet, and symbol
16360      table processing isn't initialized.  But we have to set the CU language,
16361      or we won't be able to build types correctly.
16362      Similarly, if we do not read the producer, we can not apply
16363      producer-specific interpretation.  */
16364   prepare_one_comp_unit (cu, cu->dies, language_minimal);
16365 }
16366
16367 /* Read in a signatured type and build its CU and DIEs.
16368    If the type is a stub for the real type in a DWO file,
16369    read in the real type from the DWO file as well.  */
16370
16371 static void
16372 read_signatured_type (struct signatured_type *sig_type)
16373 {
16374   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
16375
16376   gdb_assert (per_cu->is_debug_types);
16377   gdb_assert (per_cu->cu == NULL);
16378
16379   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
16380                            read_signatured_type_reader, NULL);
16381 }
16382
16383 /* Decode simple location descriptions.
16384    Given a pointer to a dwarf block that defines a location, compute
16385    the location and return the value.
16386
16387    NOTE drow/2003-11-18: This function is called in two situations
16388    now: for the address of static or global variables (partial symbols
16389    only) and for offsets into structures which are expected to be
16390    (more or less) constant.  The partial symbol case should go away,
16391    and only the constant case should remain.  That will let this
16392    function complain more accurately.  A few special modes are allowed
16393    without complaint for global variables (for instance, global
16394    register values and thread-local values).
16395
16396    A location description containing no operations indicates that the
16397    object is optimized out.  The return value is 0 for that case.
16398    FIXME drow/2003-11-16: No callers check for this case any more; soon all
16399    callers will only want a very basic result and this can become a
16400    complaint.
16401
16402    Note that stack[0] is unused except as a default error return.  */
16403
16404 static CORE_ADDR
16405 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
16406 {
16407   struct objfile *objfile = cu->objfile;
16408   int i;
16409   int size = blk->size;
16410   gdb_byte *data = blk->data;
16411   CORE_ADDR stack[64];
16412   int stacki;
16413   unsigned int bytes_read, unsnd;
16414   gdb_byte op;
16415
16416   i = 0;
16417   stacki = 0;
16418   stack[stacki] = 0;
16419   stack[++stacki] = 0;
16420
16421   while (i < size)
16422     {
16423       op = data[i++];
16424       switch (op)
16425         {
16426         case DW_OP_lit0:
16427         case DW_OP_lit1:
16428         case DW_OP_lit2:
16429         case DW_OP_lit3:
16430         case DW_OP_lit4:
16431         case DW_OP_lit5:
16432         case DW_OP_lit6:
16433         case DW_OP_lit7:
16434         case DW_OP_lit8:
16435         case DW_OP_lit9:
16436         case DW_OP_lit10:
16437         case DW_OP_lit11:
16438         case DW_OP_lit12:
16439         case DW_OP_lit13:
16440         case DW_OP_lit14:
16441         case DW_OP_lit15:
16442         case DW_OP_lit16:
16443         case DW_OP_lit17:
16444         case DW_OP_lit18:
16445         case DW_OP_lit19:
16446         case DW_OP_lit20:
16447         case DW_OP_lit21:
16448         case DW_OP_lit22:
16449         case DW_OP_lit23:
16450         case DW_OP_lit24:
16451         case DW_OP_lit25:
16452         case DW_OP_lit26:
16453         case DW_OP_lit27:
16454         case DW_OP_lit28:
16455         case DW_OP_lit29:
16456         case DW_OP_lit30:
16457         case DW_OP_lit31:
16458           stack[++stacki] = op - DW_OP_lit0;
16459           break;
16460
16461         case DW_OP_reg0:
16462         case DW_OP_reg1:
16463         case DW_OP_reg2:
16464         case DW_OP_reg3:
16465         case DW_OP_reg4:
16466         case DW_OP_reg5:
16467         case DW_OP_reg6:
16468         case DW_OP_reg7:
16469         case DW_OP_reg8:
16470         case DW_OP_reg9:
16471         case DW_OP_reg10:
16472         case DW_OP_reg11:
16473         case DW_OP_reg12:
16474         case DW_OP_reg13:
16475         case DW_OP_reg14:
16476         case DW_OP_reg15:
16477         case DW_OP_reg16:
16478         case DW_OP_reg17:
16479         case DW_OP_reg18:
16480         case DW_OP_reg19:
16481         case DW_OP_reg20:
16482         case DW_OP_reg21:
16483         case DW_OP_reg22:
16484         case DW_OP_reg23:
16485         case DW_OP_reg24:
16486         case DW_OP_reg25:
16487         case DW_OP_reg26:
16488         case DW_OP_reg27:
16489         case DW_OP_reg28:
16490         case DW_OP_reg29:
16491         case DW_OP_reg30:
16492         case DW_OP_reg31:
16493           stack[++stacki] = op - DW_OP_reg0;
16494           if (i < size)
16495             dwarf2_complex_location_expr_complaint ();
16496           break;
16497
16498         case DW_OP_regx:
16499           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
16500           i += bytes_read;
16501           stack[++stacki] = unsnd;
16502           if (i < size)
16503             dwarf2_complex_location_expr_complaint ();
16504           break;
16505
16506         case DW_OP_addr:
16507           stack[++stacki] = read_address (objfile->obfd, &data[i],
16508                                           cu, &bytes_read);
16509           i += bytes_read;
16510           break;
16511
16512         case DW_OP_const1u:
16513           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
16514           i += 1;
16515           break;
16516
16517         case DW_OP_const1s:
16518           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
16519           i += 1;
16520           break;
16521
16522         case DW_OP_const2u:
16523           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
16524           i += 2;
16525           break;
16526
16527         case DW_OP_const2s:
16528           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
16529           i += 2;
16530           break;
16531
16532         case DW_OP_const4u:
16533           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
16534           i += 4;
16535           break;
16536
16537         case DW_OP_const4s:
16538           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
16539           i += 4;
16540           break;
16541
16542         case DW_OP_const8u:
16543           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
16544           i += 8;
16545           break;
16546
16547         case DW_OP_constu:
16548           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
16549                                                   &bytes_read);
16550           i += bytes_read;
16551           break;
16552
16553         case DW_OP_consts:
16554           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
16555           i += bytes_read;
16556           break;
16557
16558         case DW_OP_dup:
16559           stack[stacki + 1] = stack[stacki];
16560           stacki++;
16561           break;
16562
16563         case DW_OP_plus:
16564           stack[stacki - 1] += stack[stacki];
16565           stacki--;
16566           break;
16567
16568         case DW_OP_plus_uconst:
16569           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
16570                                                  &bytes_read);
16571           i += bytes_read;
16572           break;
16573
16574         case DW_OP_minus:
16575           stack[stacki - 1] -= stack[stacki];
16576           stacki--;
16577           break;
16578
16579         case DW_OP_deref:
16580           /* If we're not the last op, then we definitely can't encode
16581              this using GDB's address_class enum.  This is valid for partial
16582              global symbols, although the variable's address will be bogus
16583              in the psymtab.  */
16584           if (i < size)
16585             dwarf2_complex_location_expr_complaint ();
16586           break;
16587
16588         case DW_OP_GNU_push_tls_address:
16589           /* The top of the stack has the offset from the beginning
16590              of the thread control block at which the variable is located.  */
16591           /* Nothing should follow this operator, so the top of stack would
16592              be returned.  */
16593           /* This is valid for partial global symbols, but the variable's
16594              address will be bogus in the psymtab.  Make it always at least
16595              non-zero to not look as a variable garbage collected by linker
16596              which have DW_OP_addr 0.  */
16597           if (i < size)
16598             dwarf2_complex_location_expr_complaint ();
16599           stack[stacki]++;
16600           break;
16601
16602         case DW_OP_GNU_uninit:
16603           break;
16604
16605         case DW_OP_GNU_addr_index:
16606         case DW_OP_GNU_const_index:
16607           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
16608                                                          &bytes_read);
16609           i += bytes_read;
16610           break;
16611
16612         default:
16613           {
16614             const char *name = get_DW_OP_name (op);
16615
16616             if (name)
16617               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
16618                          name);
16619             else
16620               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
16621                          op);
16622           }
16623
16624           return (stack[stacki]);
16625         }
16626
16627       /* Enforce maximum stack depth of SIZE-1 to avoid writing
16628          outside of the allocated space.  Also enforce minimum>0.  */
16629       if (stacki >= ARRAY_SIZE (stack) - 1)
16630         {
16631           complaint (&symfile_complaints,
16632                      _("location description stack overflow"));
16633           return 0;
16634         }
16635
16636       if (stacki <= 0)
16637         {
16638           complaint (&symfile_complaints,
16639                      _("location description stack underflow"));
16640           return 0;
16641         }
16642     }
16643   return (stack[stacki]);
16644 }
16645
16646 /* memory allocation interface */
16647
16648 static struct dwarf_block *
16649 dwarf_alloc_block (struct dwarf2_cu *cu)
16650 {
16651   struct dwarf_block *blk;
16652
16653   blk = (struct dwarf_block *)
16654     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
16655   return (blk);
16656 }
16657
16658 static struct die_info *
16659 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
16660 {
16661   struct die_info *die;
16662   size_t size = sizeof (struct die_info);
16663
16664   if (num_attrs > 1)
16665     size += (num_attrs - 1) * sizeof (struct attribute);
16666
16667   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
16668   memset (die, 0, sizeof (struct die_info));
16669   return (die);
16670 }
16671
16672 \f
16673 /* Macro support.  */
16674
16675 /* Return the full name of file number I in *LH's file name table.
16676    Use COMP_DIR as the name of the current directory of the
16677    compilation.  The result is allocated using xmalloc; the caller is
16678    responsible for freeing it.  */
16679 static char *
16680 file_full_name (int file, struct line_header *lh, const char *comp_dir)
16681 {
16682   /* Is the file number a valid index into the line header's file name
16683      table?  Remember that file numbers start with one, not zero.  */
16684   if (1 <= file && file <= lh->num_file_names)
16685     {
16686       struct file_entry *fe = &lh->file_names[file - 1];
16687
16688       if (IS_ABSOLUTE_PATH (fe->name))
16689         return xstrdup (fe->name);
16690       else
16691         {
16692           const char *dir;
16693           int dir_len;
16694           char *full_name;
16695
16696           if (fe->dir_index)
16697             dir = lh->include_dirs[fe->dir_index - 1];
16698           else
16699             dir = comp_dir;
16700
16701           if (dir)
16702             {
16703               dir_len = strlen (dir);
16704               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
16705               strcpy (full_name, dir);
16706               full_name[dir_len] = '/';
16707               strcpy (full_name + dir_len + 1, fe->name);
16708               return full_name;
16709             }
16710           else
16711             return xstrdup (fe->name);
16712         }
16713     }
16714   else
16715     {
16716       /* The compiler produced a bogus file number.  We can at least
16717          record the macro definitions made in the file, even if we
16718          won't be able to find the file by name.  */
16719       char fake_name[80];
16720
16721       sprintf (fake_name, "<bad macro file number %d>", file);
16722
16723       complaint (&symfile_complaints,
16724                  _("bad file number in macro information (%d)"),
16725                  file);
16726
16727       return xstrdup (fake_name);
16728     }
16729 }
16730
16731
16732 static struct macro_source_file *
16733 macro_start_file (int file, int line,
16734                   struct macro_source_file *current_file,
16735                   const char *comp_dir,
16736                   struct line_header *lh, struct objfile *objfile)
16737 {
16738   /* The full name of this source file.  */
16739   char *full_name = file_full_name (file, lh, comp_dir);
16740
16741   /* We don't create a macro table for this compilation unit
16742      at all until we actually get a filename.  */
16743   if (! pending_macros)
16744     pending_macros = new_macro_table (&objfile->objfile_obstack,
16745                                       objfile->macro_cache);
16746
16747   if (! current_file)
16748     {
16749       /* If we have no current file, then this must be the start_file
16750          directive for the compilation unit's main source file.  */
16751       current_file = macro_set_main (pending_macros, full_name);
16752       macro_define_special (pending_macros);
16753     }
16754   else
16755     current_file = macro_include (current_file, line, full_name);
16756
16757   xfree (full_name);
16758
16759   return current_file;
16760 }
16761
16762
16763 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
16764    followed by a null byte.  */
16765 static char *
16766 copy_string (const char *buf, int len)
16767 {
16768   char *s = xmalloc (len + 1);
16769
16770   memcpy (s, buf, len);
16771   s[len] = '\0';
16772   return s;
16773 }
16774
16775
16776 static const char *
16777 consume_improper_spaces (const char *p, const char *body)
16778 {
16779   if (*p == ' ')
16780     {
16781       complaint (&symfile_complaints,
16782                  _("macro definition contains spaces "
16783                    "in formal argument list:\n`%s'"),
16784                  body);
16785
16786       while (*p == ' ')
16787         p++;
16788     }
16789
16790   return p;
16791 }
16792
16793
16794 static void
16795 parse_macro_definition (struct macro_source_file *file, int line,
16796                         const char *body)
16797 {
16798   const char *p;
16799
16800   /* The body string takes one of two forms.  For object-like macro
16801      definitions, it should be:
16802
16803         <macro name> " " <definition>
16804
16805      For function-like macro definitions, it should be:
16806
16807         <macro name> "() " <definition>
16808      or
16809         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
16810
16811      Spaces may appear only where explicitly indicated, and in the
16812      <definition>.
16813
16814      The Dwarf 2 spec says that an object-like macro's name is always
16815      followed by a space, but versions of GCC around March 2002 omit
16816      the space when the macro's definition is the empty string.
16817
16818      The Dwarf 2 spec says that there should be no spaces between the
16819      formal arguments in a function-like macro's formal argument list,
16820      but versions of GCC around March 2002 include spaces after the
16821      commas.  */
16822
16823
16824   /* Find the extent of the macro name.  The macro name is terminated
16825      by either a space or null character (for an object-like macro) or
16826      an opening paren (for a function-like macro).  */
16827   for (p = body; *p; p++)
16828     if (*p == ' ' || *p == '(')
16829       break;
16830
16831   if (*p == ' ' || *p == '\0')
16832     {
16833       /* It's an object-like macro.  */
16834       int name_len = p - body;
16835       char *name = copy_string (body, name_len);
16836       const char *replacement;
16837
16838       if (*p == ' ')
16839         replacement = body + name_len + 1;
16840       else
16841         {
16842           dwarf2_macro_malformed_definition_complaint (body);
16843           replacement = body + name_len;
16844         }
16845
16846       macro_define_object (file, line, name, replacement);
16847
16848       xfree (name);
16849     }
16850   else if (*p == '(')
16851     {
16852       /* It's a function-like macro.  */
16853       char *name = copy_string (body, p - body);
16854       int argc = 0;
16855       int argv_size = 1;
16856       char **argv = xmalloc (argv_size * sizeof (*argv));
16857
16858       p++;
16859
16860       p = consume_improper_spaces (p, body);
16861
16862       /* Parse the formal argument list.  */
16863       while (*p && *p != ')')
16864         {
16865           /* Find the extent of the current argument name.  */
16866           const char *arg_start = p;
16867
16868           while (*p && *p != ',' && *p != ')' && *p != ' ')
16869             p++;
16870
16871           if (! *p || p == arg_start)
16872             dwarf2_macro_malformed_definition_complaint (body);
16873           else
16874             {
16875               /* Make sure argv has room for the new argument.  */
16876               if (argc >= argv_size)
16877                 {
16878                   argv_size *= 2;
16879                   argv = xrealloc (argv, argv_size * sizeof (*argv));
16880                 }
16881
16882               argv[argc++] = copy_string (arg_start, p - arg_start);
16883             }
16884
16885           p = consume_improper_spaces (p, body);
16886
16887           /* Consume the comma, if present.  */
16888           if (*p == ',')
16889             {
16890               p++;
16891
16892               p = consume_improper_spaces (p, body);
16893             }
16894         }
16895
16896       if (*p == ')')
16897         {
16898           p++;
16899
16900           if (*p == ' ')
16901             /* Perfectly formed definition, no complaints.  */
16902             macro_define_function (file, line, name,
16903                                    argc, (const char **) argv,
16904                                    p + 1);
16905           else if (*p == '\0')
16906             {
16907               /* Complain, but do define it.  */
16908               dwarf2_macro_malformed_definition_complaint (body);
16909               macro_define_function (file, line, name,
16910                                      argc, (const char **) argv,
16911                                      p);
16912             }
16913           else
16914             /* Just complain.  */
16915             dwarf2_macro_malformed_definition_complaint (body);
16916         }
16917       else
16918         /* Just complain.  */
16919         dwarf2_macro_malformed_definition_complaint (body);
16920
16921       xfree (name);
16922       {
16923         int i;
16924
16925         for (i = 0; i < argc; i++)
16926           xfree (argv[i]);
16927       }
16928       xfree (argv);
16929     }
16930   else
16931     dwarf2_macro_malformed_definition_complaint (body);
16932 }
16933
16934 /* Skip some bytes from BYTES according to the form given in FORM.
16935    Returns the new pointer.  */
16936
16937 static gdb_byte *
16938 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
16939                  enum dwarf_form form,
16940                  unsigned int offset_size,
16941                  struct dwarf2_section_info *section)
16942 {
16943   unsigned int bytes_read;
16944
16945   switch (form)
16946     {
16947     case DW_FORM_data1:
16948     case DW_FORM_flag:
16949       ++bytes;
16950       break;
16951
16952     case DW_FORM_data2:
16953       bytes += 2;
16954       break;
16955
16956     case DW_FORM_data4:
16957       bytes += 4;
16958       break;
16959
16960     case DW_FORM_data8:
16961       bytes += 8;
16962       break;
16963
16964     case DW_FORM_string:
16965       read_direct_string (abfd, bytes, &bytes_read);
16966       bytes += bytes_read;
16967       break;
16968
16969     case DW_FORM_sec_offset:
16970     case DW_FORM_strp:
16971       bytes += offset_size;
16972       break;
16973
16974     case DW_FORM_block:
16975       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
16976       bytes += bytes_read;
16977       break;
16978
16979     case DW_FORM_block1:
16980       bytes += 1 + read_1_byte (abfd, bytes);
16981       break;
16982     case DW_FORM_block2:
16983       bytes += 2 + read_2_bytes (abfd, bytes);
16984       break;
16985     case DW_FORM_block4:
16986       bytes += 4 + read_4_bytes (abfd, bytes);
16987       break;
16988
16989     case DW_FORM_sdata:
16990     case DW_FORM_udata:
16991     case DW_FORM_GNU_addr_index:
16992     case DW_FORM_GNU_str_index:
16993       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
16994       if (bytes == NULL)
16995         {
16996           dwarf2_section_buffer_overflow_complaint (section);
16997           return NULL;
16998         }
16999       break;
17000
17001     default:
17002       {
17003       complain:
17004         complaint (&symfile_complaints,
17005                    _("invalid form 0x%x in `%s'"),
17006                    form,
17007                    section->asection->name);
17008         return NULL;
17009       }
17010     }
17011
17012   return bytes;
17013 }
17014
17015 /* A helper for dwarf_decode_macros that handles skipping an unknown
17016    opcode.  Returns an updated pointer to the macro data buffer; or,
17017    on error, issues a complaint and returns NULL.  */
17018
17019 static gdb_byte *
17020 skip_unknown_opcode (unsigned int opcode,
17021                      gdb_byte **opcode_definitions,
17022                      gdb_byte *mac_ptr, gdb_byte *mac_end,
17023                      bfd *abfd,
17024                      unsigned int offset_size,
17025                      struct dwarf2_section_info *section)
17026 {
17027   unsigned int bytes_read, i;
17028   unsigned long arg;
17029   gdb_byte *defn;
17030
17031   if (opcode_definitions[opcode] == NULL)
17032     {
17033       complaint (&symfile_complaints,
17034                  _("unrecognized DW_MACFINO opcode 0x%x"),
17035                  opcode);
17036       return NULL;
17037     }
17038
17039   defn = opcode_definitions[opcode];
17040   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
17041   defn += bytes_read;
17042
17043   for (i = 0; i < arg; ++i)
17044     {
17045       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
17046                                  section);
17047       if (mac_ptr == NULL)
17048         {
17049           /* skip_form_bytes already issued the complaint.  */
17050           return NULL;
17051         }
17052     }
17053
17054   return mac_ptr;
17055 }
17056
17057 /* A helper function which parses the header of a macro section.
17058    If the macro section is the extended (for now called "GNU") type,
17059    then this updates *OFFSET_SIZE.  Returns a pointer to just after
17060    the header, or issues a complaint and returns NULL on error.  */
17061
17062 static gdb_byte *
17063 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
17064                           bfd *abfd,
17065                           gdb_byte *mac_ptr,
17066                           unsigned int *offset_size,
17067                           int section_is_gnu)
17068 {
17069   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
17070
17071   if (section_is_gnu)
17072     {
17073       unsigned int version, flags;
17074
17075       version = read_2_bytes (abfd, mac_ptr);
17076       if (version != 4)
17077         {
17078           complaint (&symfile_complaints,
17079                      _("unrecognized version `%d' in .debug_macro section"),
17080                      version);
17081           return NULL;
17082         }
17083       mac_ptr += 2;
17084
17085       flags = read_1_byte (abfd, mac_ptr);
17086       ++mac_ptr;
17087       *offset_size = (flags & 1) ? 8 : 4;
17088
17089       if ((flags & 2) != 0)
17090         /* We don't need the line table offset.  */
17091         mac_ptr += *offset_size;
17092
17093       /* Vendor opcode descriptions.  */
17094       if ((flags & 4) != 0)
17095         {
17096           unsigned int i, count;
17097
17098           count = read_1_byte (abfd, mac_ptr);
17099           ++mac_ptr;
17100           for (i = 0; i < count; ++i)
17101             {
17102               unsigned int opcode, bytes_read;
17103               unsigned long arg;
17104
17105               opcode = read_1_byte (abfd, mac_ptr);
17106               ++mac_ptr;
17107               opcode_definitions[opcode] = mac_ptr;
17108               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17109               mac_ptr += bytes_read;
17110               mac_ptr += arg;
17111             }
17112         }
17113     }
17114
17115   return mac_ptr;
17116 }
17117
17118 /* A helper for dwarf_decode_macros that handles the GNU extensions,
17119    including DW_MACRO_GNU_transparent_include.  */
17120
17121 static void
17122 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
17123                           struct macro_source_file *current_file,
17124                           struct line_header *lh, char *comp_dir,
17125                           struct dwarf2_section_info *section,
17126                           int section_is_gnu,
17127                           unsigned int offset_size,
17128                           struct objfile *objfile,
17129                           htab_t include_hash)
17130 {
17131   enum dwarf_macro_record_type macinfo_type;
17132   int at_commandline;
17133   gdb_byte *opcode_definitions[256];
17134
17135   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
17136                                       &offset_size, section_is_gnu);
17137   if (mac_ptr == NULL)
17138     {
17139       /* We already issued a complaint.  */
17140       return;
17141     }
17142
17143   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
17144      GDB is still reading the definitions from command line.  First
17145      DW_MACINFO_start_file will need to be ignored as it was already executed
17146      to create CURRENT_FILE for the main source holding also the command line
17147      definitions.  On first met DW_MACINFO_start_file this flag is reset to
17148      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
17149
17150   at_commandline = 1;
17151
17152   do
17153     {
17154       /* Do we at least have room for a macinfo type byte?  */
17155       if (mac_ptr >= mac_end)
17156         {
17157           dwarf2_section_buffer_overflow_complaint (section);
17158           break;
17159         }
17160
17161       macinfo_type = read_1_byte (abfd, mac_ptr);
17162       mac_ptr++;
17163
17164       /* Note that we rely on the fact that the corresponding GNU and
17165          DWARF constants are the same.  */
17166       switch (macinfo_type)
17167         {
17168           /* A zero macinfo type indicates the end of the macro
17169              information.  */
17170         case 0:
17171           break;
17172
17173         case DW_MACRO_GNU_define:
17174         case DW_MACRO_GNU_undef:
17175         case DW_MACRO_GNU_define_indirect:
17176         case DW_MACRO_GNU_undef_indirect:
17177           {
17178             unsigned int bytes_read;
17179             int line;
17180             char *body;
17181             int is_define;
17182
17183             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17184             mac_ptr += bytes_read;
17185
17186             if (macinfo_type == DW_MACRO_GNU_define
17187                 || macinfo_type == DW_MACRO_GNU_undef)
17188               {
17189                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
17190                 mac_ptr += bytes_read;
17191               }
17192             else
17193               {
17194                 LONGEST str_offset;
17195
17196                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
17197                 mac_ptr += offset_size;
17198
17199                 body = read_indirect_string_at_offset (abfd, str_offset);
17200               }
17201
17202             is_define = (macinfo_type == DW_MACRO_GNU_define
17203                          || macinfo_type == DW_MACRO_GNU_define_indirect);
17204             if (! current_file)
17205               {
17206                 /* DWARF violation as no main source is present.  */
17207                 complaint (&symfile_complaints,
17208                            _("debug info with no main source gives macro %s "
17209                              "on line %d: %s"),
17210                            is_define ? _("definition") : _("undefinition"),
17211                            line, body);
17212                 break;
17213               }
17214             if ((line == 0 && !at_commandline)
17215                 || (line != 0 && at_commandline))
17216               complaint (&symfile_complaints,
17217                          _("debug info gives %s macro %s with %s line %d: %s"),
17218                          at_commandline ? _("command-line") : _("in-file"),
17219                          is_define ? _("definition") : _("undefinition"),
17220                          line == 0 ? _("zero") : _("non-zero"), line, body);
17221
17222             if (is_define)
17223               parse_macro_definition (current_file, line, body);
17224             else
17225               {
17226                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
17227                             || macinfo_type == DW_MACRO_GNU_undef_indirect);
17228                 macro_undef (current_file, line, body);
17229               }
17230           }
17231           break;
17232
17233         case DW_MACRO_GNU_start_file:
17234           {
17235             unsigned int bytes_read;
17236             int line, file;
17237
17238             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17239             mac_ptr += bytes_read;
17240             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17241             mac_ptr += bytes_read;
17242
17243             if ((line == 0 && !at_commandline)
17244                 || (line != 0 && at_commandline))
17245               complaint (&symfile_complaints,
17246                          _("debug info gives source %d included "
17247                            "from %s at %s line %d"),
17248                          file, at_commandline ? _("command-line") : _("file"),
17249                          line == 0 ? _("zero") : _("non-zero"), line);
17250
17251             if (at_commandline)
17252               {
17253                 /* This DW_MACRO_GNU_start_file was executed in the
17254                    pass one.  */
17255                 at_commandline = 0;
17256               }
17257             else
17258               current_file = macro_start_file (file, line,
17259                                                current_file, comp_dir,
17260                                                lh, objfile);
17261           }
17262           break;
17263
17264         case DW_MACRO_GNU_end_file:
17265           if (! current_file)
17266             complaint (&symfile_complaints,
17267                        _("macro debug info has an unmatched "
17268                          "`close_file' directive"));
17269           else
17270             {
17271               current_file = current_file->included_by;
17272               if (! current_file)
17273                 {
17274                   enum dwarf_macro_record_type next_type;
17275
17276                   /* GCC circa March 2002 doesn't produce the zero
17277                      type byte marking the end of the compilation
17278                      unit.  Complain if it's not there, but exit no
17279                      matter what.  */
17280
17281                   /* Do we at least have room for a macinfo type byte?  */
17282                   if (mac_ptr >= mac_end)
17283                     {
17284                       dwarf2_section_buffer_overflow_complaint (section);
17285                       return;
17286                     }
17287
17288                   /* We don't increment mac_ptr here, so this is just
17289                      a look-ahead.  */
17290                   next_type = read_1_byte (abfd, mac_ptr);
17291                   if (next_type != 0)
17292                     complaint (&symfile_complaints,
17293                                _("no terminating 0-type entry for "
17294                                  "macros in `.debug_macinfo' section"));
17295
17296                   return;
17297                 }
17298             }
17299           break;
17300
17301         case DW_MACRO_GNU_transparent_include:
17302           {
17303             LONGEST offset;
17304             void **slot;
17305
17306             offset = read_offset_1 (abfd, mac_ptr, offset_size);
17307             mac_ptr += offset_size;
17308
17309             slot = htab_find_slot (include_hash, mac_ptr, INSERT);
17310             if (*slot != NULL)
17311               {
17312                 /* This has actually happened; see
17313                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
17314                 complaint (&symfile_complaints,
17315                            _("recursive DW_MACRO_GNU_transparent_include in "
17316                              ".debug_macro section"));
17317               }
17318             else
17319               {
17320                 *slot = mac_ptr;
17321
17322                 dwarf_decode_macro_bytes (abfd,
17323                                           section->buffer + offset,
17324                                           mac_end, current_file,
17325                                           lh, comp_dir,
17326                                           section, section_is_gnu,
17327                                           offset_size, objfile, include_hash);
17328
17329                 htab_remove_elt (include_hash, mac_ptr);
17330               }
17331           }
17332           break;
17333
17334         case DW_MACINFO_vendor_ext:
17335           if (!section_is_gnu)
17336             {
17337               unsigned int bytes_read;
17338               int constant;
17339
17340               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17341               mac_ptr += bytes_read;
17342               read_direct_string (abfd, mac_ptr, &bytes_read);
17343               mac_ptr += bytes_read;
17344
17345               /* We don't recognize any vendor extensions.  */
17346               break;
17347             }
17348           /* FALLTHROUGH */
17349
17350         default:
17351           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
17352                                          mac_ptr, mac_end, abfd, offset_size,
17353                                          section);
17354           if (mac_ptr == NULL)
17355             return;
17356           break;
17357         }
17358     } while (macinfo_type != 0);
17359 }
17360
17361 static void
17362 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
17363                      char *comp_dir, int section_is_gnu)
17364 {
17365   struct objfile *objfile = dwarf2_per_objfile->objfile;
17366   struct line_header *lh = cu->line_header;
17367   bfd *abfd;
17368   gdb_byte *mac_ptr, *mac_end;
17369   struct macro_source_file *current_file = 0;
17370   enum dwarf_macro_record_type macinfo_type;
17371   unsigned int offset_size = cu->header.offset_size;
17372   gdb_byte *opcode_definitions[256];
17373   struct cleanup *cleanup;
17374   htab_t include_hash;
17375   void **slot;
17376   struct dwarf2_section_info *section;
17377   const char *section_name;
17378
17379   if (cu->dwo_unit != NULL)
17380     {
17381       if (section_is_gnu)
17382         {
17383           section = &cu->dwo_unit->dwo_file->sections.macro;
17384           section_name = ".debug_macro.dwo";
17385         }
17386       else
17387         {
17388           section = &cu->dwo_unit->dwo_file->sections.macinfo;
17389           section_name = ".debug_macinfo.dwo";
17390         }
17391     }
17392   else
17393     {
17394       if (section_is_gnu)
17395         {
17396           section = &dwarf2_per_objfile->macro;
17397           section_name = ".debug_macro";
17398         }
17399       else
17400         {
17401           section = &dwarf2_per_objfile->macinfo;
17402           section_name = ".debug_macinfo";
17403         }
17404     }
17405
17406   dwarf2_read_section (objfile, section);
17407   if (section->buffer == NULL)
17408     {
17409       complaint (&symfile_complaints, _("missing %s section"), section_name);
17410       return;
17411     }
17412   abfd = section->asection->owner;
17413
17414   /* First pass: Find the name of the base filename.
17415      This filename is needed in order to process all macros whose definition
17416      (or undefinition) comes from the command line.  These macros are defined
17417      before the first DW_MACINFO_start_file entry, and yet still need to be
17418      associated to the base file.
17419
17420      To determine the base file name, we scan the macro definitions until we
17421      reach the first DW_MACINFO_start_file entry.  We then initialize
17422      CURRENT_FILE accordingly so that any macro definition found before the
17423      first DW_MACINFO_start_file can still be associated to the base file.  */
17424
17425   mac_ptr = section->buffer + offset;
17426   mac_end = section->buffer + section->size;
17427
17428   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
17429                                       &offset_size, section_is_gnu);
17430   if (mac_ptr == NULL)
17431     {
17432       /* We already issued a complaint.  */
17433       return;
17434     }
17435
17436   do
17437     {
17438       /* Do we at least have room for a macinfo type byte?  */
17439       if (mac_ptr >= mac_end)
17440         {
17441           /* Complaint is printed during the second pass as GDB will probably
17442              stop the first pass earlier upon finding
17443              DW_MACINFO_start_file.  */
17444           break;
17445         }
17446
17447       macinfo_type = read_1_byte (abfd, mac_ptr);
17448       mac_ptr++;
17449
17450       /* Note that we rely on the fact that the corresponding GNU and
17451          DWARF constants are the same.  */
17452       switch (macinfo_type)
17453         {
17454           /* A zero macinfo type indicates the end of the macro
17455              information.  */
17456         case 0:
17457           break;
17458
17459         case DW_MACRO_GNU_define:
17460         case DW_MACRO_GNU_undef:
17461           /* Only skip the data by MAC_PTR.  */
17462           {
17463             unsigned int bytes_read;
17464
17465             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17466             mac_ptr += bytes_read;
17467             read_direct_string (abfd, mac_ptr, &bytes_read);
17468             mac_ptr += bytes_read;
17469           }
17470           break;
17471
17472         case DW_MACRO_GNU_start_file:
17473           {
17474             unsigned int bytes_read;
17475             int line, file;
17476
17477             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17478             mac_ptr += bytes_read;
17479             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17480             mac_ptr += bytes_read;
17481
17482             current_file = macro_start_file (file, line, current_file,
17483                                              comp_dir, lh, objfile);
17484           }
17485           break;
17486
17487         case DW_MACRO_GNU_end_file:
17488           /* No data to skip by MAC_PTR.  */
17489           break;
17490
17491         case DW_MACRO_GNU_define_indirect:
17492         case DW_MACRO_GNU_undef_indirect:
17493           {
17494             unsigned int bytes_read;
17495
17496             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17497             mac_ptr += bytes_read;
17498             mac_ptr += offset_size;
17499           }
17500           break;
17501
17502         case DW_MACRO_GNU_transparent_include:
17503           /* Note that, according to the spec, a transparent include
17504              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
17505              skip this opcode.  */
17506           mac_ptr += offset_size;
17507           break;
17508
17509         case DW_MACINFO_vendor_ext:
17510           /* Only skip the data by MAC_PTR.  */
17511           if (!section_is_gnu)
17512             {
17513               unsigned int bytes_read;
17514
17515               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
17516               mac_ptr += bytes_read;
17517               read_direct_string (abfd, mac_ptr, &bytes_read);
17518               mac_ptr += bytes_read;
17519             }
17520           /* FALLTHROUGH */
17521
17522         default:
17523           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
17524                                          mac_ptr, mac_end, abfd, offset_size,
17525                                          section);
17526           if (mac_ptr == NULL)
17527             return;
17528           break;
17529         }
17530     } while (macinfo_type != 0 && current_file == NULL);
17531
17532   /* Second pass: Process all entries.
17533
17534      Use the AT_COMMAND_LINE flag to determine whether we are still processing
17535      command-line macro definitions/undefinitions.  This flag is unset when we
17536      reach the first DW_MACINFO_start_file entry.  */
17537
17538   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
17539                                     NULL, xcalloc, xfree);
17540   cleanup = make_cleanup_htab_delete (include_hash);
17541   mac_ptr = section->buffer + offset;
17542   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
17543   *slot = mac_ptr;
17544   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
17545                             current_file, lh, comp_dir, section, section_is_gnu,
17546                             offset_size, objfile, include_hash);
17547   do_cleanups (cleanup);
17548 }
17549
17550 /* Check if the attribute's form is a DW_FORM_block*
17551    if so return true else false.  */
17552
17553 static int
17554 attr_form_is_block (struct attribute *attr)
17555 {
17556   return (attr == NULL ? 0 :
17557       attr->form == DW_FORM_block1
17558       || attr->form == DW_FORM_block2
17559       || attr->form == DW_FORM_block4
17560       || attr->form == DW_FORM_block
17561       || attr->form == DW_FORM_exprloc);
17562 }
17563
17564 /* Return non-zero if ATTR's value is a section offset --- classes
17565    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
17566    You may use DW_UNSND (attr) to retrieve such offsets.
17567
17568    Section 7.5.4, "Attribute Encodings", explains that no attribute
17569    may have a value that belongs to more than one of these classes; it
17570    would be ambiguous if we did, because we use the same forms for all
17571    of them.  */
17572
17573 static int
17574 attr_form_is_section_offset (struct attribute *attr)
17575 {
17576   return (attr->form == DW_FORM_data4
17577           || attr->form == DW_FORM_data8
17578           || attr->form == DW_FORM_sec_offset);
17579 }
17580
17581 /* Return non-zero if ATTR's value falls in the 'constant' class, or
17582    zero otherwise.  When this function returns true, you can apply
17583    dwarf2_get_attr_constant_value to it.
17584
17585    However, note that for some attributes you must check
17586    attr_form_is_section_offset before using this test.  DW_FORM_data4
17587    and DW_FORM_data8 are members of both the constant class, and of
17588    the classes that contain offsets into other debug sections
17589    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
17590    that, if an attribute's can be either a constant or one of the
17591    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
17592    taken as section offsets, not constants.  */
17593
17594 static int
17595 attr_form_is_constant (struct attribute *attr)
17596 {
17597   switch (attr->form)
17598     {
17599     case DW_FORM_sdata:
17600     case DW_FORM_udata:
17601     case DW_FORM_data1:
17602     case DW_FORM_data2:
17603     case DW_FORM_data4:
17604     case DW_FORM_data8:
17605       return 1;
17606     default:
17607       return 0;
17608     }
17609 }
17610
17611 /* Return the .debug_loc section to use for CU.
17612    For DWO files use .debug_loc.dwo.  */
17613
17614 static struct dwarf2_section_info *
17615 cu_debug_loc_section (struct dwarf2_cu *cu)
17616 {
17617   if (cu->dwo_unit)
17618     return &cu->dwo_unit->dwo_file->sections.loc;
17619   return &dwarf2_per_objfile->loc;
17620 }
17621
17622 /* A helper function that fills in a dwarf2_loclist_baton.  */
17623
17624 static void
17625 fill_in_loclist_baton (struct dwarf2_cu *cu,
17626                        struct dwarf2_loclist_baton *baton,
17627                        struct attribute *attr)
17628 {
17629   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
17630
17631   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17632
17633   baton->per_cu = cu->per_cu;
17634   gdb_assert (baton->per_cu);
17635   /* We don't know how long the location list is, but make sure we
17636      don't run off the edge of the section.  */
17637   baton->size = section->size - DW_UNSND (attr);
17638   baton->data = section->buffer + DW_UNSND (attr);
17639   baton->base_address = cu->base_address;
17640   baton->from_dwo = cu->dwo_unit != NULL;
17641 }
17642
17643 static void
17644 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
17645                              struct dwarf2_cu *cu)
17646 {
17647   struct objfile *objfile = dwarf2_per_objfile->objfile;
17648   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
17649
17650   if (attr_form_is_section_offset (attr)
17651       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
17652          the section.  If so, fall through to the complaint in the
17653          other branch.  */
17654       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
17655     {
17656       struct dwarf2_loclist_baton *baton;
17657
17658       baton = obstack_alloc (&objfile->objfile_obstack,
17659                              sizeof (struct dwarf2_loclist_baton));
17660
17661       fill_in_loclist_baton (cu, baton, attr);
17662
17663       if (cu->base_known == 0)
17664         complaint (&symfile_complaints,
17665                    _("Location list used without "
17666                      "specifying the CU base address."));
17667
17668       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
17669       SYMBOL_LOCATION_BATON (sym) = baton;
17670     }
17671   else
17672     {
17673       struct dwarf2_locexpr_baton *baton;
17674
17675       baton = obstack_alloc (&objfile->objfile_obstack,
17676                              sizeof (struct dwarf2_locexpr_baton));
17677       baton->per_cu = cu->per_cu;
17678       gdb_assert (baton->per_cu);
17679
17680       if (attr_form_is_block (attr))
17681         {
17682           /* Note that we're just copying the block's data pointer
17683              here, not the actual data.  We're still pointing into the
17684              info_buffer for SYM's objfile; right now we never release
17685              that buffer, but when we do clean up properly this may
17686              need to change.  */
17687           baton->size = DW_BLOCK (attr)->size;
17688           baton->data = DW_BLOCK (attr)->data;
17689         }
17690       else
17691         {
17692           dwarf2_invalid_attrib_class_complaint ("location description",
17693                                                  SYMBOL_NATURAL_NAME (sym));
17694           baton->size = 0;
17695         }
17696
17697       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
17698       SYMBOL_LOCATION_BATON (sym) = baton;
17699     }
17700 }
17701
17702 /* Return the OBJFILE associated with the compilation unit CU.  If CU
17703    came from a separate debuginfo file, then the master objfile is
17704    returned.  */
17705
17706 struct objfile *
17707 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
17708 {
17709   struct objfile *objfile = per_cu->objfile;
17710
17711   /* Return the master objfile, so that we can report and look up the
17712      correct file containing this variable.  */
17713   if (objfile->separate_debug_objfile_backlink)
17714     objfile = objfile->separate_debug_objfile_backlink;
17715
17716   return objfile;
17717 }
17718
17719 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
17720    (CU_HEADERP is unused in such case) or prepare a temporary copy at
17721    CU_HEADERP first.  */
17722
17723 static const struct comp_unit_head *
17724 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
17725                        struct dwarf2_per_cu_data *per_cu)
17726 {
17727   gdb_byte *info_ptr;
17728
17729   if (per_cu->cu)
17730     return &per_cu->cu->header;
17731
17732   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
17733
17734   memset (cu_headerp, 0, sizeof (*cu_headerp));
17735   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
17736
17737   return cu_headerp;
17738 }
17739
17740 /* Return the address size given in the compilation unit header for CU.  */
17741
17742 int
17743 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
17744 {
17745   struct comp_unit_head cu_header_local;
17746   const struct comp_unit_head *cu_headerp;
17747
17748   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
17749
17750   return cu_headerp->addr_size;
17751 }
17752
17753 /* Return the offset size given in the compilation unit header for CU.  */
17754
17755 int
17756 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
17757 {
17758   struct comp_unit_head cu_header_local;
17759   const struct comp_unit_head *cu_headerp;
17760
17761   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
17762
17763   return cu_headerp->offset_size;
17764 }
17765
17766 /* See its dwarf2loc.h declaration.  */
17767
17768 int
17769 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
17770 {
17771   struct comp_unit_head cu_header_local;
17772   const struct comp_unit_head *cu_headerp;
17773
17774   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
17775
17776   if (cu_headerp->version == 2)
17777     return cu_headerp->addr_size;
17778   else
17779     return cu_headerp->offset_size;
17780 }
17781
17782 /* Return the text offset of the CU.  The returned offset comes from
17783    this CU's objfile.  If this objfile came from a separate debuginfo
17784    file, then the offset may be different from the corresponding
17785    offset in the parent objfile.  */
17786
17787 CORE_ADDR
17788 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
17789 {
17790   struct objfile *objfile = per_cu->objfile;
17791
17792   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17793 }
17794
17795 /* Locate the .debug_info compilation unit from CU's objfile which contains
17796    the DIE at OFFSET.  Raises an error on failure.  */
17797
17798 static struct dwarf2_per_cu_data *
17799 dwarf2_find_containing_comp_unit (sect_offset offset,
17800                                   struct objfile *objfile)
17801 {
17802   struct dwarf2_per_cu_data *this_cu;
17803   int low, high;
17804
17805   low = 0;
17806   high = dwarf2_per_objfile->n_comp_units - 1;
17807   while (high > low)
17808     {
17809       int mid = low + (high - low) / 2;
17810
17811       if (dwarf2_per_objfile->all_comp_units[mid]->offset.sect_off
17812           >= offset.sect_off)
17813         high = mid;
17814       else
17815         low = mid + 1;
17816     }
17817   gdb_assert (low == high);
17818   if (dwarf2_per_objfile->all_comp_units[low]->offset.sect_off
17819       > offset.sect_off)
17820     {
17821       if (low == 0)
17822         error (_("Dwarf Error: could not find partial DIE containing "
17823                "offset 0x%lx [in module %s]"),
17824                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
17825
17826       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
17827                   <= offset.sect_off);
17828       return dwarf2_per_objfile->all_comp_units[low-1];
17829     }
17830   else
17831     {
17832       this_cu = dwarf2_per_objfile->all_comp_units[low];
17833       if (low == dwarf2_per_objfile->n_comp_units - 1
17834           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
17835         error (_("invalid dwarf2 offset %u"), offset.sect_off);
17836       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
17837       return this_cu;
17838     }
17839 }
17840
17841 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
17842
17843 static void
17844 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
17845 {
17846   memset (cu, 0, sizeof (*cu));
17847   per_cu->cu = cu;
17848   cu->per_cu = per_cu;
17849   cu->objfile = per_cu->objfile;
17850   obstack_init (&cu->comp_unit_obstack);
17851 }
17852
17853 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
17854
17855 static void
17856 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
17857                        enum language pretend_language)
17858 {
17859   struct attribute *attr;
17860
17861   /* Set the language we're debugging.  */
17862   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
17863   if (attr)
17864     set_cu_language (DW_UNSND (attr), cu);
17865   else
17866     {
17867       cu->language = pretend_language;
17868       cu->language_defn = language_def (cu->language);
17869     }
17870
17871   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
17872   if (attr)
17873     cu->producer = DW_STRING (attr);
17874 }
17875
17876 /* Release one cached compilation unit, CU.  We unlink it from the tree
17877    of compilation units, but we don't remove it from the read_in_chain;
17878    the caller is responsible for that.
17879    NOTE: DATA is a void * because this function is also used as a
17880    cleanup routine.  */
17881
17882 static void
17883 free_heap_comp_unit (void *data)
17884 {
17885   struct dwarf2_cu *cu = data;
17886
17887   gdb_assert (cu->per_cu != NULL);
17888   cu->per_cu->cu = NULL;
17889   cu->per_cu = NULL;
17890
17891   obstack_free (&cu->comp_unit_obstack, NULL);
17892
17893   xfree (cu);
17894 }
17895
17896 /* This cleanup function is passed the address of a dwarf2_cu on the stack
17897    when we're finished with it.  We can't free the pointer itself, but be
17898    sure to unlink it from the cache.  Also release any associated storage.  */
17899
17900 static void
17901 free_stack_comp_unit (void *data)
17902 {
17903   struct dwarf2_cu *cu = data;
17904
17905   gdb_assert (cu->per_cu != NULL);
17906   cu->per_cu->cu = NULL;
17907   cu->per_cu = NULL;
17908
17909   obstack_free (&cu->comp_unit_obstack, NULL);
17910   cu->partial_dies = NULL;
17911 }
17912
17913 /* Free all cached compilation units.  */
17914
17915 static void
17916 free_cached_comp_units (void *data)
17917 {
17918   struct dwarf2_per_cu_data *per_cu, **last_chain;
17919
17920   per_cu = dwarf2_per_objfile->read_in_chain;
17921   last_chain = &dwarf2_per_objfile->read_in_chain;
17922   while (per_cu != NULL)
17923     {
17924       struct dwarf2_per_cu_data *next_cu;
17925
17926       next_cu = per_cu->cu->read_in_chain;
17927
17928       free_heap_comp_unit (per_cu->cu);
17929       *last_chain = next_cu;
17930
17931       per_cu = next_cu;
17932     }
17933 }
17934
17935 /* Increase the age counter on each cached compilation unit, and free
17936    any that are too old.  */
17937
17938 static void
17939 age_cached_comp_units (void)
17940 {
17941   struct dwarf2_per_cu_data *per_cu, **last_chain;
17942
17943   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
17944   per_cu = dwarf2_per_objfile->read_in_chain;
17945   while (per_cu != NULL)
17946     {
17947       per_cu->cu->last_used ++;
17948       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
17949         dwarf2_mark (per_cu->cu);
17950       per_cu = per_cu->cu->read_in_chain;
17951     }
17952
17953   per_cu = dwarf2_per_objfile->read_in_chain;
17954   last_chain = &dwarf2_per_objfile->read_in_chain;
17955   while (per_cu != NULL)
17956     {
17957       struct dwarf2_per_cu_data *next_cu;
17958
17959       next_cu = per_cu->cu->read_in_chain;
17960
17961       if (!per_cu->cu->mark)
17962         {
17963           free_heap_comp_unit (per_cu->cu);
17964           *last_chain = next_cu;
17965         }
17966       else
17967         last_chain = &per_cu->cu->read_in_chain;
17968
17969       per_cu = next_cu;
17970     }
17971 }
17972
17973 /* Remove a single compilation unit from the cache.  */
17974
17975 static void
17976 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
17977 {
17978   struct dwarf2_per_cu_data *per_cu, **last_chain;
17979
17980   per_cu = dwarf2_per_objfile->read_in_chain;
17981   last_chain = &dwarf2_per_objfile->read_in_chain;
17982   while (per_cu != NULL)
17983     {
17984       struct dwarf2_per_cu_data *next_cu;
17985
17986       next_cu = per_cu->cu->read_in_chain;
17987
17988       if (per_cu == target_per_cu)
17989         {
17990           free_heap_comp_unit (per_cu->cu);
17991           per_cu->cu = NULL;
17992           *last_chain = next_cu;
17993           break;
17994         }
17995       else
17996         last_chain = &per_cu->cu->read_in_chain;
17997
17998       per_cu = next_cu;
17999     }
18000 }
18001
18002 /* Release all extra memory associated with OBJFILE.  */
18003
18004 void
18005 dwarf2_free_objfile (struct objfile *objfile)
18006 {
18007   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
18008
18009   if (dwarf2_per_objfile == NULL)
18010     return;
18011
18012   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
18013   free_cached_comp_units (NULL);
18014
18015   if (dwarf2_per_objfile->quick_file_names_table)
18016     htab_delete (dwarf2_per_objfile->quick_file_names_table);
18017
18018   /* Everything else should be on the objfile obstack.  */
18019 }
18020
18021 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
18022    We store these in a hash table separate from the DIEs, and preserve them
18023    when the DIEs are flushed out of cache.
18024
18025    The CU "per_cu" pointer is needed because offset alone is not enough to
18026    uniquely identify the type.  A file may have multiple .debug_types sections,
18027    or the type may come from a DWO file.  We have to use something in
18028    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
18029    routine, get_die_type_at_offset, from outside this file, and thus won't
18030    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
18031    of the objfile.  */
18032
18033 struct dwarf2_per_cu_offset_and_type
18034 {
18035   const struct dwarf2_per_cu_data *per_cu;
18036   sect_offset offset;
18037   struct type *type;
18038 };
18039
18040 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
18041
18042 static hashval_t
18043 per_cu_offset_and_type_hash (const void *item)
18044 {
18045   const struct dwarf2_per_cu_offset_and_type *ofs = item;
18046
18047   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
18048 }
18049
18050 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
18051
18052 static int
18053 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
18054 {
18055   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
18056   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
18057
18058   return (ofs_lhs->per_cu == ofs_rhs->per_cu
18059           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
18060 }
18061
18062 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
18063    table if necessary.  For convenience, return TYPE.
18064
18065    The DIEs reading must have careful ordering to:
18066     * Not cause infite loops trying to read in DIEs as a prerequisite for
18067       reading current DIE.
18068     * Not trying to dereference contents of still incompletely read in types
18069       while reading in other DIEs.
18070     * Enable referencing still incompletely read in types just by a pointer to
18071       the type without accessing its fields.
18072
18073    Therefore caller should follow these rules:
18074      * Try to fetch any prerequisite types we may need to build this DIE type
18075        before building the type and calling set_die_type.
18076      * After building type call set_die_type for current DIE as soon as
18077        possible before fetching more types to complete the current type.
18078      * Make the type as complete as possible before fetching more types.  */
18079
18080 static struct type *
18081 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
18082 {
18083   struct dwarf2_per_cu_offset_and_type **slot, ofs;
18084   struct objfile *objfile = cu->objfile;
18085
18086   /* For Ada types, make sure that the gnat-specific data is always
18087      initialized (if not already set).  There are a few types where
18088      we should not be doing so, because the type-specific area is
18089      already used to hold some other piece of info (eg: TYPE_CODE_FLT
18090      where the type-specific area is used to store the floatformat).
18091      But this is not a problem, because the gnat-specific information
18092      is actually not needed for these types.  */
18093   if (need_gnat_info (cu)
18094       && TYPE_CODE (type) != TYPE_CODE_FUNC
18095       && TYPE_CODE (type) != TYPE_CODE_FLT
18096       && !HAVE_GNAT_AUX_INFO (type))
18097     INIT_GNAT_SPECIFIC (type);
18098
18099   if (dwarf2_per_objfile->die_type_hash == NULL)
18100     {
18101       dwarf2_per_objfile->die_type_hash =
18102         htab_create_alloc_ex (127,
18103                               per_cu_offset_and_type_hash,
18104                               per_cu_offset_and_type_eq,
18105                               NULL,
18106                               &objfile->objfile_obstack,
18107                               hashtab_obstack_allocate,
18108                               dummy_obstack_deallocate);
18109     }
18110
18111   ofs.per_cu = cu->per_cu;
18112   ofs.offset = die->offset;
18113   ofs.type = type;
18114   slot = (struct dwarf2_per_cu_offset_and_type **)
18115     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
18116   if (*slot)
18117     complaint (&symfile_complaints,
18118                _("A problem internal to GDB: DIE 0x%x has type already set"),
18119                die->offset.sect_off);
18120   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
18121   **slot = ofs;
18122   return type;
18123 }
18124
18125 /* Look up the type for the die at OFFSET in the appropriate type_hash
18126    table, or return NULL if the die does not have a saved type.  */
18127
18128 static struct type *
18129 get_die_type_at_offset (sect_offset offset,
18130                         struct dwarf2_per_cu_data *per_cu)
18131 {
18132   struct dwarf2_per_cu_offset_and_type *slot, ofs;
18133
18134   if (dwarf2_per_objfile->die_type_hash == NULL)
18135     return NULL;
18136
18137   ofs.per_cu = per_cu;
18138   ofs.offset = offset;
18139   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
18140   if (slot)
18141     return slot->type;
18142   else
18143     return NULL;
18144 }
18145
18146 /* Look up the type for DIE in the appropriate type_hash table,
18147    or return NULL if DIE does not have a saved type.  */
18148
18149 static struct type *
18150 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
18151 {
18152   return get_die_type_at_offset (die->offset, cu->per_cu);
18153 }
18154
18155 /* Add a dependence relationship from CU to REF_PER_CU.  */
18156
18157 static void
18158 dwarf2_add_dependence (struct dwarf2_cu *cu,
18159                        struct dwarf2_per_cu_data *ref_per_cu)
18160 {
18161   void **slot;
18162
18163   if (cu->dependencies == NULL)
18164     cu->dependencies
18165       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
18166                               NULL, &cu->comp_unit_obstack,
18167                               hashtab_obstack_allocate,
18168                               dummy_obstack_deallocate);
18169
18170   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
18171   if (*slot == NULL)
18172     *slot = ref_per_cu;
18173 }
18174
18175 /* Subroutine of dwarf2_mark to pass to htab_traverse.
18176    Set the mark field in every compilation unit in the
18177    cache that we must keep because we are keeping CU.  */
18178
18179 static int
18180 dwarf2_mark_helper (void **slot, void *data)
18181 {
18182   struct dwarf2_per_cu_data *per_cu;
18183
18184   per_cu = (struct dwarf2_per_cu_data *) *slot;
18185
18186   /* cu->dependencies references may not yet have been ever read if QUIT aborts
18187      reading of the chain.  As such dependencies remain valid it is not much
18188      useful to track and undo them during QUIT cleanups.  */
18189   if (per_cu->cu == NULL)
18190     return 1;
18191
18192   if (per_cu->cu->mark)
18193     return 1;
18194   per_cu->cu->mark = 1;
18195
18196   if (per_cu->cu->dependencies != NULL)
18197     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
18198
18199   return 1;
18200 }
18201
18202 /* Set the mark field in CU and in every other compilation unit in the
18203    cache that we must keep because we are keeping CU.  */
18204
18205 static void
18206 dwarf2_mark (struct dwarf2_cu *cu)
18207 {
18208   if (cu->mark)
18209     return;
18210   cu->mark = 1;
18211   if (cu->dependencies != NULL)
18212     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
18213 }
18214
18215 static void
18216 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
18217 {
18218   while (per_cu)
18219     {
18220       per_cu->cu->mark = 0;
18221       per_cu = per_cu->cu->read_in_chain;
18222     }
18223 }
18224
18225 /* Trivial hash function for partial_die_info: the hash value of a DIE
18226    is its offset in .debug_info for this objfile.  */
18227
18228 static hashval_t
18229 partial_die_hash (const void *item)
18230 {
18231   const struct partial_die_info *part_die = item;
18232
18233   return part_die->offset.sect_off;
18234 }
18235
18236 /* Trivial comparison function for partial_die_info structures: two DIEs
18237    are equal if they have the same offset.  */
18238
18239 static int
18240 partial_die_eq (const void *item_lhs, const void *item_rhs)
18241 {
18242   const struct partial_die_info *part_die_lhs = item_lhs;
18243   const struct partial_die_info *part_die_rhs = item_rhs;
18244
18245   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
18246 }
18247
18248 static struct cmd_list_element *set_dwarf2_cmdlist;
18249 static struct cmd_list_element *show_dwarf2_cmdlist;
18250
18251 static void
18252 set_dwarf2_cmd (char *args, int from_tty)
18253 {
18254   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
18255 }
18256
18257 static void
18258 show_dwarf2_cmd (char *args, int from_tty)
18259 {
18260   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
18261 }
18262
18263 /* If section described by INFO was mmapped, munmap it now.  */
18264
18265 static void
18266 munmap_section_buffer (struct dwarf2_section_info *info)
18267 {
18268   if (info->map_addr != NULL)
18269     {
18270 #ifdef HAVE_MMAP
18271       int res;
18272
18273       res = munmap (info->map_addr, info->map_len);
18274       gdb_assert (res == 0);
18275 #else
18276       /* Without HAVE_MMAP, we should never be here to begin with.  */
18277       gdb_assert_not_reached ("no mmap support");
18278 #endif
18279     }
18280 }
18281
18282 /* munmap debug sections for OBJFILE, if necessary.  */
18283
18284 static void
18285 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
18286 {
18287   struct dwarf2_per_objfile *data = d;
18288   int ix;
18289   struct dwarf2_section_info *section;
18290
18291   /* This is sorted according to the order they're defined in to make it easier
18292      to keep in sync.  */
18293   munmap_section_buffer (&data->info);
18294   munmap_section_buffer (&data->abbrev);
18295   munmap_section_buffer (&data->line);
18296   munmap_section_buffer (&data->loc);
18297   munmap_section_buffer (&data->macinfo);
18298   munmap_section_buffer (&data->macro);
18299   munmap_section_buffer (&data->str);
18300   munmap_section_buffer (&data->ranges);
18301   munmap_section_buffer (&data->addr);
18302   munmap_section_buffer (&data->frame);
18303   munmap_section_buffer (&data->eh_frame);
18304   munmap_section_buffer (&data->gdb_index);
18305
18306   for (ix = 0;
18307        VEC_iterate (dwarf2_section_info_def, data->types, ix, section);
18308        ++ix)
18309     munmap_section_buffer (section);
18310
18311   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
18312     VEC_free (dwarf2_per_cu_ptr,
18313               dwarf2_per_objfile->all_comp_units[ix]->s.imported_symtabs);
18314
18315   VEC_free (dwarf2_section_info_def, data->types);
18316
18317   if (data->dwo_files)
18318     free_dwo_files (data->dwo_files, objfile);
18319 }
18320
18321 \f
18322 /* The "save gdb-index" command.  */
18323
18324 /* The contents of the hash table we create when building the string
18325    table.  */
18326 struct strtab_entry
18327 {
18328   offset_type offset;
18329   const char *str;
18330 };
18331
18332 /* Hash function for a strtab_entry.
18333
18334    Function is used only during write_hash_table so no index format backward
18335    compatibility is needed.  */
18336
18337 static hashval_t
18338 hash_strtab_entry (const void *e)
18339 {
18340   const struct strtab_entry *entry = e;
18341   return mapped_index_string_hash (INT_MAX, entry->str);
18342 }
18343
18344 /* Equality function for a strtab_entry.  */
18345
18346 static int
18347 eq_strtab_entry (const void *a, const void *b)
18348 {
18349   const struct strtab_entry *ea = a;
18350   const struct strtab_entry *eb = b;
18351   return !strcmp (ea->str, eb->str);
18352 }
18353
18354 /* Create a strtab_entry hash table.  */
18355
18356 static htab_t
18357 create_strtab (void)
18358 {
18359   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
18360                             xfree, xcalloc, xfree);
18361 }
18362
18363 /* Add a string to the constant pool.  Return the string's offset in
18364    host order.  */
18365
18366 static offset_type
18367 add_string (htab_t table, struct obstack *cpool, const char *str)
18368 {
18369   void **slot;
18370   struct strtab_entry entry;
18371   struct strtab_entry *result;
18372
18373   entry.str = str;
18374   slot = htab_find_slot (table, &entry, INSERT);
18375   if (*slot)
18376     result = *slot;
18377   else
18378     {
18379       result = XNEW (struct strtab_entry);
18380       result->offset = obstack_object_size (cpool);
18381       result->str = str;
18382       obstack_grow_str0 (cpool, str);
18383       *slot = result;
18384     }
18385   return result->offset;
18386 }
18387
18388 /* An entry in the symbol table.  */
18389 struct symtab_index_entry
18390 {
18391   /* The name of the symbol.  */
18392   const char *name;
18393   /* The offset of the name in the constant pool.  */
18394   offset_type index_offset;
18395   /* A sorted vector of the indices of all the CUs that hold an object
18396      of this name.  */
18397   VEC (offset_type) *cu_indices;
18398 };
18399
18400 /* The symbol table.  This is a power-of-2-sized hash table.  */
18401 struct mapped_symtab
18402 {
18403   offset_type n_elements;
18404   offset_type size;
18405   struct symtab_index_entry **data;
18406 };
18407
18408 /* Hash function for a symtab_index_entry.  */
18409
18410 static hashval_t
18411 hash_symtab_entry (const void *e)
18412 {
18413   const struct symtab_index_entry *entry = e;
18414   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
18415                          sizeof (offset_type) * VEC_length (offset_type,
18416                                                             entry->cu_indices),
18417                          0);
18418 }
18419
18420 /* Equality function for a symtab_index_entry.  */
18421
18422 static int
18423 eq_symtab_entry (const void *a, const void *b)
18424 {
18425   const struct symtab_index_entry *ea = a;
18426   const struct symtab_index_entry *eb = b;
18427   int len = VEC_length (offset_type, ea->cu_indices);
18428   if (len != VEC_length (offset_type, eb->cu_indices))
18429     return 0;
18430   return !memcmp (VEC_address (offset_type, ea->cu_indices),
18431                   VEC_address (offset_type, eb->cu_indices),
18432                   sizeof (offset_type) * len);
18433 }
18434
18435 /* Destroy a symtab_index_entry.  */
18436
18437 static void
18438 delete_symtab_entry (void *p)
18439 {
18440   struct symtab_index_entry *entry = p;
18441   VEC_free (offset_type, entry->cu_indices);
18442   xfree (entry);
18443 }
18444
18445 /* Create a hash table holding symtab_index_entry objects.  */
18446
18447 static htab_t
18448 create_symbol_hash_table (void)
18449 {
18450   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
18451                             delete_symtab_entry, xcalloc, xfree);
18452 }
18453
18454 /* Create a new mapped symtab object.  */
18455
18456 static struct mapped_symtab *
18457 create_mapped_symtab (void)
18458 {
18459   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
18460   symtab->n_elements = 0;
18461   symtab->size = 1024;
18462   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
18463   return symtab;
18464 }
18465
18466 /* Destroy a mapped_symtab.  */
18467
18468 static void
18469 cleanup_mapped_symtab (void *p)
18470 {
18471   struct mapped_symtab *symtab = p;
18472   /* The contents of the array are freed when the other hash table is
18473      destroyed.  */
18474   xfree (symtab->data);
18475   xfree (symtab);
18476 }
18477
18478 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
18479    the slot.
18480    
18481    Function is used only during write_hash_table so no index format backward
18482    compatibility is needed.  */
18483
18484 static struct symtab_index_entry **
18485 find_slot (struct mapped_symtab *symtab, const char *name)
18486 {
18487   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
18488
18489   index = hash & (symtab->size - 1);
18490   step = ((hash * 17) & (symtab->size - 1)) | 1;
18491
18492   for (;;)
18493     {
18494       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
18495         return &symtab->data[index];
18496       index = (index + step) & (symtab->size - 1);
18497     }
18498 }
18499
18500 /* Expand SYMTAB's hash table.  */
18501
18502 static void
18503 hash_expand (struct mapped_symtab *symtab)
18504 {
18505   offset_type old_size = symtab->size;
18506   offset_type i;
18507   struct symtab_index_entry **old_entries = symtab->data;
18508
18509   symtab->size *= 2;
18510   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
18511
18512   for (i = 0; i < old_size; ++i)
18513     {
18514       if (old_entries[i])
18515         {
18516           struct symtab_index_entry **slot = find_slot (symtab,
18517                                                         old_entries[i]->name);
18518           *slot = old_entries[i];
18519         }
18520     }
18521
18522   xfree (old_entries);
18523 }
18524
18525 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
18526    CU_INDEX is the index of the CU in which the symbol appears.
18527    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
18528
18529 static void
18530 add_index_entry (struct mapped_symtab *symtab, const char *name,
18531                  int is_static, gdb_index_symbol_kind kind,
18532                  offset_type cu_index)
18533 {
18534   struct symtab_index_entry **slot;
18535   offset_type cu_index_and_attrs;
18536
18537   ++symtab->n_elements;
18538   if (4 * symtab->n_elements / 3 >= symtab->size)
18539     hash_expand (symtab);
18540
18541   slot = find_slot (symtab, name);
18542   if (!*slot)
18543     {
18544       *slot = XNEW (struct symtab_index_entry);
18545       (*slot)->name = name;
18546       /* index_offset is set later.  */
18547       (*slot)->cu_indices = NULL;
18548     }
18549
18550   cu_index_and_attrs = 0;
18551   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
18552   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
18553   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
18554
18555   /* We don't want to record an index value twice as we want to avoid the
18556      duplication.
18557      We process all global symbols and then all static symbols
18558      (which would allow us to avoid the duplication by only having to check
18559      the last entry pushed), but a symbol could have multiple kinds in one CU.
18560      To keep things simple we don't worry about the duplication here and
18561      sort and uniqufy the list after we've processed all symbols.  */
18562   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
18563 }
18564
18565 /* qsort helper routine for uniquify_cu_indices.  */
18566
18567 static int
18568 offset_type_compare (const void *ap, const void *bp)
18569 {
18570   offset_type a = *(offset_type *) ap;
18571   offset_type b = *(offset_type *) bp;
18572
18573   return (a > b) - (b > a);
18574 }
18575
18576 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
18577
18578 static void
18579 uniquify_cu_indices (struct mapped_symtab *symtab)
18580 {
18581   int i;
18582
18583   for (i = 0; i < symtab->size; ++i)
18584     {
18585       struct symtab_index_entry *entry = symtab->data[i];
18586
18587       if (entry
18588           && entry->cu_indices != NULL)
18589         {
18590           unsigned int next_to_insert, next_to_check;
18591           offset_type last_value;
18592
18593           qsort (VEC_address (offset_type, entry->cu_indices),
18594                  VEC_length (offset_type, entry->cu_indices),
18595                  sizeof (offset_type), offset_type_compare);
18596
18597           last_value = VEC_index (offset_type, entry->cu_indices, 0);
18598           next_to_insert = 1;
18599           for (next_to_check = 1;
18600                next_to_check < VEC_length (offset_type, entry->cu_indices);
18601                ++next_to_check)
18602             {
18603               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
18604                   != last_value)
18605                 {
18606                   last_value = VEC_index (offset_type, entry->cu_indices,
18607                                           next_to_check);
18608                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
18609                                last_value);
18610                   ++next_to_insert;
18611                 }
18612             }
18613           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
18614         }
18615     }
18616 }
18617
18618 /* Add a vector of indices to the constant pool.  */
18619
18620 static offset_type
18621 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
18622                       struct symtab_index_entry *entry)
18623 {
18624   void **slot;
18625
18626   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
18627   if (!*slot)
18628     {
18629       offset_type len = VEC_length (offset_type, entry->cu_indices);
18630       offset_type val = MAYBE_SWAP (len);
18631       offset_type iter;
18632       int i;
18633
18634       *slot = entry;
18635       entry->index_offset = obstack_object_size (cpool);
18636
18637       obstack_grow (cpool, &val, sizeof (val));
18638       for (i = 0;
18639            VEC_iterate (offset_type, entry->cu_indices, i, iter);
18640            ++i)
18641         {
18642           val = MAYBE_SWAP (iter);
18643           obstack_grow (cpool, &val, sizeof (val));
18644         }
18645     }
18646   else
18647     {
18648       struct symtab_index_entry *old_entry = *slot;
18649       entry->index_offset = old_entry->index_offset;
18650       entry = old_entry;
18651     }
18652   return entry->index_offset;
18653 }
18654
18655 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
18656    constant pool entries going into the obstack CPOOL.  */
18657
18658 static void
18659 write_hash_table (struct mapped_symtab *symtab,
18660                   struct obstack *output, struct obstack *cpool)
18661 {
18662   offset_type i;
18663   htab_t symbol_hash_table;
18664   htab_t str_table;
18665
18666   symbol_hash_table = create_symbol_hash_table ();
18667   str_table = create_strtab ();
18668
18669   /* We add all the index vectors to the constant pool first, to
18670      ensure alignment is ok.  */
18671   for (i = 0; i < symtab->size; ++i)
18672     {
18673       if (symtab->data[i])
18674         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
18675     }
18676
18677   /* Now write out the hash table.  */
18678   for (i = 0; i < symtab->size; ++i)
18679     {
18680       offset_type str_off, vec_off;
18681
18682       if (symtab->data[i])
18683         {
18684           str_off = add_string (str_table, cpool, symtab->data[i]->name);
18685           vec_off = symtab->data[i]->index_offset;
18686         }
18687       else
18688         {
18689           /* While 0 is a valid constant pool index, it is not valid
18690              to have 0 for both offsets.  */
18691           str_off = 0;
18692           vec_off = 0;
18693         }
18694
18695       str_off = MAYBE_SWAP (str_off);
18696       vec_off = MAYBE_SWAP (vec_off);
18697
18698       obstack_grow (output, &str_off, sizeof (str_off));
18699       obstack_grow (output, &vec_off, sizeof (vec_off));
18700     }
18701
18702   htab_delete (str_table);
18703   htab_delete (symbol_hash_table);
18704 }
18705
18706 /* Struct to map psymtab to CU index in the index file.  */
18707 struct psymtab_cu_index_map
18708 {
18709   struct partial_symtab *psymtab;
18710   unsigned int cu_index;
18711 };
18712
18713 static hashval_t
18714 hash_psymtab_cu_index (const void *item)
18715 {
18716   const struct psymtab_cu_index_map *map = item;
18717
18718   return htab_hash_pointer (map->psymtab);
18719 }
18720
18721 static int
18722 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
18723 {
18724   const struct psymtab_cu_index_map *lhs = item_lhs;
18725   const struct psymtab_cu_index_map *rhs = item_rhs;
18726
18727   return lhs->psymtab == rhs->psymtab;
18728 }
18729
18730 /* Helper struct for building the address table.  */
18731 struct addrmap_index_data
18732 {
18733   struct objfile *objfile;
18734   struct obstack *addr_obstack;
18735   htab_t cu_index_htab;
18736
18737   /* Non-zero if the previous_* fields are valid.
18738      We can't write an entry until we see the next entry (since it is only then
18739      that we know the end of the entry).  */
18740   int previous_valid;
18741   /* Index of the CU in the table of all CUs in the index file.  */
18742   unsigned int previous_cu_index;
18743   /* Start address of the CU.  */
18744   CORE_ADDR previous_cu_start;
18745 };
18746
18747 /* Write an address entry to OBSTACK.  */
18748
18749 static void
18750 add_address_entry (struct objfile *objfile, struct obstack *obstack,
18751                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
18752 {
18753   offset_type cu_index_to_write;
18754   char addr[8];
18755   CORE_ADDR baseaddr;
18756
18757   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18758
18759   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
18760   obstack_grow (obstack, addr, 8);
18761   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
18762   obstack_grow (obstack, addr, 8);
18763   cu_index_to_write = MAYBE_SWAP (cu_index);
18764   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
18765 }
18766
18767 /* Worker function for traversing an addrmap to build the address table.  */
18768
18769 static int
18770 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
18771 {
18772   struct addrmap_index_data *data = datap;
18773   struct partial_symtab *pst = obj;
18774
18775   if (data->previous_valid)
18776     add_address_entry (data->objfile, data->addr_obstack,
18777                        data->previous_cu_start, start_addr,
18778                        data->previous_cu_index);
18779
18780   data->previous_cu_start = start_addr;
18781   if (pst != NULL)
18782     {
18783       struct psymtab_cu_index_map find_map, *map;
18784       find_map.psymtab = pst;
18785       map = htab_find (data->cu_index_htab, &find_map);
18786       gdb_assert (map != NULL);
18787       data->previous_cu_index = map->cu_index;
18788       data->previous_valid = 1;
18789     }
18790   else
18791       data->previous_valid = 0;
18792
18793   return 0;
18794 }
18795
18796 /* Write OBJFILE's address map to OBSTACK.
18797    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
18798    in the index file.  */
18799
18800 static void
18801 write_address_map (struct objfile *objfile, struct obstack *obstack,
18802                    htab_t cu_index_htab)
18803 {
18804   struct addrmap_index_data addrmap_index_data;
18805
18806   /* When writing the address table, we have to cope with the fact that
18807      the addrmap iterator only provides the start of a region; we have to
18808      wait until the next invocation to get the start of the next region.  */
18809
18810   addrmap_index_data.objfile = objfile;
18811   addrmap_index_data.addr_obstack = obstack;
18812   addrmap_index_data.cu_index_htab = cu_index_htab;
18813   addrmap_index_data.previous_valid = 0;
18814
18815   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
18816                    &addrmap_index_data);
18817
18818   /* It's highly unlikely the last entry (end address = 0xff...ff)
18819      is valid, but we should still handle it.
18820      The end address is recorded as the start of the next region, but that
18821      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
18822      anyway.  */
18823   if (addrmap_index_data.previous_valid)
18824     add_address_entry (objfile, obstack,
18825                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
18826                        addrmap_index_data.previous_cu_index);
18827 }
18828
18829 /* Return the symbol kind of PSYM.  */
18830
18831 static gdb_index_symbol_kind
18832 symbol_kind (struct partial_symbol *psym)
18833 {
18834   domain_enum domain = PSYMBOL_DOMAIN (psym);
18835   enum address_class aclass = PSYMBOL_CLASS (psym);
18836
18837   switch (domain)
18838     {
18839     case VAR_DOMAIN:
18840       switch (aclass)
18841         {
18842         case LOC_BLOCK:
18843           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
18844         case LOC_TYPEDEF:
18845           return GDB_INDEX_SYMBOL_KIND_TYPE;
18846         case LOC_COMPUTED:
18847         case LOC_CONST_BYTES:
18848         case LOC_OPTIMIZED_OUT:
18849         case LOC_STATIC:
18850           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
18851         case LOC_CONST:
18852           /* Note: It's currently impossible to recognize psyms as enum values
18853              short of reading the type info.  For now punt.  */
18854           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
18855         default:
18856           /* There are other LOC_FOO values that one might want to classify
18857              as variables, but dwarf2read.c doesn't currently use them.  */
18858           return GDB_INDEX_SYMBOL_KIND_OTHER;
18859         }
18860     case STRUCT_DOMAIN:
18861       return GDB_INDEX_SYMBOL_KIND_TYPE;
18862     default:
18863       return GDB_INDEX_SYMBOL_KIND_OTHER;
18864     }
18865 }
18866
18867 /* Add a list of partial symbols to SYMTAB.  */
18868
18869 static void
18870 write_psymbols (struct mapped_symtab *symtab,
18871                 htab_t psyms_seen,
18872                 struct partial_symbol **psymp,
18873                 int count,
18874                 offset_type cu_index,
18875                 int is_static)
18876 {
18877   for (; count-- > 0; ++psymp)
18878     {
18879       struct partial_symbol *psym = *psymp;
18880       void **slot;
18881
18882       if (SYMBOL_LANGUAGE (psym) == language_ada)
18883         error (_("Ada is not currently supported by the index"));
18884
18885       /* Only add a given psymbol once.  */
18886       slot = htab_find_slot (psyms_seen, psym, INSERT);
18887       if (!*slot)
18888         {
18889           gdb_index_symbol_kind kind = symbol_kind (psym);
18890
18891           *slot = psym;
18892           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
18893                            is_static, kind, cu_index);
18894         }
18895     }
18896 }
18897
18898 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
18899    exception if there is an error.  */
18900
18901 static void
18902 write_obstack (FILE *file, struct obstack *obstack)
18903 {
18904   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
18905               file)
18906       != obstack_object_size (obstack))
18907     error (_("couldn't data write to file"));
18908 }
18909
18910 /* Unlink a file if the argument is not NULL.  */
18911
18912 static void
18913 unlink_if_set (void *p)
18914 {
18915   char **filename = p;
18916   if (*filename)
18917     unlink (*filename);
18918 }
18919
18920 /* A helper struct used when iterating over debug_types.  */
18921 struct signatured_type_index_data
18922 {
18923   struct objfile *objfile;
18924   struct mapped_symtab *symtab;
18925   struct obstack *types_list;
18926   htab_t psyms_seen;
18927   int cu_index;
18928 };
18929
18930 /* A helper function that writes a single signatured_type to an
18931    obstack.  */
18932
18933 static int
18934 write_one_signatured_type (void **slot, void *d)
18935 {
18936   struct signatured_type_index_data *info = d;
18937   struct signatured_type *entry = (struct signatured_type *) *slot;
18938   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
18939   struct partial_symtab *psymtab = per_cu->v.psymtab;
18940   gdb_byte val[8];
18941
18942   write_psymbols (info->symtab,
18943                   info->psyms_seen,
18944                   info->objfile->global_psymbols.list
18945                   + psymtab->globals_offset,
18946                   psymtab->n_global_syms, info->cu_index,
18947                   0);
18948   write_psymbols (info->symtab,
18949                   info->psyms_seen,
18950                   info->objfile->static_psymbols.list
18951                   + psymtab->statics_offset,
18952                   psymtab->n_static_syms, info->cu_index,
18953                   1);
18954
18955   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
18956                           entry->per_cu.offset.sect_off);
18957   obstack_grow (info->types_list, val, 8);
18958   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
18959                           entry->type_offset_in_tu.cu_off);
18960   obstack_grow (info->types_list, val, 8);
18961   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
18962   obstack_grow (info->types_list, val, 8);
18963
18964   ++info->cu_index;
18965
18966   return 1;
18967 }
18968
18969 /* Recurse into all "included" dependencies and write their symbols as
18970    if they appeared in this psymtab.  */
18971
18972 static void
18973 recursively_write_psymbols (struct objfile *objfile,
18974                             struct partial_symtab *psymtab,
18975                             struct mapped_symtab *symtab,
18976                             htab_t psyms_seen,
18977                             offset_type cu_index)
18978 {
18979   int i;
18980
18981   for (i = 0; i < psymtab->number_of_dependencies; ++i)
18982     if (psymtab->dependencies[i]->user != NULL)
18983       recursively_write_psymbols (objfile, psymtab->dependencies[i],
18984                                   symtab, psyms_seen, cu_index);
18985
18986   write_psymbols (symtab,
18987                   psyms_seen,
18988                   objfile->global_psymbols.list + psymtab->globals_offset,
18989                   psymtab->n_global_syms, cu_index,
18990                   0);
18991   write_psymbols (symtab,
18992                   psyms_seen,
18993                   objfile->static_psymbols.list + psymtab->statics_offset,
18994                   psymtab->n_static_syms, cu_index,
18995                   1);
18996 }
18997
18998 /* Create an index file for OBJFILE in the directory DIR.  */
18999
19000 static void
19001 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
19002 {
19003   struct cleanup *cleanup;
19004   char *filename, *cleanup_filename;
19005   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
19006   struct obstack cu_list, types_cu_list;
19007   int i;
19008   FILE *out_file;
19009   struct mapped_symtab *symtab;
19010   offset_type val, size_of_contents, total_len;
19011   struct stat st;
19012   htab_t psyms_seen;
19013   htab_t cu_index_htab;
19014   struct psymtab_cu_index_map *psymtab_cu_index_map;
19015
19016   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
19017     return;
19018
19019   if (dwarf2_per_objfile->using_index)
19020     error (_("Cannot use an index to create the index"));
19021
19022   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
19023     error (_("Cannot make an index when the file has multiple .debug_types sections"));
19024
19025   if (stat (objfile->name, &st) < 0)
19026     perror_with_name (objfile->name);
19027
19028   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
19029                      INDEX_SUFFIX, (char *) NULL);
19030   cleanup = make_cleanup (xfree, filename);
19031
19032   out_file = fopen (filename, "wb");
19033   if (!out_file)
19034     error (_("Can't open `%s' for writing"), filename);
19035
19036   cleanup_filename = filename;
19037   make_cleanup (unlink_if_set, &cleanup_filename);
19038
19039   symtab = create_mapped_symtab ();
19040   make_cleanup (cleanup_mapped_symtab, symtab);
19041
19042   obstack_init (&addr_obstack);
19043   make_cleanup_obstack_free (&addr_obstack);
19044
19045   obstack_init (&cu_list);
19046   make_cleanup_obstack_free (&cu_list);
19047
19048   obstack_init (&types_cu_list);
19049   make_cleanup_obstack_free (&types_cu_list);
19050
19051   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
19052                                   NULL, xcalloc, xfree);
19053   make_cleanup_htab_delete (psyms_seen);
19054
19055   /* While we're scanning CU's create a table that maps a psymtab pointer
19056      (which is what addrmap records) to its index (which is what is recorded
19057      in the index file).  This will later be needed to write the address
19058      table.  */
19059   cu_index_htab = htab_create_alloc (100,
19060                                      hash_psymtab_cu_index,
19061                                      eq_psymtab_cu_index,
19062                                      NULL, xcalloc, xfree);
19063   make_cleanup_htab_delete (cu_index_htab);
19064   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
19065     xmalloc (sizeof (struct psymtab_cu_index_map)
19066              * dwarf2_per_objfile->n_comp_units);
19067   make_cleanup (xfree, psymtab_cu_index_map);
19068
19069   /* The CU list is already sorted, so we don't need to do additional
19070      work here.  Also, the debug_types entries do not appear in
19071      all_comp_units, but only in their own hash table.  */
19072   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
19073     {
19074       struct dwarf2_per_cu_data *per_cu
19075         = dwarf2_per_objfile->all_comp_units[i];
19076       struct partial_symtab *psymtab = per_cu->v.psymtab;
19077       gdb_byte val[8];
19078       struct psymtab_cu_index_map *map;
19079       void **slot;
19080
19081       if (psymtab->user == NULL)
19082         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
19083
19084       map = &psymtab_cu_index_map[i];
19085       map->psymtab = psymtab;
19086       map->cu_index = i;
19087       slot = htab_find_slot (cu_index_htab, map, INSERT);
19088       gdb_assert (slot != NULL);
19089       gdb_assert (*slot == NULL);
19090       *slot = map;
19091
19092       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
19093                               per_cu->offset.sect_off);
19094       obstack_grow (&cu_list, val, 8);
19095       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
19096       obstack_grow (&cu_list, val, 8);
19097     }
19098
19099   /* Dump the address map.  */
19100   write_address_map (objfile, &addr_obstack, cu_index_htab);
19101
19102   /* Write out the .debug_type entries, if any.  */
19103   if (dwarf2_per_objfile->signatured_types)
19104     {
19105       struct signatured_type_index_data sig_data;
19106
19107       sig_data.objfile = objfile;
19108       sig_data.symtab = symtab;
19109       sig_data.types_list = &types_cu_list;
19110       sig_data.psyms_seen = psyms_seen;
19111       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
19112       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
19113                               write_one_signatured_type, &sig_data);
19114     }
19115
19116   /* Now that we've processed all symbols we can shrink their cu_indices
19117      lists.  */
19118   uniquify_cu_indices (symtab);
19119
19120   obstack_init (&constant_pool);
19121   make_cleanup_obstack_free (&constant_pool);
19122   obstack_init (&symtab_obstack);
19123   make_cleanup_obstack_free (&symtab_obstack);
19124   write_hash_table (symtab, &symtab_obstack, &constant_pool);
19125
19126   obstack_init (&contents);
19127   make_cleanup_obstack_free (&contents);
19128   size_of_contents = 6 * sizeof (offset_type);
19129   total_len = size_of_contents;
19130
19131   /* The version number.  */
19132   val = MAYBE_SWAP (7);
19133   obstack_grow (&contents, &val, sizeof (val));
19134
19135   /* The offset of the CU list from the start of the file.  */
19136   val = MAYBE_SWAP (total_len);
19137   obstack_grow (&contents, &val, sizeof (val));
19138   total_len += obstack_object_size (&cu_list);
19139
19140   /* The offset of the types CU list from the start of the file.  */
19141   val = MAYBE_SWAP (total_len);
19142   obstack_grow (&contents, &val, sizeof (val));
19143   total_len += obstack_object_size (&types_cu_list);
19144
19145   /* The offset of the address table from the start of the file.  */
19146   val = MAYBE_SWAP (total_len);
19147   obstack_grow (&contents, &val, sizeof (val));
19148   total_len += obstack_object_size (&addr_obstack);
19149
19150   /* The offset of the symbol table from the start of the file.  */
19151   val = MAYBE_SWAP (total_len);
19152   obstack_grow (&contents, &val, sizeof (val));
19153   total_len += obstack_object_size (&symtab_obstack);
19154
19155   /* The offset of the constant pool from the start of the file.  */
19156   val = MAYBE_SWAP (total_len);
19157   obstack_grow (&contents, &val, sizeof (val));
19158   total_len += obstack_object_size (&constant_pool);
19159
19160   gdb_assert (obstack_object_size (&contents) == size_of_contents);
19161
19162   write_obstack (out_file, &contents);
19163   write_obstack (out_file, &cu_list);
19164   write_obstack (out_file, &types_cu_list);
19165   write_obstack (out_file, &addr_obstack);
19166   write_obstack (out_file, &symtab_obstack);
19167   write_obstack (out_file, &constant_pool);
19168
19169   fclose (out_file);
19170
19171   /* We want to keep the file, so we set cleanup_filename to NULL
19172      here.  See unlink_if_set.  */
19173   cleanup_filename = NULL;
19174
19175   do_cleanups (cleanup);
19176 }
19177
19178 /* Implementation of the `save gdb-index' command.
19179    
19180    Note that the file format used by this command is documented in the
19181    GDB manual.  Any changes here must be documented there.  */
19182
19183 static void
19184 save_gdb_index_command (char *arg, int from_tty)
19185 {
19186   struct objfile *objfile;
19187
19188   if (!arg || !*arg)
19189     error (_("usage: save gdb-index DIRECTORY"));
19190
19191   ALL_OBJFILES (objfile)
19192   {
19193     struct stat st;
19194
19195     /* If the objfile does not correspond to an actual file, skip it.  */
19196     if (stat (objfile->name, &st) < 0)
19197       continue;
19198
19199     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19200     if (dwarf2_per_objfile)
19201       {
19202         volatile struct gdb_exception except;
19203
19204         TRY_CATCH (except, RETURN_MASK_ERROR)
19205           {
19206             write_psymtabs_to_index (objfile, arg);
19207           }
19208         if (except.reason < 0)
19209           exception_fprintf (gdb_stderr, except,
19210                              _("Error while writing index for `%s': "),
19211                              objfile->name);
19212       }
19213   }
19214 }
19215
19216 \f
19217
19218 int dwarf2_always_disassemble;
19219
19220 static void
19221 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
19222                                 struct cmd_list_element *c, const char *value)
19223 {
19224   fprintf_filtered (file,
19225                     _("Whether to always disassemble "
19226                       "DWARF expressions is %s.\n"),
19227                     value);
19228 }
19229
19230 static void
19231 show_check_physname (struct ui_file *file, int from_tty,
19232                      struct cmd_list_element *c, const char *value)
19233 {
19234   fprintf_filtered (file,
19235                     _("Whether to check \"physname\" is %s.\n"),
19236                     value);
19237 }
19238
19239 void _initialize_dwarf2_read (void);
19240
19241 void
19242 _initialize_dwarf2_read (void)
19243 {
19244   struct cmd_list_element *c;
19245
19246   dwarf2_objfile_data_key
19247     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
19248
19249   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
19250 Set DWARF 2 specific variables.\n\
19251 Configure DWARF 2 variables such as the cache size"),
19252                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
19253                   0/*allow-unknown*/, &maintenance_set_cmdlist);
19254
19255   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
19256 Show DWARF 2 specific variables\n\
19257 Show DWARF 2 variables such as the cache size"),
19258                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
19259                   0/*allow-unknown*/, &maintenance_show_cmdlist);
19260
19261   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
19262                             &dwarf2_max_cache_age, _("\
19263 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
19264 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
19265 A higher limit means that cached compilation units will be stored\n\
19266 in memory longer, and more total memory will be used.  Zero disables\n\
19267 caching, which can slow down startup."),
19268                             NULL,
19269                             show_dwarf2_max_cache_age,
19270                             &set_dwarf2_cmdlist,
19271                             &show_dwarf2_cmdlist);
19272
19273   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
19274                            &dwarf2_always_disassemble, _("\
19275 Set whether `info address' always disassembles DWARF expressions."), _("\
19276 Show whether `info address' always disassembles DWARF expressions."), _("\
19277 When enabled, DWARF expressions are always printed in an assembly-like\n\
19278 syntax.  When disabled, expressions will be printed in a more\n\
19279 conversational style, when possible."),
19280                            NULL,
19281                            show_dwarf2_always_disassemble,
19282                            &set_dwarf2_cmdlist,
19283                            &show_dwarf2_cmdlist);
19284
19285   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
19286 Set debugging of the dwarf2 reader."), _("\
19287 Show debugging of the dwarf2 reader."), _("\
19288 When enabled, debugging messages are printed during dwarf2 reading\n\
19289 and symtab expansion."),
19290                             NULL,
19291                             NULL,
19292                             &setdebuglist, &showdebuglist);
19293
19294   add_setshow_zinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
19295 Set debugging of the dwarf2 DIE reader."), _("\
19296 Show debugging of the dwarf2 DIE reader."), _("\
19297 When enabled (non-zero), DIEs are dumped after they are read in.\n\
19298 The value is the maximum depth to print."),
19299                             NULL,
19300                             NULL,
19301                             &setdebuglist, &showdebuglist);
19302
19303   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
19304 Set cross-checking of \"physname\" code against demangler."), _("\
19305 Show cross-checking of \"physname\" code against demangler."), _("\
19306 When enabled, GDB's internal \"physname\" code is checked against\n\
19307 the demangler."),
19308                            NULL, show_check_physname,
19309                            &setdebuglist, &showdebuglist);
19310
19311   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
19312                _("\
19313 Save a gdb-index file.\n\
19314 Usage: save gdb-index DIRECTORY"),
19315                &save_cmdlist);
19316   set_cmd_completer (c, filename_completer);
19317 }