* dwarf2read.c (struct dwarf2_per_objfile): Clarify comment.
[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 "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70
71 #include <fcntl.h>
72 #include "gdb_string.h"
73 #include "gdb_assert.h"
74 #include <sys/types.h>
75
76 typedef struct symbol *symbolp;
77 DEF_VEC_P (symbolp);
78
79 /* When non-zero, print basic high level tracing messages.
80    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
81 static int dwarf2_read_debug = 0;
82
83 /* When non-zero, dump DIEs after they are read in.  */
84 static unsigned int dwarf2_die_debug = 0;
85
86 /* When non-zero, cross-check physname against demangler.  */
87 static int check_physname = 0;
88
89 /* When non-zero, do not reject deprecated .gdb_index sections.  */
90 static int use_deprecated_index_sections = 0;
91
92 /* When set, the file that we're processing is known to have debugging
93    info for C++ namespaces.  GCC 3.3.x did not produce this information,
94    but later versions do.  */
95
96 static int processing_has_namespace_info;
97
98 static const struct objfile_data *dwarf2_objfile_data_key;
99
100 struct dwarf2_section_info
101 {
102   asection *asection;
103   gdb_byte *buffer;
104   bfd_size_type size;
105   /* True if we have tried to read this section.  */
106   int readin;
107 };
108
109 typedef struct dwarf2_section_info dwarf2_section_info_def;
110 DEF_VEC_O (dwarf2_section_info_def);
111
112 /* All offsets in the index are of this type.  It must be
113    architecture-independent.  */
114 typedef uint32_t offset_type;
115
116 DEF_VEC_I (offset_type);
117
118 /* Ensure only legit values are used.  */
119 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
120   do { \
121     gdb_assert ((unsigned int) (value) <= 1); \
122     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
123   } while (0)
124
125 /* Ensure only legit values are used.  */
126 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
127   do { \
128     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
129                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
130     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
131   } while (0)
132
133 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
134 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
135   do { \
136     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
137     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
138   } while (0)
139
140 /* A description of the mapped index.  The file format is described in
141    a comment by the code that writes the index.  */
142 struct mapped_index
143 {
144   /* Index data format version.  */
145   int version;
146
147   /* The total length of the buffer.  */
148   off_t total_size;
149
150   /* A pointer to the address table data.  */
151   const gdb_byte *address_table;
152
153   /* Size of the address table data in bytes.  */
154   offset_type address_table_size;
155
156   /* The symbol table, implemented as a hash table.  */
157   const offset_type *symbol_table;
158
159   /* Size in slots, each slot is 2 offset_types.  */
160   offset_type symbol_table_slots;
161
162   /* A pointer to the constant pool.  */
163   const char *constant_pool;
164 };
165
166 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
167 DEF_VEC_P (dwarf2_per_cu_ptr);
168
169 /* Collection of data recorded per objfile.
170    This hangs off of dwarf2_objfile_data_key.  */
171
172 struct dwarf2_per_objfile
173 {
174   struct dwarf2_section_info info;
175   struct dwarf2_section_info abbrev;
176   struct dwarf2_section_info line;
177   struct dwarf2_section_info loc;
178   struct dwarf2_section_info macinfo;
179   struct dwarf2_section_info macro;
180   struct dwarf2_section_info str;
181   struct dwarf2_section_info ranges;
182   struct dwarf2_section_info addr;
183   struct dwarf2_section_info frame;
184   struct dwarf2_section_info eh_frame;
185   struct dwarf2_section_info gdb_index;
186
187   VEC (dwarf2_section_info_def) *types;
188
189   /* Back link.  */
190   struct objfile *objfile;
191
192   /* Table of all the compilation units.  This is used to locate
193      the target compilation unit of a particular reference.  */
194   struct dwarf2_per_cu_data **all_comp_units;
195
196   /* The number of compilation units in ALL_COMP_UNITS.  */
197   int n_comp_units;
198
199   /* The number of .debug_types-related CUs.  */
200   int n_type_units;
201
202   /* The .debug_types-related CUs (TUs).  */
203   struct signatured_type **all_type_units;
204
205   /* The number of entries in all_type_unit_groups.  */
206   int n_type_unit_groups;
207
208   /* Table of type unit groups.
209      This exists to make it easy to iterate over all CUs and TU groups.  */
210   struct type_unit_group **all_type_unit_groups;
211
212   /* Table of struct type_unit_group objects.
213      The hash key is the DW_AT_stmt_list value.  */
214   htab_t type_unit_groups;
215
216   /* A table mapping .debug_types signatures to its signatured_type entry.
217      This is NULL if the .debug_types section hasn't been read in yet.  */
218   htab_t signatured_types;
219
220   /* Type unit statistics, to see how well the scaling improvements
221      are doing.  */
222   struct tu_stats
223   {
224     int nr_uniq_abbrev_tables;
225     int nr_symtabs;
226     int nr_symtab_sharers;
227     int nr_stmt_less_type_units;
228   } tu_stats;
229
230   /* A chain of compilation units that are currently read in, so that
231      they can be freed later.  */
232   struct dwarf2_per_cu_data *read_in_chain;
233
234   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
235      This is NULL if the table hasn't been allocated yet.  */
236   htab_t dwo_files;
237
238   /* Non-zero if we've check for whether there is a DWP file.  */
239   int dwp_checked;
240
241   /* The DWP file if there is one, or NULL.  */
242   struct dwp_file *dwp_file;
243
244   /* The shared '.dwz' file, if one exists.  This is used when the
245      original data was compressed using 'dwz -m'.  */
246   struct dwz_file *dwz_file;
247
248   /* A flag indicating wether this objfile has a section loaded at a
249      VMA of 0.  */
250   int has_section_at_zero;
251
252   /* True if we are using the mapped index,
253      or we are faking it for OBJF_READNOW's sake.  */
254   unsigned char using_index;
255
256   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
257   struct mapped_index *index_table;
258
259   /* When using index_table, this keeps track of all quick_file_names entries.
260      TUs typically share line table entries with a CU, so we maintain a
261      separate table of all line table entries to support the sharing.
262      Note that while there can be way more TUs than CUs, we've already
263      sorted all the TUs into "type unit groups", grouped by their
264      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
265      CU and its associated TU group if there is one.  */
266   htab_t quick_file_names_table;
267
268   /* Set during partial symbol reading, to prevent queueing of full
269      symbols.  */
270   int reading_partial_symbols;
271
272   /* Table mapping type DIEs to their struct type *.
273      This is NULL if not allocated yet.
274      The mapping is done via (CU/TU signature + DIE offset) -> type.  */
275   htab_t die_type_hash;
276
277   /* The CUs we recently read.  */
278   VEC (dwarf2_per_cu_ptr) *just_read_cus;
279 };
280
281 static struct dwarf2_per_objfile *dwarf2_per_objfile;
282
283 /* Default names of the debugging sections.  */
284
285 /* Note that if the debugging section has been compressed, it might
286    have a name like .zdebug_info.  */
287
288 static const struct dwarf2_debug_sections dwarf2_elf_names =
289 {
290   { ".debug_info", ".zdebug_info" },
291   { ".debug_abbrev", ".zdebug_abbrev" },
292   { ".debug_line", ".zdebug_line" },
293   { ".debug_loc", ".zdebug_loc" },
294   { ".debug_macinfo", ".zdebug_macinfo" },
295   { ".debug_macro", ".zdebug_macro" },
296   { ".debug_str", ".zdebug_str" },
297   { ".debug_ranges", ".zdebug_ranges" },
298   { ".debug_types", ".zdebug_types" },
299   { ".debug_addr", ".zdebug_addr" },
300   { ".debug_frame", ".zdebug_frame" },
301   { ".eh_frame", NULL },
302   { ".gdb_index", ".zgdb_index" },
303   23
304 };
305
306 /* List of DWO/DWP sections.  */
307
308 static const struct dwop_section_names
309 {
310   struct dwarf2_section_names abbrev_dwo;
311   struct dwarf2_section_names info_dwo;
312   struct dwarf2_section_names line_dwo;
313   struct dwarf2_section_names loc_dwo;
314   struct dwarf2_section_names macinfo_dwo;
315   struct dwarf2_section_names macro_dwo;
316   struct dwarf2_section_names str_dwo;
317   struct dwarf2_section_names str_offsets_dwo;
318   struct dwarf2_section_names types_dwo;
319   struct dwarf2_section_names cu_index;
320   struct dwarf2_section_names tu_index;
321 }
322 dwop_section_names =
323 {
324   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
325   { ".debug_info.dwo", ".zdebug_info.dwo" },
326   { ".debug_line.dwo", ".zdebug_line.dwo" },
327   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
328   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
329   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
330   { ".debug_str.dwo", ".zdebug_str.dwo" },
331   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
332   { ".debug_types.dwo", ".zdebug_types.dwo" },
333   { ".debug_cu_index", ".zdebug_cu_index" },
334   { ".debug_tu_index", ".zdebug_tu_index" },
335 };
336
337 /* local data types */
338
339 /* The data in a compilation unit header, after target2host
340    translation, looks like this.  */
341 struct comp_unit_head
342 {
343   unsigned int length;
344   short version;
345   unsigned char addr_size;
346   unsigned char signed_addr_p;
347   sect_offset abbrev_offset;
348
349   /* Size of file offsets; either 4 or 8.  */
350   unsigned int offset_size;
351
352   /* Size of the length field; either 4 or 12.  */
353   unsigned int initial_length_size;
354
355   /* Offset to the first byte of this compilation unit header in the
356      .debug_info section, for resolving relative reference dies.  */
357   sect_offset offset;
358
359   /* Offset to first die in this cu from the start of the cu.
360      This will be the first byte following the compilation unit header.  */
361   cu_offset first_die_offset;
362 };
363
364 /* Type used for delaying computation of method physnames.
365    See comments for compute_delayed_physnames.  */
366 struct delayed_method_info
367 {
368   /* The type to which the method is attached, i.e., its parent class.  */
369   struct type *type;
370
371   /* The index of the method in the type's function fieldlists.  */
372   int fnfield_index;
373
374   /* The index of the method in the fieldlist.  */
375   int index;
376
377   /* The name of the DIE.  */
378   const char *name;
379
380   /*  The DIE associated with this method.  */
381   struct die_info *die;
382 };
383
384 typedef struct delayed_method_info delayed_method_info;
385 DEF_VEC_O (delayed_method_info);
386
387 /* Internal state when decoding a particular compilation unit.  */
388 struct dwarf2_cu
389 {
390   /* The objfile containing this compilation unit.  */
391   struct objfile *objfile;
392
393   /* The header of the compilation unit.  */
394   struct comp_unit_head header;
395
396   /* Base address of this compilation unit.  */
397   CORE_ADDR base_address;
398
399   /* Non-zero if base_address has been set.  */
400   int base_known;
401
402   /* The language we are debugging.  */
403   enum language language;
404   const struct language_defn *language_defn;
405
406   const char *producer;
407
408   /* The generic symbol table building routines have separate lists for
409      file scope symbols and all all other scopes (local scopes).  So
410      we need to select the right one to pass to add_symbol_to_list().
411      We do it by keeping a pointer to the correct list in list_in_scope.
412
413      FIXME: The original dwarf code just treated the file scope as the
414      first local scope, and all other local scopes as nested local
415      scopes, and worked fine.  Check to see if we really need to
416      distinguish these in buildsym.c.  */
417   struct pending **list_in_scope;
418
419   /* The abbrev table for this CU.
420      Normally this points to the abbrev table in the objfile.
421      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
422   struct abbrev_table *abbrev_table;
423
424   /* Hash table holding all the loaded partial DIEs
425      with partial_die->offset.SECT_OFF as hash.  */
426   htab_t partial_dies;
427
428   /* Storage for things with the same lifetime as this read-in compilation
429      unit, including partial DIEs.  */
430   struct obstack comp_unit_obstack;
431
432   /* When multiple dwarf2_cu structures are living in memory, this field
433      chains them all together, so that they can be released efficiently.
434      We will probably also want a generation counter so that most-recently-used
435      compilation units are cached...  */
436   struct dwarf2_per_cu_data *read_in_chain;
437
438   /* Backchain to our per_cu entry if the tree has been built.  */
439   struct dwarf2_per_cu_data *per_cu;
440
441   /* How many compilation units ago was this CU last referenced?  */
442   int last_used;
443
444   /* A hash table of DIE cu_offset for following references with
445      die_info->offset.sect_off as hash.  */
446   htab_t die_hash;
447
448   /* Full DIEs if read in.  */
449   struct die_info *dies;
450
451   /* A set of pointers to dwarf2_per_cu_data objects for compilation
452      units referenced by this one.  Only set during full symbol processing;
453      partial symbol tables do not have dependencies.  */
454   htab_t dependencies;
455
456   /* Header data from the line table, during full symbol processing.  */
457   struct line_header *line_header;
458
459   /* A list of methods which need to have physnames computed
460      after all type information has been read.  */
461   VEC (delayed_method_info) *method_list;
462
463   /* To be copied to symtab->call_site_htab.  */
464   htab_t call_site_htab;
465
466   /* Non-NULL if this CU came from a DWO file.
467      There is an invariant here that is important to remember:
468      Except for attributes copied from the top level DIE in the "main"
469      (or "stub") file in preparation for reading the DWO file
470      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
471      Either there isn't a DWO file (in which case this is NULL and the point
472      is moot), or there is and either we're not going to read it (in which
473      case this is NULL) or there is and we are reading it (in which case this
474      is non-NULL).  */
475   struct dwo_unit *dwo_unit;
476
477   /* The DW_AT_addr_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   ULONGEST addr_base;
481
482   /* The DW_AT_ranges_base attribute if present, zero otherwise
483      (zero is a valid value though).
484      Note this value comes from the stub CU/TU's DIE.
485      Also note that the value is zero in the non-DWO case so this value can
486      be used without needing to know whether DWO files are in use or not.  */
487   ULONGEST ranges_base;
488
489   /* Mark used when releasing cached dies.  */
490   unsigned int mark : 1;
491
492   /* This CU references .debug_loc.  See the symtab->locations_valid field.
493      This test is imperfect as there may exist optimized debug code not using
494      any location list and still facing inlining issues if handled as
495      unoptimized code.  For a future better test see GCC PR other/32998.  */
496   unsigned int has_loclist : 1;
497
498   /* These cache the results for producer_is_gxx_lt_4_6 and producer_is_icc.
499      CHECKED_PRODUCER is set if both PRODUCER_IS_GXX_LT_4_6 and PRODUCER_IS_ICC
500      are valid.  This information is cached because profiling CU expansion
501      showed excessive time spent in producer_is_gxx_lt_4_6.  */
502   unsigned int checked_producer : 1;
503   unsigned int producer_is_gxx_lt_4_6 : 1;
504   unsigned int producer_is_icc : 1;
505 };
506
507 /* Persistent data held for a compilation unit, even when not
508    processing it.  We put a pointer to this structure in the
509    read_symtab_private field of the psymtab.  */
510
511 struct dwarf2_per_cu_data
512 {
513   /* The start offset and length of this compilation unit.
514      NOTE: Unlike comp_unit_head.length, this length includes
515      initial_length_size.
516      If the DIE refers to a DWO file, this is always of the original die,
517      not the DWO file.  */
518   sect_offset offset;
519   unsigned int length;
520
521   /* Flag indicating this compilation unit will be read in before
522      any of the current compilation units are processed.  */
523   unsigned int queued : 1;
524
525   /* This flag will be set when reading partial DIEs if we need to load
526      absolutely all DIEs for this compilation unit, instead of just the ones
527      we think are interesting.  It gets set if we look for a DIE in the
528      hash table and don't find it.  */
529   unsigned int load_all_dies : 1;
530
531   /* Non-zero if this CU is from .debug_types.  */
532   unsigned int is_debug_types : 1;
533
534   /* Non-zero if this CU is from the .dwz file.  */
535   unsigned int is_dwz : 1;
536
537   /* The section this CU/TU lives in.
538      If the DIE refers to a DWO file, this is always the original die,
539      not the DWO file.  */
540   struct dwarf2_section_info *info_or_types_section;
541
542   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
543      of the CU cache it gets reset to NULL again.  */
544   struct dwarf2_cu *cu;
545
546   /* The corresponding objfile.
547      Normally we can get the objfile from dwarf2_per_objfile.
548      However we can enter this file with just a "per_cu" handle.  */
549   struct objfile *objfile;
550
551   /* When using partial symbol tables, the 'psymtab' field is active.
552      Otherwise the 'quick' field is active.  */
553   union
554   {
555     /* The partial symbol table associated with this compilation unit,
556        or NULL for unread partial units.  */
557     struct partial_symtab *psymtab;
558
559     /* Data needed by the "quick" functions.  */
560     struct dwarf2_per_cu_quick_data *quick;
561   } v;
562
563   union
564   {
565     /* The CUs we import using DW_TAG_imported_unit.  This is filled in
566        while reading psymtabs, used to compute the psymtab dependencies,
567        and then cleared.  Then it is filled in again while reading full
568        symbols, and only deleted when the objfile is destroyed.  */
569     VEC (dwarf2_per_cu_ptr) *imported_symtabs;
570
571     /* Type units are grouped by their DW_AT_stmt_list entry so that they
572        can share them.  If this is a TU, this points to the containing
573        symtab.  */
574     struct type_unit_group *type_unit_group;
575   } s;
576 };
577
578 /* Entry in the signatured_types hash table.  */
579
580 struct signatured_type
581 {
582   /* The "per_cu" object of this type.
583      N.B.: This is the first member so that it's easy to convert pointers
584      between them.  */
585   struct dwarf2_per_cu_data per_cu;
586
587   /* The type's signature.  */
588   ULONGEST signature;
589
590   /* Offset in the TU of the type's DIE, as read from the TU header.
591      If the definition lives in a DWO file, this value is unusable.  */
592   cu_offset type_offset_in_tu;
593
594   /* Offset in the section of the type's DIE.
595      If the definition lives in a DWO file, this is the offset in the
596      .debug_types.dwo section.
597      The value is zero until the actual value is known.
598      Zero is otherwise not a valid section offset.  */
599   sect_offset type_offset_in_section;
600 };
601
602 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
603    This includes type_unit_group and quick_file_names.  */
604
605 struct stmt_list_hash
606 {
607   /* The DWO unit this table is from or NULL if there is none.  */
608   struct dwo_unit *dwo_unit;
609
610   /* Offset in .debug_line or .debug_line.dwo.  */
611   sect_offset line_offset;
612 };
613
614 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
615    an object of this type.  */
616
617 struct type_unit_group
618 {
619   /* dwarf2read.c's main "handle" on the symtab.
620      To simplify things we create an artificial CU that "includes" all the
621      type units using this stmt_list so that the rest of the code still has
622      a "per_cu" handle on the symtab.
623      This PER_CU is recognized by having no section.  */
624 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->info_or_types_section == NULL)
625   struct dwarf2_per_cu_data per_cu;
626
627   union
628   {
629     /* The TUs that share this DW_AT_stmt_list entry.
630        This is added to while parsing type units to build partial symtabs,
631        and is deleted afterwards and not used again.  */
632     VEC (dwarf2_per_cu_ptr) *tus;
633
634     /* When reading the line table in "quick" functions, we need a real TU.
635        Any will do, we know they all share the same DW_AT_stmt_list entry.
636        For simplicity's sake, we pick the first one.  */
637     struct dwarf2_per_cu_data *first_tu;
638   } t;
639
640   /* The primary symtab.
641      Type units in a group needn't all be defined in the same source file,
642      so we create an essentially anonymous symtab as the primary symtab.  */
643   struct symtab *primary_symtab;
644
645   /* The data used to construct the hash key.  */
646   struct stmt_list_hash hash;
647
648   /* The number of symtabs from the line header.
649      The value here must match line_header.num_file_names.  */
650   unsigned int num_symtabs;
651
652   /* The symbol tables for this TU (obtained from the files listed in
653      DW_AT_stmt_list).
654      WARNING: The order of entries here must match the order of entries
655      in the line header.  After the first TU using this type_unit_group, the
656      line header for the subsequent TUs is recreated from this.  This is done
657      because we need to use the same symtabs for each TU using the same
658      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
659      there's no guarantee the line header doesn't have duplicate entries.  */
660   struct symtab **symtabs;
661 };
662
663 /* These sections are what may appear in a DWO file.  */
664
665 struct dwo_sections
666 {
667   struct dwarf2_section_info abbrev;
668   struct dwarf2_section_info line;
669   struct dwarf2_section_info loc;
670   struct dwarf2_section_info macinfo;
671   struct dwarf2_section_info macro;
672   struct dwarf2_section_info str;
673   struct dwarf2_section_info str_offsets;
674   /* In the case of a virtual DWO file, these two are unused.  */
675   struct dwarf2_section_info info;
676   VEC (dwarf2_section_info_def) *types;
677 };
678
679 /* Common bits of DWO CUs/TUs.  */
680
681 struct dwo_unit
682 {
683   /* Backlink to the containing struct dwo_file.  */
684   struct dwo_file *dwo_file;
685
686   /* The "id" that distinguishes this CU/TU.
687      .debug_info calls this "dwo_id", .debug_types calls this "signature".
688      Since signatures came first, we stick with it for consistency.  */
689   ULONGEST signature;
690
691   /* The section this CU/TU lives in, in the DWO file.  */
692   struct dwarf2_section_info *info_or_types_section;
693
694   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
695   sect_offset offset;
696   unsigned int length;
697
698   /* For types, offset in the type's DIE of the type defined by this TU.  */
699   cu_offset type_offset_in_tu;
700 };
701
702 /* Data for one DWO file.
703    This includes virtual DWO files that have been packaged into a
704    DWP file.  */
705
706 struct dwo_file
707 {
708   /* The DW_AT_GNU_dwo_name attribute.  This is the hash key.
709      For virtual DWO files the name is constructed from the section offsets
710      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
711      from related CU+TUs.  */
712   const char *name;
713
714   /* The bfd, when the file is open.  Otherwise this is NULL.
715      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
716   bfd *dbfd;
717
718   /* Section info for this file.  */
719   struct dwo_sections sections;
720
721   /* Table of CUs in the file.
722      Each element is a struct dwo_unit.  */
723   htab_t cus;
724
725   /* Table of TUs in the file.
726      Each element is a struct dwo_unit.  */
727   htab_t tus;
728 };
729
730 /* These sections are what may appear in a DWP file.  */
731
732 struct dwp_sections
733 {
734   struct dwarf2_section_info str;
735   struct dwarf2_section_info cu_index;
736   struct dwarf2_section_info tu_index;
737   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
738      by section number.  We don't need to record them here.  */
739 };
740
741 /* These sections are what may appear in a virtual DWO file.  */
742
743 struct virtual_dwo_sections
744 {
745   struct dwarf2_section_info abbrev;
746   struct dwarf2_section_info line;
747   struct dwarf2_section_info loc;
748   struct dwarf2_section_info macinfo;
749   struct dwarf2_section_info macro;
750   struct dwarf2_section_info str_offsets;
751   /* Each DWP hash table entry records one CU or one TU.
752      That is recorded here, and copied to dwo_unit.info_or_types_section.  */
753   struct dwarf2_section_info info_or_types;
754 };
755
756 /* Contents of DWP hash tables.  */
757
758 struct dwp_hash_table
759 {
760   uint32_t nr_units, nr_slots;
761   const gdb_byte *hash_table, *unit_table, *section_pool;
762 };
763
764 /* Data for one DWP file.  */
765
766 struct dwp_file
767 {
768   /* Name of the file.  */
769   const char *name;
770
771   /* The bfd, when the file is open.  Otherwise this is NULL.  */
772   bfd *dbfd;
773
774   /* Section info for this file.  */
775   struct dwp_sections sections;
776
777   /* Table of CUs in the file. */
778   const struct dwp_hash_table *cus;
779
780   /* Table of TUs in the file.  */
781   const struct dwp_hash_table *tus;
782
783   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
784   htab_t loaded_cutus;
785
786   /* Table to map ELF section numbers to their sections.  */
787   unsigned int num_sections;
788   asection **elf_sections;
789 };
790
791 /* This represents a '.dwz' file.  */
792
793 struct dwz_file
794 {
795   /* A dwz file can only contain a few sections.  */
796   struct dwarf2_section_info abbrev;
797   struct dwarf2_section_info info;
798   struct dwarf2_section_info str;
799   struct dwarf2_section_info line;
800   struct dwarf2_section_info macro;
801   struct dwarf2_section_info gdb_index;
802
803   /* The dwz's BFD.  */
804   bfd *dwz_bfd;
805 };
806
807 /* Struct used to pass misc. parameters to read_die_and_children, et
808    al.  which are used for both .debug_info and .debug_types dies.
809    All parameters here are unchanging for the life of the call.  This
810    struct exists to abstract away the constant parameters of die reading.  */
811
812 struct die_reader_specs
813 {
814   /* die_section->asection->owner.  */
815   bfd* abfd;
816
817   /* The CU of the DIE we are parsing.  */
818   struct dwarf2_cu *cu;
819
820   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
821   struct dwo_file *dwo_file;
822
823   /* The section the die comes from.
824      This is either .debug_info or .debug_types, or the .dwo variants.  */
825   struct dwarf2_section_info *die_section;
826
827   /* die_section->buffer.  */
828   gdb_byte *buffer;
829
830   /* The end of the buffer.  */
831   const gdb_byte *buffer_end;
832 };
833
834 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
835 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
836                                       gdb_byte *info_ptr,
837                                       struct die_info *comp_unit_die,
838                                       int has_children,
839                                       void *data);
840
841 /* The line number information for a compilation unit (found in the
842    .debug_line section) begins with a "statement program header",
843    which contains the following information.  */
844 struct line_header
845 {
846   unsigned int total_length;
847   unsigned short version;
848   unsigned int header_length;
849   unsigned char minimum_instruction_length;
850   unsigned char maximum_ops_per_instruction;
851   unsigned char default_is_stmt;
852   int line_base;
853   unsigned char line_range;
854   unsigned char opcode_base;
855
856   /* standard_opcode_lengths[i] is the number of operands for the
857      standard opcode whose value is i.  This means that
858      standard_opcode_lengths[0] is unused, and the last meaningful
859      element is standard_opcode_lengths[opcode_base - 1].  */
860   unsigned char *standard_opcode_lengths;
861
862   /* The include_directories table.  NOTE!  These strings are not
863      allocated with xmalloc; instead, they are pointers into
864      debug_line_buffer.  If you try to free them, `free' will get
865      indigestion.  */
866   unsigned int num_include_dirs, include_dirs_size;
867   char **include_dirs;
868
869   /* The file_names table.  NOTE!  These strings are not allocated
870      with xmalloc; instead, they are pointers into debug_line_buffer.
871      Don't try to free them directly.  */
872   unsigned int num_file_names, file_names_size;
873   struct file_entry
874   {
875     char *name;
876     unsigned int dir_index;
877     unsigned int mod_time;
878     unsigned int length;
879     int included_p; /* Non-zero if referenced by the Line Number Program.  */
880     struct symtab *symtab; /* The associated symbol table, if any.  */
881   } *file_names;
882
883   /* The start and end of the statement program following this
884      header.  These point into dwarf2_per_objfile->line_buffer.  */
885   gdb_byte *statement_program_start, *statement_program_end;
886 };
887
888 /* When we construct a partial symbol table entry we only
889    need this much information.  */
890 struct partial_die_info
891   {
892     /* Offset of this DIE.  */
893     sect_offset offset;
894
895     /* DWARF-2 tag for this DIE.  */
896     ENUM_BITFIELD(dwarf_tag) tag : 16;
897
898     /* Assorted flags describing the data found in this DIE.  */
899     unsigned int has_children : 1;
900     unsigned int is_external : 1;
901     unsigned int is_declaration : 1;
902     unsigned int has_type : 1;
903     unsigned int has_specification : 1;
904     unsigned int has_pc_info : 1;
905     unsigned int may_be_inlined : 1;
906
907     /* Flag set if the SCOPE field of this structure has been
908        computed.  */
909     unsigned int scope_set : 1;
910
911     /* Flag set if the DIE has a byte_size attribute.  */
912     unsigned int has_byte_size : 1;
913
914     /* Flag set if any of the DIE's children are template arguments.  */
915     unsigned int has_template_arguments : 1;
916
917     /* Flag set if fixup_partial_die has been called on this die.  */
918     unsigned int fixup_called : 1;
919
920     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
921     unsigned int is_dwz : 1;
922
923     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
924     unsigned int spec_is_dwz : 1;
925
926     /* The name of this DIE.  Normally the value of DW_AT_name, but
927        sometimes a default name for unnamed DIEs.  */
928     char *name;
929
930     /* The linkage name, if present.  */
931     const char *linkage_name;
932
933     /* The scope to prepend to our children.  This is generally
934        allocated on the comp_unit_obstack, so will disappear
935        when this compilation unit leaves the cache.  */
936     char *scope;
937
938     /* Some data associated with the partial DIE.  The tag determines
939        which field is live.  */
940     union
941     {
942       /* The location description associated with this DIE, if any.  */
943       struct dwarf_block *locdesc;
944       /* The offset of an import, for DW_TAG_imported_unit.  */
945       sect_offset offset;
946     } d;
947
948     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
949     CORE_ADDR lowpc;
950     CORE_ADDR highpc;
951
952     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
953        DW_AT_sibling, if any.  */
954     /* NOTE: This member isn't strictly necessary, read_partial_die could
955        return DW_AT_sibling values to its caller load_partial_dies.  */
956     gdb_byte *sibling;
957
958     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
959        DW_AT_specification (or DW_AT_abstract_origin or
960        DW_AT_extension).  */
961     sect_offset spec_offset;
962
963     /* Pointers to this DIE's parent, first child, and next sibling,
964        if any.  */
965     struct partial_die_info *die_parent, *die_child, *die_sibling;
966   };
967
968 /* This data structure holds the information of an abbrev.  */
969 struct abbrev_info
970   {
971     unsigned int number;        /* number identifying abbrev */
972     enum dwarf_tag tag;         /* dwarf tag */
973     unsigned short has_children;                /* boolean */
974     unsigned short num_attrs;   /* number of attributes */
975     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
976     struct abbrev_info *next;   /* next in chain */
977   };
978
979 struct attr_abbrev
980   {
981     ENUM_BITFIELD(dwarf_attribute) name : 16;
982     ENUM_BITFIELD(dwarf_form) form : 16;
983   };
984
985 /* Size of abbrev_table.abbrev_hash_table.  */
986 #define ABBREV_HASH_SIZE 121
987
988 /* Top level data structure to contain an abbreviation table.  */
989
990 struct abbrev_table
991 {
992   /* Where the abbrev table came from.
993      This is used as a sanity check when the table is used.  */
994   sect_offset offset;
995
996   /* Storage for the abbrev table.  */
997   struct obstack abbrev_obstack;
998
999   /* Hash table of abbrevs.
1000      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1001      It could be statically allocated, but the previous code didn't so we
1002      don't either.  */
1003   struct abbrev_info **abbrevs;
1004 };
1005
1006 /* Attributes have a name and a value.  */
1007 struct attribute
1008   {
1009     ENUM_BITFIELD(dwarf_attribute) name : 16;
1010     ENUM_BITFIELD(dwarf_form) form : 15;
1011
1012     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1013        field should be in u.str (existing only for DW_STRING) but it is kept
1014        here for better struct attribute alignment.  */
1015     unsigned int string_is_canonical : 1;
1016
1017     union
1018       {
1019         char *str;
1020         struct dwarf_block *blk;
1021         ULONGEST unsnd;
1022         LONGEST snd;
1023         CORE_ADDR addr;
1024         struct signatured_type *signatured_type;
1025       }
1026     u;
1027   };
1028
1029 /* This data structure holds a complete die structure.  */
1030 struct die_info
1031   {
1032     /* DWARF-2 tag for this DIE.  */
1033     ENUM_BITFIELD(dwarf_tag) tag : 16;
1034
1035     /* Number of attributes */
1036     unsigned char num_attrs;
1037
1038     /* True if we're presently building the full type name for the
1039        type derived from this DIE.  */
1040     unsigned char building_fullname : 1;
1041
1042     /* Abbrev number */
1043     unsigned int abbrev;
1044
1045     /* Offset in .debug_info or .debug_types section.  */
1046     sect_offset offset;
1047
1048     /* The dies in a compilation unit form an n-ary tree.  PARENT
1049        points to this die's parent; CHILD points to the first child of
1050        this node; and all the children of a given node are chained
1051        together via their SIBLING fields.  */
1052     struct die_info *child;     /* Its first child, if any.  */
1053     struct die_info *sibling;   /* Its next sibling, if any.  */
1054     struct die_info *parent;    /* Its parent, if any.  */
1055
1056     /* An array of attributes, with NUM_ATTRS elements.  There may be
1057        zero, but it's not common and zero-sized arrays are not
1058        sufficiently portable C.  */
1059     struct attribute attrs[1];
1060   };
1061
1062 /* Get at parts of an attribute structure.  */
1063
1064 #define DW_STRING(attr)    ((attr)->u.str)
1065 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1066 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1067 #define DW_BLOCK(attr)     ((attr)->u.blk)
1068 #define DW_SND(attr)       ((attr)->u.snd)
1069 #define DW_ADDR(attr)      ((attr)->u.addr)
1070 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
1071
1072 /* Blocks are a bunch of untyped bytes.  */
1073 struct dwarf_block
1074   {
1075     size_t size;
1076
1077     /* Valid only if SIZE is not zero.  */
1078     gdb_byte *data;
1079   };
1080
1081 #ifndef ATTR_ALLOC_CHUNK
1082 #define ATTR_ALLOC_CHUNK 4
1083 #endif
1084
1085 /* Allocate fields for structs, unions and enums in this size.  */
1086 #ifndef DW_FIELD_ALLOC_CHUNK
1087 #define DW_FIELD_ALLOC_CHUNK 4
1088 #endif
1089
1090 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1091    but this would require a corresponding change in unpack_field_as_long
1092    and friends.  */
1093 static int bits_per_byte = 8;
1094
1095 /* The routines that read and process dies for a C struct or C++ class
1096    pass lists of data member fields and lists of member function fields
1097    in an instance of a field_info structure, as defined below.  */
1098 struct field_info
1099   {
1100     /* List of data member and baseclasses fields.  */
1101     struct nextfield
1102       {
1103         struct nextfield *next;
1104         int accessibility;
1105         int virtuality;
1106         struct field field;
1107       }
1108      *fields, *baseclasses;
1109
1110     /* Number of fields (including baseclasses).  */
1111     int nfields;
1112
1113     /* Number of baseclasses.  */
1114     int nbaseclasses;
1115
1116     /* Set if the accesibility of one of the fields is not public.  */
1117     int non_public_fields;
1118
1119     /* Member function fields array, entries are allocated in the order they
1120        are encountered in the object file.  */
1121     struct nextfnfield
1122       {
1123         struct nextfnfield *next;
1124         struct fn_field fnfield;
1125       }
1126      *fnfields;
1127
1128     /* Member function fieldlist array, contains name of possibly overloaded
1129        member function, number of overloaded member functions and a pointer
1130        to the head of the member function field chain.  */
1131     struct fnfieldlist
1132       {
1133         char *name;
1134         int length;
1135         struct nextfnfield *head;
1136       }
1137      *fnfieldlists;
1138
1139     /* Number of entries in the fnfieldlists array.  */
1140     int nfnfields;
1141
1142     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1143        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1144     struct typedef_field_list
1145       {
1146         struct typedef_field field;
1147         struct typedef_field_list *next;
1148       }
1149     *typedef_field_list;
1150     unsigned typedef_field_list_count;
1151   };
1152
1153 /* One item on the queue of compilation units to read in full symbols
1154    for.  */
1155 struct dwarf2_queue_item
1156 {
1157   struct dwarf2_per_cu_data *per_cu;
1158   enum language pretend_language;
1159   struct dwarf2_queue_item *next;
1160 };
1161
1162 /* The current queue.  */
1163 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1164
1165 /* Loaded secondary compilation units are kept in memory until they
1166    have not been referenced for the processing of this many
1167    compilation units.  Set this to zero to disable caching.  Cache
1168    sizes of up to at least twenty will improve startup time for
1169    typical inter-CU-reference binaries, at an obvious memory cost.  */
1170 static int dwarf2_max_cache_age = 5;
1171 static void
1172 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1173                            struct cmd_list_element *c, const char *value)
1174 {
1175   fprintf_filtered (file, _("The upper bound on the age of cached "
1176                             "dwarf2 compilation units is %s.\n"),
1177                     value);
1178 }
1179
1180
1181 /* Various complaints about symbol reading that don't abort the process.  */
1182
1183 static void
1184 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1185 {
1186   complaint (&symfile_complaints,
1187              _("statement list doesn't fit in .debug_line section"));
1188 }
1189
1190 static void
1191 dwarf2_debug_line_missing_file_complaint (void)
1192 {
1193   complaint (&symfile_complaints,
1194              _(".debug_line section has line data without a file"));
1195 }
1196
1197 static void
1198 dwarf2_debug_line_missing_end_sequence_complaint (void)
1199 {
1200   complaint (&symfile_complaints,
1201              _(".debug_line section has line "
1202                "program sequence without an end"));
1203 }
1204
1205 static void
1206 dwarf2_complex_location_expr_complaint (void)
1207 {
1208   complaint (&symfile_complaints, _("location expression too complex"));
1209 }
1210
1211 static void
1212 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1213                                               int arg3)
1214 {
1215   complaint (&symfile_complaints,
1216              _("const value length mismatch for '%s', got %d, expected %d"),
1217              arg1, arg2, arg3);
1218 }
1219
1220 static void
1221 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1222 {
1223   complaint (&symfile_complaints,
1224              _("debug info runs off end of %s section"
1225                " [in module %s]"),
1226              section->asection->name,
1227              bfd_get_filename (section->asection->owner));
1228 }
1229
1230 static void
1231 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1232 {
1233   complaint (&symfile_complaints,
1234              _("macro debug info contains a "
1235                "malformed macro definition:\n`%s'"),
1236              arg1);
1237 }
1238
1239 static void
1240 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1241 {
1242   complaint (&symfile_complaints,
1243              _("invalid attribute class or form for '%s' in '%s'"),
1244              arg1, arg2);
1245 }
1246
1247 /* local function prototypes */
1248
1249 static void dwarf2_locate_sections (bfd *, asection *, void *);
1250
1251 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1252                                            struct objfile *);
1253
1254 static void dwarf2_find_base_address (struct die_info *die,
1255                                       struct dwarf2_cu *cu);
1256
1257 static void dwarf2_build_psymtabs_hard (struct objfile *);
1258
1259 static void scan_partial_symbols (struct partial_die_info *,
1260                                   CORE_ADDR *, CORE_ADDR *,
1261                                   int, struct dwarf2_cu *);
1262
1263 static void add_partial_symbol (struct partial_die_info *,
1264                                 struct dwarf2_cu *);
1265
1266 static void add_partial_namespace (struct partial_die_info *pdi,
1267                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1268                                    int need_pc, struct dwarf2_cu *cu);
1269
1270 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1271                                 CORE_ADDR *highpc, int need_pc,
1272                                 struct dwarf2_cu *cu);
1273
1274 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1275                                      struct dwarf2_cu *cu);
1276
1277 static void add_partial_subprogram (struct partial_die_info *pdi,
1278                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1279                                     int need_pc, struct dwarf2_cu *cu);
1280
1281 static void dwarf2_psymtab_to_symtab (struct partial_symtab *);
1282
1283 static void psymtab_to_symtab_1 (struct partial_symtab *);
1284
1285 static struct abbrev_info *abbrev_table_lookup_abbrev
1286   (const struct abbrev_table *, unsigned int);
1287
1288 static struct abbrev_table *abbrev_table_read_table
1289   (struct dwarf2_section_info *, sect_offset);
1290
1291 static void abbrev_table_free (struct abbrev_table *);
1292
1293 static void abbrev_table_free_cleanup (void *);
1294
1295 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1296                                  struct dwarf2_section_info *);
1297
1298 static void dwarf2_free_abbrev_table (void *);
1299
1300 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1301
1302 static struct partial_die_info *load_partial_dies
1303   (const struct die_reader_specs *, gdb_byte *, int);
1304
1305 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1306                                    struct partial_die_info *,
1307                                    struct abbrev_info *,
1308                                    unsigned int,
1309                                    gdb_byte *);
1310
1311 static struct partial_die_info *find_partial_die (sect_offset, int,
1312                                                   struct dwarf2_cu *);
1313
1314 static void fixup_partial_die (struct partial_die_info *,
1315                                struct dwarf2_cu *);
1316
1317 static gdb_byte *read_attribute (const struct die_reader_specs *,
1318                                  struct attribute *, struct attr_abbrev *,
1319                                  gdb_byte *);
1320
1321 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1322
1323 static int read_1_signed_byte (bfd *, const gdb_byte *);
1324
1325 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1326
1327 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1328
1329 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1330
1331 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1332                                unsigned int *);
1333
1334 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1335
1336 static LONGEST read_checked_initial_length_and_offset
1337   (bfd *, gdb_byte *, const struct comp_unit_head *,
1338    unsigned int *, unsigned int *);
1339
1340 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1341                             unsigned int *);
1342
1343 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1344
1345 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1346                                        sect_offset);
1347
1348 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1349
1350 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1351
1352 static char *read_indirect_string (bfd *, gdb_byte *,
1353                                    const struct comp_unit_head *,
1354                                    unsigned int *);
1355
1356 static char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1357
1358 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1359
1360 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1361
1362 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1363                                               unsigned int *);
1364
1365 static char *read_str_index (const struct die_reader_specs *reader,
1366                              struct dwarf2_cu *cu, ULONGEST str_index);
1367
1368 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1369
1370 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1371                                       struct dwarf2_cu *);
1372
1373 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1374                                                 unsigned int);
1375
1376 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1377                                struct dwarf2_cu *cu);
1378
1379 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1380
1381 static struct die_info *die_specification (struct die_info *die,
1382                                            struct dwarf2_cu **);
1383
1384 static void free_line_header (struct line_header *lh);
1385
1386 static void add_file_name (struct line_header *, char *, unsigned int,
1387                            unsigned int, unsigned int);
1388
1389 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1390                                                      struct dwarf2_cu *cu);
1391
1392 static void dwarf_decode_lines (struct line_header *, const char *,
1393                                 struct dwarf2_cu *, struct partial_symtab *,
1394                                 int);
1395
1396 static void dwarf2_start_subfile (char *, const char *, const char *);
1397
1398 static void dwarf2_start_symtab (struct dwarf2_cu *,
1399                                  char *, char *, CORE_ADDR);
1400
1401 static struct symbol *new_symbol (struct die_info *, struct type *,
1402                                   struct dwarf2_cu *);
1403
1404 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1405                                        struct dwarf2_cu *, struct symbol *);
1406
1407 static void dwarf2_const_value (struct attribute *, struct symbol *,
1408                                 struct dwarf2_cu *);
1409
1410 static void dwarf2_const_value_attr (struct attribute *attr,
1411                                      struct type *type,
1412                                      const char *name,
1413                                      struct obstack *obstack,
1414                                      struct dwarf2_cu *cu, LONGEST *value,
1415                                      gdb_byte **bytes,
1416                                      struct dwarf2_locexpr_baton **baton);
1417
1418 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1419
1420 static int need_gnat_info (struct dwarf2_cu *);
1421
1422 static struct type *die_descriptive_type (struct die_info *,
1423                                           struct dwarf2_cu *);
1424
1425 static void set_descriptive_type (struct type *, struct die_info *,
1426                                   struct dwarf2_cu *);
1427
1428 static struct type *die_containing_type (struct die_info *,
1429                                          struct dwarf2_cu *);
1430
1431 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1432                                      struct dwarf2_cu *);
1433
1434 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1435
1436 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1437
1438 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1439
1440 static char *typename_concat (struct obstack *obs, const char *prefix,
1441                               const char *suffix, int physname,
1442                               struct dwarf2_cu *cu);
1443
1444 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1445
1446 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1447
1448 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1449
1450 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1451
1452 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1453
1454 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1455                                struct dwarf2_cu *, struct partial_symtab *);
1456
1457 static int dwarf2_get_pc_bounds (struct die_info *,
1458                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1459                                  struct partial_symtab *);
1460
1461 static void get_scope_pc_bounds (struct die_info *,
1462                                  CORE_ADDR *, CORE_ADDR *,
1463                                  struct dwarf2_cu *);
1464
1465 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1466                                         CORE_ADDR, struct dwarf2_cu *);
1467
1468 static void dwarf2_add_field (struct field_info *, struct die_info *,
1469                               struct dwarf2_cu *);
1470
1471 static void dwarf2_attach_fields_to_type (struct field_info *,
1472                                           struct type *, struct dwarf2_cu *);
1473
1474 static void dwarf2_add_member_fn (struct field_info *,
1475                                   struct die_info *, struct type *,
1476                                   struct dwarf2_cu *);
1477
1478 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1479                                              struct type *,
1480                                              struct dwarf2_cu *);
1481
1482 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1483
1484 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1485
1486 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1487
1488 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1489
1490 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1491
1492 static struct type *read_module_type (struct die_info *die,
1493                                       struct dwarf2_cu *cu);
1494
1495 static const char *namespace_name (struct die_info *die,
1496                                    int *is_anonymous, struct dwarf2_cu *);
1497
1498 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1499
1500 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1501
1502 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1503                                                        struct dwarf2_cu *);
1504
1505 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1506                                                gdb_byte *info_ptr,
1507                                                gdb_byte **new_info_ptr,
1508                                                struct die_info *parent);
1509
1510 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1511                                                gdb_byte *info_ptr,
1512                                                gdb_byte **new_info_ptr,
1513                                                struct die_info *parent);
1514
1515 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1516                                   struct die_info **, gdb_byte *, int *, int);
1517
1518 static gdb_byte *read_full_die (const struct die_reader_specs *,
1519                                 struct die_info **, gdb_byte *, int *);
1520
1521 static void process_die (struct die_info *, struct dwarf2_cu *);
1522
1523 static char *dwarf2_canonicalize_name (char *, struct dwarf2_cu *,
1524                                        struct obstack *);
1525
1526 static char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1527
1528 static const char *dwarf2_full_name (char *name,
1529                                      struct die_info *die,
1530                                      struct dwarf2_cu *cu);
1531
1532 static struct die_info *dwarf2_extension (struct die_info *die,
1533                                           struct dwarf2_cu **);
1534
1535 static const char *dwarf_tag_name (unsigned int);
1536
1537 static const char *dwarf_attr_name (unsigned int);
1538
1539 static const char *dwarf_form_name (unsigned int);
1540
1541 static char *dwarf_bool_name (unsigned int);
1542
1543 static const char *dwarf_type_encoding_name (unsigned int);
1544
1545 static struct die_info *sibling_die (struct die_info *);
1546
1547 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1548
1549 static void dump_die_for_error (struct die_info *);
1550
1551 static void dump_die_1 (struct ui_file *, int level, int max_level,
1552                         struct die_info *);
1553
1554 /*static*/ void dump_die (struct die_info *, int max_level);
1555
1556 static void store_in_ref_table (struct die_info *,
1557                                 struct dwarf2_cu *);
1558
1559 static int is_ref_attr (struct attribute *);
1560
1561 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1562
1563 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1564
1565 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1566                                                struct attribute *,
1567                                                struct dwarf2_cu **);
1568
1569 static struct die_info *follow_die_ref (struct die_info *,
1570                                         struct attribute *,
1571                                         struct dwarf2_cu **);
1572
1573 static struct die_info *follow_die_sig (struct die_info *,
1574                                         struct attribute *,
1575                                         struct dwarf2_cu **);
1576
1577 static struct signatured_type *lookup_signatured_type_at_offset
1578     (struct objfile *objfile,
1579      struct dwarf2_section_info *section, sect_offset offset);
1580
1581 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1582
1583 static void read_signatured_type (struct signatured_type *);
1584
1585 static struct type_unit_group *get_type_unit_group
1586     (struct dwarf2_cu *, struct attribute *);
1587
1588 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1589
1590 /* memory allocation interface */
1591
1592 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1593
1594 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1595
1596 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1597                                  char *, int);
1598
1599 static int attr_form_is_block (struct attribute *);
1600
1601 static int attr_form_is_section_offset (struct attribute *);
1602
1603 static int attr_form_is_constant (struct attribute *);
1604
1605 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1606                                    struct dwarf2_loclist_baton *baton,
1607                                    struct attribute *attr);
1608
1609 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1610                                          struct symbol *sym,
1611                                          struct dwarf2_cu *cu);
1612
1613 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1614                                gdb_byte *info_ptr,
1615                                struct abbrev_info *abbrev);
1616
1617 static void free_stack_comp_unit (void *);
1618
1619 static hashval_t partial_die_hash (const void *item);
1620
1621 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1622
1623 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1624   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1625
1626 static void init_one_comp_unit (struct dwarf2_cu *cu,
1627                                 struct dwarf2_per_cu_data *per_cu);
1628
1629 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1630                                    struct die_info *comp_unit_die,
1631                                    enum language pretend_language);
1632
1633 static void free_heap_comp_unit (void *);
1634
1635 static void free_cached_comp_units (void *);
1636
1637 static void age_cached_comp_units (void);
1638
1639 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1640
1641 static struct type *set_die_type (struct die_info *, struct type *,
1642                                   struct dwarf2_cu *);
1643
1644 static void create_all_comp_units (struct objfile *);
1645
1646 static int create_all_type_units (struct objfile *);
1647
1648 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1649                                  enum language);
1650
1651 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1652                                     enum language);
1653
1654 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1655                                     enum language);
1656
1657 static void dwarf2_add_dependence (struct dwarf2_cu *,
1658                                    struct dwarf2_per_cu_data *);
1659
1660 static void dwarf2_mark (struct dwarf2_cu *);
1661
1662 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1663
1664 static struct type *get_die_type_at_offset (sect_offset,
1665                                             struct dwarf2_per_cu_data *per_cu);
1666
1667 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1668
1669 static void dwarf2_release_queue (void *dummy);
1670
1671 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1672                              enum language pretend_language);
1673
1674 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1675                                   struct dwarf2_per_cu_data *per_cu,
1676                                   enum language pretend_language);
1677
1678 static void process_queue (void);
1679
1680 static void find_file_and_directory (struct die_info *die,
1681                                      struct dwarf2_cu *cu,
1682                                      char **name, char **comp_dir);
1683
1684 static char *file_full_name (int file, struct line_header *lh,
1685                              const char *comp_dir);
1686
1687 static gdb_byte *read_and_check_comp_unit_head
1688   (struct comp_unit_head *header,
1689    struct dwarf2_section_info *section,
1690    struct dwarf2_section_info *abbrev_section, gdb_byte *info_ptr,
1691    int is_debug_types_section);
1692
1693 static void init_cutu_and_read_dies
1694   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1695    int use_existing_cu, int keep,
1696    die_reader_func_ftype *die_reader_func, void *data);
1697
1698 static void init_cutu_and_read_dies_simple
1699   (struct dwarf2_per_cu_data *this_cu,
1700    die_reader_func_ftype *die_reader_func, void *data);
1701
1702 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1703
1704 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1705
1706 static struct dwo_unit *lookup_dwo_comp_unit
1707   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1708
1709 static struct dwo_unit *lookup_dwo_type_unit
1710   (struct signatured_type *, const char *, const char *);
1711
1712 static void free_dwo_file_cleanup (void *);
1713
1714 static void process_cu_includes (void);
1715
1716 #if WORDS_BIGENDIAN
1717
1718 /* Convert VALUE between big- and little-endian.  */
1719 static offset_type
1720 byte_swap (offset_type value)
1721 {
1722   offset_type result;
1723
1724   result = (value & 0xff) << 24;
1725   result |= (value & 0xff00) << 8;
1726   result |= (value & 0xff0000) >> 8;
1727   result |= (value & 0xff000000) >> 24;
1728   return result;
1729 }
1730
1731 #define MAYBE_SWAP(V)  byte_swap (V)
1732
1733 #else
1734 #define MAYBE_SWAP(V) (V)
1735 #endif /* WORDS_BIGENDIAN */
1736
1737 /* The suffix for an index file.  */
1738 #define INDEX_SUFFIX ".gdb-index"
1739
1740 static const char *dwarf2_physname (char *name, struct die_info *die,
1741                                     struct dwarf2_cu *cu);
1742
1743 /* Try to locate the sections we need for DWARF 2 debugging
1744    information and return true if we have enough to do something.
1745    NAMES points to the dwarf2 section names, or is NULL if the standard
1746    ELF names are used.  */
1747
1748 int
1749 dwarf2_has_info (struct objfile *objfile,
1750                  const struct dwarf2_debug_sections *names)
1751 {
1752   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1753   if (!dwarf2_per_objfile)
1754     {
1755       /* Initialize per-objfile state.  */
1756       struct dwarf2_per_objfile *data
1757         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1758
1759       memset (data, 0, sizeof (*data));
1760       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1761       dwarf2_per_objfile = data;
1762
1763       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1764                              (void *) names);
1765       dwarf2_per_objfile->objfile = objfile;
1766     }
1767   return (dwarf2_per_objfile->info.asection != NULL
1768           && dwarf2_per_objfile->abbrev.asection != NULL);
1769 }
1770
1771 /* When loading sections, we look either for uncompressed section or for
1772    compressed section names.  */
1773
1774 static int
1775 section_is_p (const char *section_name,
1776               const struct dwarf2_section_names *names)
1777 {
1778   if (names->normal != NULL
1779       && strcmp (section_name, names->normal) == 0)
1780     return 1;
1781   if (names->compressed != NULL
1782       && strcmp (section_name, names->compressed) == 0)
1783     return 1;
1784   return 0;
1785 }
1786
1787 /* This function is mapped across the sections and remembers the
1788    offset and size of each of the debugging sections we are interested
1789    in.  */
1790
1791 static void
1792 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1793 {
1794   const struct dwarf2_debug_sections *names;
1795   flagword aflag = bfd_get_section_flags (abfd, sectp);
1796
1797   if (vnames == NULL)
1798     names = &dwarf2_elf_names;
1799   else
1800     names = (const struct dwarf2_debug_sections *) vnames;
1801
1802   if ((aflag & SEC_HAS_CONTENTS) == 0)
1803     {
1804     }
1805   else if (section_is_p (sectp->name, &names->info))
1806     {
1807       dwarf2_per_objfile->info.asection = sectp;
1808       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1809     }
1810   else if (section_is_p (sectp->name, &names->abbrev))
1811     {
1812       dwarf2_per_objfile->abbrev.asection = sectp;
1813       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1814     }
1815   else if (section_is_p (sectp->name, &names->line))
1816     {
1817       dwarf2_per_objfile->line.asection = sectp;
1818       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1819     }
1820   else if (section_is_p (sectp->name, &names->loc))
1821     {
1822       dwarf2_per_objfile->loc.asection = sectp;
1823       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1824     }
1825   else if (section_is_p (sectp->name, &names->macinfo))
1826     {
1827       dwarf2_per_objfile->macinfo.asection = sectp;
1828       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1829     }
1830   else if (section_is_p (sectp->name, &names->macro))
1831     {
1832       dwarf2_per_objfile->macro.asection = sectp;
1833       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1834     }
1835   else if (section_is_p (sectp->name, &names->str))
1836     {
1837       dwarf2_per_objfile->str.asection = sectp;
1838       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1839     }
1840   else if (section_is_p (sectp->name, &names->addr))
1841     {
1842       dwarf2_per_objfile->addr.asection = sectp;
1843       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1844     }
1845   else if (section_is_p (sectp->name, &names->frame))
1846     {
1847       dwarf2_per_objfile->frame.asection = sectp;
1848       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1849     }
1850   else if (section_is_p (sectp->name, &names->eh_frame))
1851     {
1852       dwarf2_per_objfile->eh_frame.asection = sectp;
1853       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1854     }
1855   else if (section_is_p (sectp->name, &names->ranges))
1856     {
1857       dwarf2_per_objfile->ranges.asection = sectp;
1858       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1859     }
1860   else if (section_is_p (sectp->name, &names->types))
1861     {
1862       struct dwarf2_section_info type_section;
1863
1864       memset (&type_section, 0, sizeof (type_section));
1865       type_section.asection = sectp;
1866       type_section.size = bfd_get_section_size (sectp);
1867
1868       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1869                      &type_section);
1870     }
1871   else if (section_is_p (sectp->name, &names->gdb_index))
1872     {
1873       dwarf2_per_objfile->gdb_index.asection = sectp;
1874       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1875     }
1876
1877   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1878       && bfd_section_vma (abfd, sectp) == 0)
1879     dwarf2_per_objfile->has_section_at_zero = 1;
1880 }
1881
1882 /* A helper function that decides whether a section is empty,
1883    or not present.  */
1884
1885 static int
1886 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1887 {
1888   return info->asection == NULL || info->size == 0;
1889 }
1890
1891 /* Read the contents of the section INFO.
1892    OBJFILE is the main object file, but not necessarily the file where
1893    the section comes from.  E.g., for DWO files INFO->asection->owner
1894    is the bfd of the DWO file.
1895    If the section is compressed, uncompress it before returning.  */
1896
1897 static void
1898 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1899 {
1900   asection *sectp = info->asection;
1901   bfd *abfd;
1902   gdb_byte *buf, *retbuf;
1903   unsigned char header[4];
1904
1905   if (info->readin)
1906     return;
1907   info->buffer = NULL;
1908   info->readin = 1;
1909
1910   if (dwarf2_section_empty_p (info))
1911     return;
1912
1913   abfd = sectp->owner;
1914
1915   /* If the section has relocations, we must read it ourselves.
1916      Otherwise we attach it to the BFD.  */
1917   if ((sectp->flags & SEC_RELOC) == 0)
1918     {
1919       const gdb_byte *bytes = gdb_bfd_map_section (sectp, &info->size);
1920
1921       /* We have to cast away const here for historical reasons.
1922          Fixing dwarf2read to be const-correct would be quite nice.  */
1923       info->buffer = (gdb_byte *) bytes;
1924       return;
1925     }
1926
1927   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1928   info->buffer = buf;
1929
1930   /* When debugging .o files, we may need to apply relocations; see
1931      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1932      We never compress sections in .o files, so we only need to
1933      try this when the section is not compressed.  */
1934   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1935   if (retbuf != NULL)
1936     {
1937       info->buffer = retbuf;
1938       return;
1939     }
1940
1941   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1942       || bfd_bread (buf, info->size, abfd) != info->size)
1943     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1944            bfd_get_filename (abfd));
1945 }
1946
1947 /* A helper function that returns the size of a section in a safe way.
1948    If you are positive that the section has been read before using the
1949    size, then it is safe to refer to the dwarf2_section_info object's
1950    "size" field directly.  In other cases, you must call this
1951    function, because for compressed sections the size field is not set
1952    correctly until the section has been read.  */
1953
1954 static bfd_size_type
1955 dwarf2_section_size (struct objfile *objfile,
1956                      struct dwarf2_section_info *info)
1957 {
1958   if (!info->readin)
1959     dwarf2_read_section (objfile, info);
1960   return info->size;
1961 }
1962
1963 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1964    SECTION_NAME.  */
1965
1966 void
1967 dwarf2_get_section_info (struct objfile *objfile,
1968                          enum dwarf2_section_enum sect,
1969                          asection **sectp, gdb_byte **bufp,
1970                          bfd_size_type *sizep)
1971 {
1972   struct dwarf2_per_objfile *data
1973     = objfile_data (objfile, dwarf2_objfile_data_key);
1974   struct dwarf2_section_info *info;
1975
1976   /* We may see an objfile without any DWARF, in which case we just
1977      return nothing.  */
1978   if (data == NULL)
1979     {
1980       *sectp = NULL;
1981       *bufp = NULL;
1982       *sizep = 0;
1983       return;
1984     }
1985   switch (sect)
1986     {
1987     case DWARF2_DEBUG_FRAME:
1988       info = &data->frame;
1989       break;
1990     case DWARF2_EH_FRAME:
1991       info = &data->eh_frame;
1992       break;
1993     default:
1994       gdb_assert_not_reached ("unexpected section");
1995     }
1996
1997   dwarf2_read_section (objfile, info);
1998
1999   *sectp = info->asection;
2000   *bufp = info->buffer;
2001   *sizep = info->size;
2002 }
2003
2004 /* A helper function to find the sections for a .dwz file.  */
2005
2006 static void
2007 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2008 {
2009   struct dwz_file *dwz_file = arg;
2010
2011   /* Note that we only support the standard ELF names, because .dwz
2012      is ELF-only (at the time of writing).  */
2013   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2014     {
2015       dwz_file->abbrev.asection = sectp;
2016       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2017     }
2018   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2019     {
2020       dwz_file->info.asection = sectp;
2021       dwz_file->info.size = bfd_get_section_size (sectp);
2022     }
2023   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2024     {
2025       dwz_file->str.asection = sectp;
2026       dwz_file->str.size = bfd_get_section_size (sectp);
2027     }
2028   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2029     {
2030       dwz_file->line.asection = sectp;
2031       dwz_file->line.size = bfd_get_section_size (sectp);
2032     }
2033   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2034     {
2035       dwz_file->macro.asection = sectp;
2036       dwz_file->macro.size = bfd_get_section_size (sectp);
2037     }
2038   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2039     {
2040       dwz_file->gdb_index.asection = sectp;
2041       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2042     }
2043 }
2044
2045 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2046    cannot be found.  */
2047
2048 static struct dwz_file *
2049 dwarf2_get_dwz_file (void)
2050 {
2051   bfd *abfd, *dwz_bfd;
2052   asection *section;
2053   gdb_byte *data;
2054   struct cleanup *cleanup;
2055   const char *filename;
2056   struct dwz_file *result;
2057
2058   if (dwarf2_per_objfile->dwz_file != NULL)
2059     return dwarf2_per_objfile->dwz_file;
2060
2061   abfd = dwarf2_per_objfile->objfile->obfd;
2062   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2063   if (section == NULL)
2064     error (_("could not find '.gnu_debugaltlink' section"));
2065   if (!bfd_malloc_and_get_section (abfd, section, &data))
2066     error (_("could not read '.gnu_debugaltlink' section: %s"),
2067            bfd_errmsg (bfd_get_error ()));
2068   cleanup = make_cleanup (xfree, data);
2069
2070   filename = data;
2071   if (!IS_ABSOLUTE_PATH (filename))
2072     {
2073       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2074       char *rel;
2075
2076       make_cleanup (xfree, abs);
2077       abs = ldirname (abs);
2078       make_cleanup (xfree, abs);
2079
2080       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2081       make_cleanup (xfree, rel);
2082       filename = rel;
2083     }
2084
2085   /* The format is just a NUL-terminated file name, followed by the
2086      build-id.  For now, though, we ignore the build-id.  */
2087   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2088   if (dwz_bfd == NULL)
2089     error (_("could not read '%s': %s"), filename,
2090            bfd_errmsg (bfd_get_error ()));
2091
2092   if (!bfd_check_format (dwz_bfd, bfd_object))
2093     {
2094       gdb_bfd_unref (dwz_bfd);
2095       error (_("file '%s' was not usable: %s"), filename,
2096              bfd_errmsg (bfd_get_error ()));
2097     }
2098
2099   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2100                            struct dwz_file);
2101   result->dwz_bfd = dwz_bfd;
2102
2103   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2104
2105   do_cleanups (cleanup);
2106
2107   return result;
2108 }
2109 \f
2110 /* DWARF quick_symbols_functions support.  */
2111
2112 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2113    unique line tables, so we maintain a separate table of all .debug_line
2114    derived entries to support the sharing.
2115    All the quick functions need is the list of file names.  We discard the
2116    line_header when we're done and don't need to record it here.  */
2117 struct quick_file_names
2118 {
2119   /* The data used to construct the hash key.  */
2120   struct stmt_list_hash hash;
2121
2122   /* The number of entries in file_names, real_names.  */
2123   unsigned int num_file_names;
2124
2125   /* The file names from the line table, after being run through
2126      file_full_name.  */
2127   const char **file_names;
2128
2129   /* The file names from the line table after being run through
2130      gdb_realpath.  These are computed lazily.  */
2131   const char **real_names;
2132 };
2133
2134 /* When using the index (and thus not using psymtabs), each CU has an
2135    object of this type.  This is used to hold information needed by
2136    the various "quick" methods.  */
2137 struct dwarf2_per_cu_quick_data
2138 {
2139   /* The file table.  This can be NULL if there was no file table
2140      or it's currently not read in.
2141      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2142   struct quick_file_names *file_names;
2143
2144   /* The corresponding symbol table.  This is NULL if symbols for this
2145      CU have not yet been read.  */
2146   struct symtab *symtab;
2147
2148   /* A temporary mark bit used when iterating over all CUs in
2149      expand_symtabs_matching.  */
2150   unsigned int mark : 1;
2151
2152   /* True if we've tried to read the file table and found there isn't one.
2153      There will be no point in trying to read it again next time.  */
2154   unsigned int no_file_data : 1;
2155 };
2156
2157 /* Utility hash function for a stmt_list_hash.  */
2158
2159 static hashval_t
2160 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2161 {
2162   hashval_t v = 0;
2163
2164   if (stmt_list_hash->dwo_unit != NULL)
2165     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2166   v += stmt_list_hash->line_offset.sect_off;
2167   return v;
2168 }
2169
2170 /* Utility equality function for a stmt_list_hash.  */
2171
2172 static int
2173 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2174                     const struct stmt_list_hash *rhs)
2175 {
2176   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2177     return 0;
2178   if (lhs->dwo_unit != NULL
2179       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2180     return 0;
2181
2182   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2183 }
2184
2185 /* Hash function for a quick_file_names.  */
2186
2187 static hashval_t
2188 hash_file_name_entry (const void *e)
2189 {
2190   const struct quick_file_names *file_data = e;
2191
2192   return hash_stmt_list_entry (&file_data->hash);
2193 }
2194
2195 /* Equality function for a quick_file_names.  */
2196
2197 static int
2198 eq_file_name_entry (const void *a, const void *b)
2199 {
2200   const struct quick_file_names *ea = a;
2201   const struct quick_file_names *eb = b;
2202
2203   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2204 }
2205
2206 /* Delete function for a quick_file_names.  */
2207
2208 static void
2209 delete_file_name_entry (void *e)
2210 {
2211   struct quick_file_names *file_data = e;
2212   int i;
2213
2214   for (i = 0; i < file_data->num_file_names; ++i)
2215     {
2216       xfree ((void*) file_data->file_names[i]);
2217       if (file_data->real_names)
2218         xfree ((void*) file_data->real_names[i]);
2219     }
2220
2221   /* The space for the struct itself lives on objfile_obstack,
2222      so we don't free it here.  */
2223 }
2224
2225 /* Create a quick_file_names hash table.  */
2226
2227 static htab_t
2228 create_quick_file_names_table (unsigned int nr_initial_entries)
2229 {
2230   return htab_create_alloc (nr_initial_entries,
2231                             hash_file_name_entry, eq_file_name_entry,
2232                             delete_file_name_entry, xcalloc, xfree);
2233 }
2234
2235 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2236    have to be created afterwards.  You should call age_cached_comp_units after
2237    processing PER_CU->CU.  dw2_setup must have been already called.  */
2238
2239 static void
2240 load_cu (struct dwarf2_per_cu_data *per_cu)
2241 {
2242   if (per_cu->is_debug_types)
2243     load_full_type_unit (per_cu);
2244   else
2245     load_full_comp_unit (per_cu, language_minimal);
2246
2247   gdb_assert (per_cu->cu != NULL);
2248
2249   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2250 }
2251
2252 /* Read in the symbols for PER_CU.  */
2253
2254 static void
2255 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2256 {
2257   struct cleanup *back_to;
2258
2259   /* Skip type_unit_groups, reading the type units they contain
2260      is handled elsewhere.  */
2261   if (IS_TYPE_UNIT_GROUP (per_cu))
2262     return;
2263
2264   back_to = make_cleanup (dwarf2_release_queue, NULL);
2265
2266   if (dwarf2_per_objfile->using_index
2267       ? per_cu->v.quick->symtab == NULL
2268       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2269     {
2270       queue_comp_unit (per_cu, language_minimal);
2271       load_cu (per_cu);
2272     }
2273
2274   process_queue ();
2275
2276   /* Age the cache, releasing compilation units that have not
2277      been used recently.  */
2278   age_cached_comp_units ();
2279
2280   do_cleanups (back_to);
2281 }
2282
2283 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2284    the objfile from which this CU came.  Returns the resulting symbol
2285    table.  */
2286
2287 static struct symtab *
2288 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2289 {
2290   gdb_assert (dwarf2_per_objfile->using_index);
2291   if (!per_cu->v.quick->symtab)
2292     {
2293       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2294       increment_reading_symtab ();
2295       dw2_do_instantiate_symtab (per_cu);
2296       process_cu_includes ();
2297       do_cleanups (back_to);
2298     }
2299   return per_cu->v.quick->symtab;
2300 }
2301
2302 /* Return the CU given its index.
2303
2304    This is intended for loops like:
2305
2306    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2307                     + dwarf2_per_objfile->n_type_units); ++i)
2308      {
2309        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2310
2311        ...;
2312      }
2313 */
2314
2315 static struct dwarf2_per_cu_data *
2316 dw2_get_cu (int index)
2317 {
2318   if (index >= dwarf2_per_objfile->n_comp_units)
2319     {
2320       index -= dwarf2_per_objfile->n_comp_units;
2321       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2322       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2323     }
2324
2325   return dwarf2_per_objfile->all_comp_units[index];
2326 }
2327
2328 /* Return the primary CU given its index.
2329    The difference between this function and dw2_get_cu is in the handling
2330    of type units (TUs).  Here we return the type_unit_group object.
2331
2332    This is intended for loops like:
2333
2334    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2335                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2336      {
2337        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2338
2339        ...;
2340      }
2341 */
2342
2343 static struct dwarf2_per_cu_data *
2344 dw2_get_primary_cu (int index)
2345 {
2346   if (index >= dwarf2_per_objfile->n_comp_units)
2347     {
2348       index -= dwarf2_per_objfile->n_comp_units;
2349       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2350       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2351     }
2352
2353   return dwarf2_per_objfile->all_comp_units[index];
2354 }
2355
2356 /* A helper function that knows how to read a 64-bit value in a way
2357    that doesn't make gdb die.  Returns 1 if the conversion went ok, 0
2358    otherwise.  */
2359
2360 static int
2361 extract_cu_value (const char *bytes, ULONGEST *result)
2362 {
2363   if (sizeof (ULONGEST) < 8)
2364     {
2365       int i;
2366
2367       /* Ignore the upper 4 bytes if they are all zero.  */
2368       for (i = 0; i < 4; ++i)
2369         if (bytes[i + 4] != 0)
2370           return 0;
2371
2372       *result = extract_unsigned_integer (bytes, 4, BFD_ENDIAN_LITTLE);
2373     }
2374   else
2375     *result = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2376   return 1;
2377 }
2378
2379 /* A helper for create_cus_from_index that handles a given list of
2380    CUs.  */
2381
2382 static int
2383 create_cus_from_index_list (struct objfile *objfile,
2384                             const gdb_byte *cu_list, offset_type n_elements,
2385                             struct dwarf2_section_info *section,
2386                             int is_dwz,
2387                             int base_offset)
2388 {
2389   offset_type i;
2390
2391   for (i = 0; i < n_elements; i += 2)
2392     {
2393       struct dwarf2_per_cu_data *the_cu;
2394       ULONGEST offset, length;
2395
2396       if (!extract_cu_value (cu_list, &offset)
2397           || !extract_cu_value (cu_list + 8, &length))
2398         return 0;
2399       cu_list += 2 * 8;
2400
2401       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2402                                struct dwarf2_per_cu_data);
2403       the_cu->offset.sect_off = offset;
2404       the_cu->length = length;
2405       the_cu->objfile = objfile;
2406       the_cu->info_or_types_section = section;
2407       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2408                                         struct dwarf2_per_cu_quick_data);
2409       the_cu->is_dwz = is_dwz;
2410       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2411     }
2412
2413   return 1;
2414 }
2415
2416 /* Read the CU list from the mapped index, and use it to create all
2417    the CU objects for this objfile.  Return 0 if something went wrong,
2418    1 if everything went ok.  */
2419
2420 static int
2421 create_cus_from_index (struct objfile *objfile,
2422                        const gdb_byte *cu_list, offset_type cu_list_elements,
2423                        const gdb_byte *dwz_list, offset_type dwz_elements)
2424 {
2425   struct dwz_file *dwz;
2426
2427   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2428   dwarf2_per_objfile->all_comp_units
2429     = obstack_alloc (&objfile->objfile_obstack,
2430                      dwarf2_per_objfile->n_comp_units
2431                      * sizeof (struct dwarf2_per_cu_data *));
2432
2433   if (!create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2434                                    &dwarf2_per_objfile->info, 0, 0))
2435     return 0;
2436
2437   if (dwz_elements == 0)
2438     return 1;
2439
2440   dwz = dwarf2_get_dwz_file ();
2441   return create_cus_from_index_list (objfile, dwz_list, dwz_elements,
2442                                      &dwz->info, 1, cu_list_elements / 2);
2443 }
2444
2445 /* Create the signatured type hash table from the index.  */
2446
2447 static int
2448 create_signatured_type_table_from_index (struct objfile *objfile,
2449                                          struct dwarf2_section_info *section,
2450                                          const gdb_byte *bytes,
2451                                          offset_type elements)
2452 {
2453   offset_type i;
2454   htab_t sig_types_hash;
2455
2456   dwarf2_per_objfile->n_type_units = elements / 3;
2457   dwarf2_per_objfile->all_type_units
2458     = obstack_alloc (&objfile->objfile_obstack,
2459                      dwarf2_per_objfile->n_type_units
2460                      * sizeof (struct signatured_type *));
2461
2462   sig_types_hash = allocate_signatured_type_table (objfile);
2463
2464   for (i = 0; i < elements; i += 3)
2465     {
2466       struct signatured_type *sig_type;
2467       ULONGEST offset, type_offset_in_tu, signature;
2468       void **slot;
2469
2470       if (!extract_cu_value (bytes, &offset)
2471           || !extract_cu_value (bytes + 8, &type_offset_in_tu))
2472         return 0;
2473       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2474       bytes += 3 * 8;
2475
2476       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2477                                  struct signatured_type);
2478       sig_type->signature = signature;
2479       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2480       sig_type->per_cu.is_debug_types = 1;
2481       sig_type->per_cu.info_or_types_section = section;
2482       sig_type->per_cu.offset.sect_off = offset;
2483       sig_type->per_cu.objfile = objfile;
2484       sig_type->per_cu.v.quick
2485         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2486                           struct dwarf2_per_cu_quick_data);
2487
2488       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2489       *slot = sig_type;
2490
2491       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2492     }
2493
2494   dwarf2_per_objfile->signatured_types = sig_types_hash;
2495
2496   return 1;
2497 }
2498
2499 /* Read the address map data from the mapped index, and use it to
2500    populate the objfile's psymtabs_addrmap.  */
2501
2502 static void
2503 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2504 {
2505   const gdb_byte *iter, *end;
2506   struct obstack temp_obstack;
2507   struct addrmap *mutable_map;
2508   struct cleanup *cleanup;
2509   CORE_ADDR baseaddr;
2510
2511   obstack_init (&temp_obstack);
2512   cleanup = make_cleanup_obstack_free (&temp_obstack);
2513   mutable_map = addrmap_create_mutable (&temp_obstack);
2514
2515   iter = index->address_table;
2516   end = iter + index->address_table_size;
2517
2518   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2519
2520   while (iter < end)
2521     {
2522       ULONGEST hi, lo, cu_index;
2523       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2524       iter += 8;
2525       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2526       iter += 8;
2527       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2528       iter += 4;
2529       
2530       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2531                          dw2_get_cu (cu_index));
2532     }
2533
2534   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2535                                                     &objfile->objfile_obstack);
2536   do_cleanups (cleanup);
2537 }
2538
2539 /* The hash function for strings in the mapped index.  This is the same as
2540    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2541    implementation.  This is necessary because the hash function is tied to the
2542    format of the mapped index file.  The hash values do not have to match with
2543    SYMBOL_HASH_NEXT.
2544    
2545    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2546
2547 static hashval_t
2548 mapped_index_string_hash (int index_version, const void *p)
2549 {
2550   const unsigned char *str = (const unsigned char *) p;
2551   hashval_t r = 0;
2552   unsigned char c;
2553
2554   while ((c = *str++) != 0)
2555     {
2556       if (index_version >= 5)
2557         c = tolower (c);
2558       r = r * 67 + c - 113;
2559     }
2560
2561   return r;
2562 }
2563
2564 /* Find a slot in the mapped index INDEX for the object named NAME.
2565    If NAME is found, set *VEC_OUT to point to the CU vector in the
2566    constant pool and return 1.  If NAME cannot be found, return 0.  */
2567
2568 static int
2569 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2570                           offset_type **vec_out)
2571 {
2572   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2573   offset_type hash;
2574   offset_type slot, step;
2575   int (*cmp) (const char *, const char *);
2576
2577   if (current_language->la_language == language_cplus
2578       || current_language->la_language == language_java
2579       || current_language->la_language == language_fortran)
2580     {
2581       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2582          not contain any.  */
2583       const char *paren = strchr (name, '(');
2584
2585       if (paren)
2586         {
2587           char *dup;
2588
2589           dup = xmalloc (paren - name + 1);
2590           memcpy (dup, name, paren - name);
2591           dup[paren - name] = 0;
2592
2593           make_cleanup (xfree, dup);
2594           name = dup;
2595         }
2596     }
2597
2598   /* Index version 4 did not support case insensitive searches.  But the
2599      indices for case insensitive languages are built in lowercase, therefore
2600      simulate our NAME being searched is also lowercased.  */
2601   hash = mapped_index_string_hash ((index->version == 4
2602                                     && case_sensitivity == case_sensitive_off
2603                                     ? 5 : index->version),
2604                                    name);
2605
2606   slot = hash & (index->symbol_table_slots - 1);
2607   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2608   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2609
2610   for (;;)
2611     {
2612       /* Convert a slot number to an offset into the table.  */
2613       offset_type i = 2 * slot;
2614       const char *str;
2615       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2616         {
2617           do_cleanups (back_to);
2618           return 0;
2619         }
2620
2621       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2622       if (!cmp (name, str))
2623         {
2624           *vec_out = (offset_type *) (index->constant_pool
2625                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2626           do_cleanups (back_to);
2627           return 1;
2628         }
2629
2630       slot = (slot + step) & (index->symbol_table_slots - 1);
2631     }
2632 }
2633
2634 /* A helper function that reads the .gdb_index from SECTION and fills
2635    in MAP.  FILENAME is the name of the file containing the section;
2636    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2637    ok to use deprecated sections.
2638
2639    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2640    out parameters that are filled in with information about the CU and
2641    TU lists in the section.
2642
2643    Returns 1 if all went well, 0 otherwise.  */
2644
2645 static int
2646 read_index_from_section (struct objfile *objfile,
2647                          const char *filename,
2648                          int deprecated_ok,
2649                          struct dwarf2_section_info *section,
2650                          struct mapped_index *map,
2651                          const gdb_byte **cu_list,
2652                          offset_type *cu_list_elements,
2653                          const gdb_byte **types_list,
2654                          offset_type *types_list_elements)
2655 {
2656   char *addr;
2657   offset_type version;
2658   offset_type *metadata;
2659   int i;
2660
2661   if (dwarf2_section_empty_p (section))
2662     return 0;
2663
2664   /* Older elfutils strip versions could keep the section in the main
2665      executable while splitting it for the separate debug info file.  */
2666   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2667     return 0;
2668
2669   dwarf2_read_section (objfile, section);
2670
2671   addr = section->buffer;
2672   /* Version check.  */
2673   version = MAYBE_SWAP (*(offset_type *) addr);
2674   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2675      causes the index to behave very poorly for certain requests.  Version 3
2676      contained incomplete addrmap.  So, it seems better to just ignore such
2677      indices.  */
2678   if (version < 4)
2679     {
2680       static int warning_printed = 0;
2681       if (!warning_printed)
2682         {
2683           warning (_("Skipping obsolete .gdb_index section in %s."),
2684                    filename);
2685           warning_printed = 1;
2686         }
2687       return 0;
2688     }
2689   /* Index version 4 uses a different hash function than index version
2690      5 and later.
2691
2692      Versions earlier than 6 did not emit psymbols for inlined
2693      functions.  Using these files will cause GDB not to be able to
2694      set breakpoints on inlined functions by name, so we ignore these
2695      indices unless the user has done
2696      "set use-deprecated-index-sections on".  */
2697   if (version < 6 && !deprecated_ok)
2698     {
2699       static int warning_printed = 0;
2700       if (!warning_printed)
2701         {
2702           warning (_("\
2703 Skipping deprecated .gdb_index section in %s.\n\
2704 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2705 to use the section anyway."),
2706                    filename);
2707           warning_printed = 1;
2708         }
2709       return 0;
2710     }
2711   /* Indexes with higher version than the one supported by GDB may be no
2712      longer backward compatible.  */
2713   if (version > 7)
2714     return 0;
2715
2716   map->version = version;
2717   map->total_size = section->size;
2718
2719   metadata = (offset_type *) (addr + sizeof (offset_type));
2720
2721   i = 0;
2722   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2723   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2724                        / 8);
2725   ++i;
2726
2727   *types_list = addr + MAYBE_SWAP (metadata[i]);
2728   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2729                            - MAYBE_SWAP (metadata[i]))
2730                           / 8);
2731   ++i;
2732
2733   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2734   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2735                              - MAYBE_SWAP (metadata[i]));
2736   ++i;
2737
2738   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2739   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2740                               - MAYBE_SWAP (metadata[i]))
2741                              / (2 * sizeof (offset_type)));
2742   ++i;
2743
2744   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2745
2746   return 1;
2747 }
2748
2749
2750 /* Read the index file.  If everything went ok, initialize the "quick"
2751    elements of all the CUs and return 1.  Otherwise, return 0.  */
2752
2753 static int
2754 dwarf2_read_index (struct objfile *objfile)
2755 {
2756   struct mapped_index local_map, *map;
2757   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2758   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2759
2760   if (!read_index_from_section (objfile, objfile->name,
2761                                 use_deprecated_index_sections,
2762                                 &dwarf2_per_objfile->gdb_index, &local_map,
2763                                 &cu_list, &cu_list_elements,
2764                                 &types_list, &types_list_elements))
2765     return 0;
2766
2767   /* Don't use the index if it's empty.  */
2768   if (local_map.symbol_table_slots == 0)
2769     return 0;
2770
2771   /* If there is a .dwz file, read it so we can get its CU list as
2772      well.  */
2773   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2774     {
2775       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2776       struct mapped_index dwz_map;
2777       const gdb_byte *dwz_types_ignore;
2778       offset_type dwz_types_elements_ignore;
2779
2780       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2781                                     1,
2782                                     &dwz->gdb_index, &dwz_map,
2783                                     &dwz_list, &dwz_list_elements,
2784                                     &dwz_types_ignore,
2785                                     &dwz_types_elements_ignore))
2786         {
2787           warning (_("could not read '.gdb_index' section from %s; skipping"),
2788                    bfd_get_filename (dwz->dwz_bfd));
2789           return 0;
2790         }
2791     }
2792
2793   if (!create_cus_from_index (objfile, cu_list, cu_list_elements,
2794                               dwz_list, dwz_list_elements))
2795     return 0;
2796
2797   if (types_list_elements)
2798     {
2799       struct dwarf2_section_info *section;
2800
2801       /* We can only handle a single .debug_types when we have an
2802          index.  */
2803       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2804         return 0;
2805
2806       section = VEC_index (dwarf2_section_info_def,
2807                            dwarf2_per_objfile->types, 0);
2808
2809       if (!create_signatured_type_table_from_index (objfile, section,
2810                                                     types_list,
2811                                                     types_list_elements))
2812         return 0;
2813     }
2814
2815   create_addrmap_from_index (objfile, &local_map);
2816
2817   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2818   *map = local_map;
2819
2820   dwarf2_per_objfile->index_table = map;
2821   dwarf2_per_objfile->using_index = 1;
2822   dwarf2_per_objfile->quick_file_names_table =
2823     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2824
2825   return 1;
2826 }
2827
2828 /* A helper for the "quick" functions which sets the global
2829    dwarf2_per_objfile according to OBJFILE.  */
2830
2831 static void
2832 dw2_setup (struct objfile *objfile)
2833 {
2834   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2835   gdb_assert (dwarf2_per_objfile);
2836 }
2837
2838 /* Reader function for dw2_build_type_unit_groups.  */
2839
2840 static void
2841 dw2_build_type_unit_groups_reader (const struct die_reader_specs *reader,
2842                                    gdb_byte *info_ptr,
2843                                    struct die_info *type_unit_die,
2844                                    int has_children,
2845                                    void *data)
2846 {
2847   struct dwarf2_cu *cu = reader->cu;
2848   struct attribute *attr;
2849   struct type_unit_group *tu_group;
2850
2851   gdb_assert (data == NULL);
2852
2853   if (! has_children)
2854     return;
2855
2856   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
2857   /* Call this for its side-effect of creating the associated
2858      struct type_unit_group if it doesn't already exist.  */
2859   tu_group = get_type_unit_group (cu, attr);
2860 }
2861
2862 /* Build dwarf2_per_objfile->type_unit_groups.
2863    This function may be called multiple times.  */
2864
2865 static void
2866 dw2_build_type_unit_groups (void)
2867 {
2868   if (dwarf2_per_objfile->type_unit_groups == NULL)
2869     build_type_unit_groups (dw2_build_type_unit_groups_reader, NULL);
2870 }
2871
2872 /* die_reader_func for dw2_get_file_names.  */
2873
2874 static void
2875 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2876                            gdb_byte *info_ptr,
2877                            struct die_info *comp_unit_die,
2878                            int has_children,
2879                            void *data)
2880 {
2881   struct dwarf2_cu *cu = reader->cu;
2882   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2883   struct objfile *objfile = dwarf2_per_objfile->objfile;
2884   struct dwarf2_per_cu_data *lh_cu;
2885   struct line_header *lh;
2886   struct attribute *attr;
2887   int i;
2888   char *name, *comp_dir;
2889   void **slot;
2890   struct quick_file_names *qfn;
2891   unsigned int line_offset;
2892
2893   /* Our callers never want to match partial units -- instead they
2894      will match the enclosing full CU.  */
2895   if (comp_unit_die->tag == DW_TAG_partial_unit)
2896     {
2897       this_cu->v.quick->no_file_data = 1;
2898       return;
2899     }
2900
2901   /* If we're reading the line header for TUs, store it in the "per_cu"
2902      for tu_group.  */
2903   if (this_cu->is_debug_types)
2904     {
2905       struct type_unit_group *tu_group = data;
2906
2907       gdb_assert (tu_group != NULL);
2908       lh_cu = &tu_group->per_cu;
2909     }
2910   else
2911     lh_cu = this_cu;
2912
2913   lh = NULL;
2914   slot = NULL;
2915   line_offset = 0;
2916
2917   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2918   if (attr)
2919     {
2920       struct quick_file_names find_entry;
2921
2922       line_offset = DW_UNSND (attr);
2923
2924       /* We may have already read in this line header (TU line header sharing).
2925          If we have we're done.  */
2926       find_entry.hash.dwo_unit = cu->dwo_unit;
2927       find_entry.hash.line_offset.sect_off = line_offset;
2928       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2929                              &find_entry, INSERT);
2930       if (*slot != NULL)
2931         {
2932           lh_cu->v.quick->file_names = *slot;
2933           return;
2934         }
2935
2936       lh = dwarf_decode_line_header (line_offset, cu);
2937     }
2938   if (lh == NULL)
2939     {
2940       lh_cu->v.quick->no_file_data = 1;
2941       return;
2942     }
2943
2944   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2945   qfn->hash.dwo_unit = cu->dwo_unit;
2946   qfn->hash.line_offset.sect_off = line_offset;
2947   gdb_assert (slot != NULL);
2948   *slot = qfn;
2949
2950   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2951
2952   qfn->num_file_names = lh->num_file_names;
2953   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2954                                    lh->num_file_names * sizeof (char *));
2955   for (i = 0; i < lh->num_file_names; ++i)
2956     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2957   qfn->real_names = NULL;
2958
2959   free_line_header (lh);
2960
2961   lh_cu->v.quick->file_names = qfn;
2962 }
2963
2964 /* A helper for the "quick" functions which attempts to read the line
2965    table for THIS_CU.  */
2966
2967 static struct quick_file_names *
2968 dw2_get_file_names (struct objfile *objfile,
2969                     struct dwarf2_per_cu_data *this_cu)
2970 {
2971   /* For TUs this should only be called on the parent group.  */
2972   if (this_cu->is_debug_types)
2973     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2974
2975   if (this_cu->v.quick->file_names != NULL)
2976     return this_cu->v.quick->file_names;
2977   /* If we know there is no line data, no point in looking again.  */
2978   if (this_cu->v.quick->no_file_data)
2979     return NULL;
2980
2981   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2982      in the stub for CUs, there's is no need to lookup the DWO file.
2983      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2984      DWO file.  */
2985   if (this_cu->is_debug_types)
2986     {
2987       struct type_unit_group *tu_group = this_cu->s.type_unit_group;
2988
2989       init_cutu_and_read_dies (tu_group->t.first_tu, NULL, 0, 0,
2990                                dw2_get_file_names_reader, tu_group);
2991     }
2992   else
2993     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2994
2995   if (this_cu->v.quick->no_file_data)
2996     return NULL;
2997   return this_cu->v.quick->file_names;
2998 }
2999
3000 /* A helper for the "quick" functions which computes and caches the
3001    real path for a given file name from the line table.  */
3002
3003 static const char *
3004 dw2_get_real_path (struct objfile *objfile,
3005                    struct quick_file_names *qfn, int index)
3006 {
3007   if (qfn->real_names == NULL)
3008     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3009                                       qfn->num_file_names, sizeof (char *));
3010
3011   if (qfn->real_names[index] == NULL)
3012     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3013
3014   return qfn->real_names[index];
3015 }
3016
3017 static struct symtab *
3018 dw2_find_last_source_symtab (struct objfile *objfile)
3019 {
3020   int index;
3021
3022   dw2_setup (objfile);
3023   index = dwarf2_per_objfile->n_comp_units - 1;
3024   return dw2_instantiate_symtab (dw2_get_cu (index));
3025 }
3026
3027 /* Traversal function for dw2_forget_cached_source_info.  */
3028
3029 static int
3030 dw2_free_cached_file_names (void **slot, void *info)
3031 {
3032   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3033
3034   if (file_data->real_names)
3035     {
3036       int i;
3037
3038       for (i = 0; i < file_data->num_file_names; ++i)
3039         {
3040           xfree ((void*) file_data->real_names[i]);
3041           file_data->real_names[i] = NULL;
3042         }
3043     }
3044
3045   return 1;
3046 }
3047
3048 static void
3049 dw2_forget_cached_source_info (struct objfile *objfile)
3050 {
3051   dw2_setup (objfile);
3052
3053   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3054                           dw2_free_cached_file_names, NULL);
3055 }
3056
3057 /* Helper function for dw2_map_symtabs_matching_filename that expands
3058    the symtabs and calls the iterator.  */
3059
3060 static int
3061 dw2_map_expand_apply (struct objfile *objfile,
3062                       struct dwarf2_per_cu_data *per_cu,
3063                       const char *name,
3064                       const char *full_path, const char *real_path,
3065                       int (*callback) (struct symtab *, void *),
3066                       void *data)
3067 {
3068   struct symtab *last_made = objfile->symtabs;
3069
3070   /* Don't visit already-expanded CUs.  */
3071   if (per_cu->v.quick->symtab)
3072     return 0;
3073
3074   /* This may expand more than one symtab, and we want to iterate over
3075      all of them.  */
3076   dw2_instantiate_symtab (per_cu);
3077
3078   return iterate_over_some_symtabs (name, full_path, real_path, callback, data,
3079                                     objfile->symtabs, last_made);
3080 }
3081
3082 /* Implementation of the map_symtabs_matching_filename method.  */
3083
3084 static int
3085 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3086                                    const char *full_path, const char *real_path,
3087                                    int (*callback) (struct symtab *, void *),
3088                                    void *data)
3089 {
3090   int i;
3091   const char *name_basename = lbasename (name);
3092   int name_len = strlen (name);
3093   int is_abs = IS_ABSOLUTE_PATH (name);
3094
3095   dw2_setup (objfile);
3096
3097   dw2_build_type_unit_groups ();
3098
3099   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3100                    + dwarf2_per_objfile->n_type_unit_groups); ++i)
3101     {
3102       int j;
3103       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3104       struct quick_file_names *file_data;
3105
3106       /* We only need to look at symtabs not already expanded.  */
3107       if (per_cu->v.quick->symtab)
3108         continue;
3109
3110       file_data = dw2_get_file_names (objfile, per_cu);
3111       if (file_data == NULL)
3112         continue;
3113
3114       for (j = 0; j < file_data->num_file_names; ++j)
3115         {
3116           const char *this_name = file_data->file_names[j];
3117
3118           if (FILENAME_CMP (name, this_name) == 0
3119               || (!is_abs && compare_filenames_for_search (this_name,
3120                                                            name, name_len)))
3121             {
3122               if (dw2_map_expand_apply (objfile, per_cu,
3123                                         name, full_path, real_path,
3124                                         callback, data))
3125                 return 1;
3126             }
3127
3128           /* Before we invoke realpath, which can get expensive when many
3129              files are involved, do a quick comparison of the basenames.  */
3130           if (! basenames_may_differ
3131               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3132             continue;
3133
3134           if (full_path != NULL)
3135             {
3136               const char *this_real_name = dw2_get_real_path (objfile,
3137                                                               file_data, j);
3138
3139               if (this_real_name != NULL
3140                   && (FILENAME_CMP (full_path, this_real_name) == 0
3141                       || (!is_abs
3142                           && compare_filenames_for_search (this_real_name,
3143                                                            name, name_len))))
3144                 {
3145                   if (dw2_map_expand_apply (objfile, per_cu,
3146                                             name, full_path, real_path,
3147                                             callback, data))
3148                     return 1;
3149                 }
3150             }
3151
3152           if (real_path != NULL)
3153             {
3154               const char *this_real_name = dw2_get_real_path (objfile,
3155                                                               file_data, j);
3156
3157               if (this_real_name != NULL
3158                   && (FILENAME_CMP (real_path, this_real_name) == 0
3159                       || (!is_abs
3160                           && compare_filenames_for_search (this_real_name,
3161                                                            name, name_len))))
3162                 {
3163                   if (dw2_map_expand_apply (objfile, per_cu,
3164                                             name, full_path, real_path,
3165                                             callback, data))
3166                     return 1;
3167                 }
3168             }
3169         }
3170     }
3171
3172   return 0;
3173 }
3174
3175 static struct symtab *
3176 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3177                    const char *name, domain_enum domain)
3178 {
3179   /* We do all the work in the pre_expand_symtabs_matching hook
3180      instead.  */
3181   return NULL;
3182 }
3183
3184 /* A helper function that expands all symtabs that hold an object
3185    named NAME.  If WANT_SPECIFIC_BLOCK is non-zero, only look for
3186    symbols in block BLOCK_KIND.  */
3187
3188 static void
3189 dw2_do_expand_symtabs_matching (struct objfile *objfile,
3190                                 int want_specific_block,
3191                                 enum block_enum block_kind,
3192                                 const char *name, domain_enum domain)
3193 {
3194   struct mapped_index *index;
3195
3196   dw2_setup (objfile);
3197
3198   index = dwarf2_per_objfile->index_table;
3199
3200   /* index_table is NULL if OBJF_READNOW.  */
3201   if (index)
3202     {
3203       offset_type *vec;
3204
3205       if (find_slot_in_mapped_hash (index, name, &vec))
3206         {
3207           offset_type i, len = MAYBE_SWAP (*vec);
3208           for (i = 0; i < len; ++i)
3209             {
3210               offset_type cu_index_and_attrs = MAYBE_SWAP (vec[i + 1]);
3211               offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3212               struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3213               int want_static = block_kind != GLOBAL_BLOCK;
3214               /* This value is only valid for index versions >= 7.  */
3215               int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3216               gdb_index_symbol_kind symbol_kind =
3217                 GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3218               /* Only check the symbol attributes if they're present.
3219                  Indices prior to version 7 don't record them,
3220                  and indices >= 7 may elide them for certain symbols
3221                  (gold does this).  */
3222               int attrs_valid =
3223                 (index->version >= 7
3224                  && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3225
3226               if (attrs_valid
3227                   && want_specific_block
3228                   && want_static != is_static)
3229                 continue;
3230
3231               /* Only check the symbol's kind if it has one.  */
3232               if (attrs_valid)
3233                 {
3234                   switch (domain)
3235                     {
3236                     case VAR_DOMAIN:
3237                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3238                           && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3239                           /* Some types are also in VAR_DOMAIN.  */
3240                           && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3241                         continue;
3242                       break;
3243                     case STRUCT_DOMAIN:
3244                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3245                         continue;
3246                       break;
3247                     case LABEL_DOMAIN:
3248                       if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3249                         continue;
3250                       break;
3251                     default:
3252                       break;
3253                     }
3254                 }
3255
3256               dw2_instantiate_symtab (per_cu);
3257             }
3258         }
3259     }
3260 }
3261
3262 static void
3263 dw2_pre_expand_symtabs_matching (struct objfile *objfile,
3264                                  enum block_enum block_kind, const char *name,
3265                                  domain_enum domain)
3266 {
3267   dw2_do_expand_symtabs_matching (objfile, 1, block_kind, name, domain);
3268 }
3269
3270 static void
3271 dw2_print_stats (struct objfile *objfile)
3272 {
3273   int i, count;
3274
3275   dw2_setup (objfile);
3276   count = 0;
3277   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3278                    + dwarf2_per_objfile->n_type_units); ++i)
3279     {
3280       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3281
3282       if (!per_cu->v.quick->symtab)
3283         ++count;
3284     }
3285   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3286 }
3287
3288 static void
3289 dw2_dump (struct objfile *objfile)
3290 {
3291   /* Nothing worth printing.  */
3292 }
3293
3294 static void
3295 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3296               struct section_offsets *delta)
3297 {
3298   /* There's nothing to relocate here.  */
3299 }
3300
3301 static void
3302 dw2_expand_symtabs_for_function (struct objfile *objfile,
3303                                  const char *func_name)
3304 {
3305   /* Note: It doesn't matter what we pass for block_kind here.  */
3306   dw2_do_expand_symtabs_matching (objfile, 0, GLOBAL_BLOCK, func_name,
3307                                   VAR_DOMAIN);
3308 }
3309
3310 static void
3311 dw2_expand_all_symtabs (struct objfile *objfile)
3312 {
3313   int i;
3314
3315   dw2_setup (objfile);
3316
3317   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3318                    + dwarf2_per_objfile->n_type_units); ++i)
3319     {
3320       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3321
3322       dw2_instantiate_symtab (per_cu);
3323     }
3324 }
3325
3326 static void
3327 dw2_expand_symtabs_with_filename (struct objfile *objfile,
3328                                   const char *filename)
3329 {
3330   int i;
3331
3332   dw2_setup (objfile);
3333
3334   /* We don't need to consider type units here.
3335      This is only called for examining code, e.g. expand_line_sal.
3336      There can be an order of magnitude (or more) more type units
3337      than comp units, and we avoid them if we can.  */
3338
3339   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3340     {
3341       int j;
3342       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3343       struct quick_file_names *file_data;
3344
3345       /* We only need to look at symtabs not already expanded.  */
3346       if (per_cu->v.quick->symtab)
3347         continue;
3348
3349       file_data = dw2_get_file_names (objfile, per_cu);
3350       if (file_data == NULL)
3351         continue;
3352
3353       for (j = 0; j < file_data->num_file_names; ++j)
3354         {
3355           const char *this_name = file_data->file_names[j];
3356           if (FILENAME_CMP (this_name, filename) == 0)
3357             {
3358               dw2_instantiate_symtab (per_cu);
3359               break;
3360             }
3361         }
3362     }
3363 }
3364
3365 /* A helper function for dw2_find_symbol_file that finds the primary
3366    file name for a given CU.  This is a die_reader_func.  */
3367
3368 static void
3369 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3370                                  gdb_byte *info_ptr,
3371                                  struct die_info *comp_unit_die,
3372                                  int has_children,
3373                                  void *data)
3374 {
3375   const char **result_ptr = data;
3376   struct dwarf2_cu *cu = reader->cu;
3377   struct attribute *attr;
3378
3379   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3380   if (attr == NULL)
3381     *result_ptr = NULL;
3382   else
3383     *result_ptr = DW_STRING (attr);
3384 }
3385
3386 static const char *
3387 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3388 {
3389   struct dwarf2_per_cu_data *per_cu;
3390   offset_type *vec;
3391   const char *filename;
3392
3393   dw2_setup (objfile);
3394
3395   /* index_table is NULL if OBJF_READNOW.  */
3396   if (!dwarf2_per_objfile->index_table)
3397     {
3398       struct symtab *s;
3399
3400       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3401         {
3402           struct blockvector *bv = BLOCKVECTOR (s);
3403           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3404           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3405
3406           if (sym)
3407             return SYMBOL_SYMTAB (sym)->filename;
3408         }
3409       return NULL;
3410     }
3411
3412   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3413                                  name, &vec))
3414     return NULL;
3415
3416   /* Note that this just looks at the very first one named NAME -- but
3417      actually we are looking for a function.  find_main_filename
3418      should be rewritten so that it doesn't require a custom hook.  It
3419      could just use the ordinary symbol tables.  */
3420   /* vec[0] is the length, which must always be >0.  */
3421   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3422
3423   if (per_cu->v.quick->symtab != NULL)
3424     return per_cu->v.quick->symtab->filename;
3425
3426   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3427                            dw2_get_primary_filename_reader, &filename);
3428
3429   return filename;
3430 }
3431
3432 static void
3433 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3434                           struct objfile *objfile, int global,
3435                           int (*callback) (struct block *,
3436                                            struct symbol *, void *),
3437                           void *data, symbol_compare_ftype *match,
3438                           symbol_compare_ftype *ordered_compare)
3439 {
3440   /* Currently unimplemented; used for Ada.  The function can be called if the
3441      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3442      does not look for non-Ada symbols this function should just return.  */
3443 }
3444
3445 static void
3446 dw2_expand_symtabs_matching
3447   (struct objfile *objfile,
3448    int (*file_matcher) (const char *, void *),
3449    int (*name_matcher) (const char *, void *),
3450    enum search_domain kind,
3451    void *data)
3452 {
3453   int i;
3454   offset_type iter;
3455   struct mapped_index *index;
3456
3457   dw2_setup (objfile);
3458
3459   /* index_table is NULL if OBJF_READNOW.  */
3460   if (!dwarf2_per_objfile->index_table)
3461     return;
3462   index = dwarf2_per_objfile->index_table;
3463
3464   if (file_matcher != NULL)
3465     {
3466       struct cleanup *cleanup;
3467       htab_t visited_found, visited_not_found;
3468
3469       dw2_build_type_unit_groups ();
3470
3471       visited_found = htab_create_alloc (10,
3472                                          htab_hash_pointer, htab_eq_pointer,
3473                                          NULL, xcalloc, xfree);
3474       cleanup = make_cleanup_htab_delete (visited_found);
3475       visited_not_found = htab_create_alloc (10,
3476                                              htab_hash_pointer, htab_eq_pointer,
3477                                              NULL, xcalloc, xfree);
3478       make_cleanup_htab_delete (visited_not_found);
3479
3480       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3481                        + dwarf2_per_objfile->n_type_unit_groups); ++i)
3482         {
3483           int j;
3484           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3485           struct quick_file_names *file_data;
3486           void **slot;
3487
3488           per_cu->v.quick->mark = 0;
3489
3490           /* We only need to look at symtabs not already expanded.  */
3491           if (per_cu->v.quick->symtab)
3492             continue;
3493
3494           file_data = dw2_get_file_names (objfile, per_cu);
3495           if (file_data == NULL)
3496             continue;
3497
3498           if (htab_find (visited_not_found, file_data) != NULL)
3499             continue;
3500           else if (htab_find (visited_found, file_data) != NULL)
3501             {
3502               per_cu->v.quick->mark = 1;
3503               continue;
3504             }
3505
3506           for (j = 0; j < file_data->num_file_names; ++j)
3507             {
3508               if (file_matcher (file_data->file_names[j], data))
3509                 {
3510                   per_cu->v.quick->mark = 1;
3511                   break;
3512                 }
3513             }
3514
3515           slot = htab_find_slot (per_cu->v.quick->mark
3516                                  ? visited_found
3517                                  : visited_not_found,
3518                                  file_data, INSERT);
3519           *slot = file_data;
3520         }
3521
3522       do_cleanups (cleanup);
3523     }
3524
3525   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3526     {
3527       offset_type idx = 2 * iter;
3528       const char *name;
3529       offset_type *vec, vec_len, vec_idx;
3530
3531       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3532         continue;
3533
3534       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3535
3536       if (! (*name_matcher) (name, data))
3537         continue;
3538
3539       /* The name was matched, now expand corresponding CUs that were
3540          marked.  */
3541       vec = (offset_type *) (index->constant_pool
3542                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3543       vec_len = MAYBE_SWAP (vec[0]);
3544       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3545         {
3546           struct dwarf2_per_cu_data *per_cu;
3547           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3548           gdb_index_symbol_kind symbol_kind =
3549             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3550           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3551
3552           /* Don't crash on bad data.  */
3553           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3554                            + dwarf2_per_objfile->n_type_units))
3555             continue;
3556
3557           /* Only check the symbol's kind if it has one.
3558              Indices prior to version 7 don't record it.  */
3559           if (index->version >= 7)
3560             {
3561               switch (kind)
3562                 {
3563                 case VARIABLES_DOMAIN:
3564                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3565                     continue;
3566                   break;
3567                 case FUNCTIONS_DOMAIN:
3568                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3569                     continue;
3570                   break;
3571                 case TYPES_DOMAIN:
3572                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3573                     continue;
3574                   break;
3575                 default:
3576                   break;
3577                 }
3578             }
3579
3580           per_cu = dw2_get_cu (cu_index);
3581           if (file_matcher == NULL || per_cu->v.quick->mark)
3582             dw2_instantiate_symtab (per_cu);
3583         }
3584     }
3585 }
3586
3587 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3588    symtab.  */
3589
3590 static struct symtab *
3591 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3592 {
3593   int i;
3594
3595   if (BLOCKVECTOR (symtab) != NULL
3596       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3597     return symtab;
3598
3599   if (symtab->includes == NULL)
3600     return NULL;
3601
3602   for (i = 0; symtab->includes[i]; ++i)
3603     {
3604       struct symtab *s = symtab->includes[i];
3605
3606       s = recursively_find_pc_sect_symtab (s, pc);
3607       if (s != NULL)
3608         return s;
3609     }
3610
3611   return NULL;
3612 }
3613
3614 static struct symtab *
3615 dw2_find_pc_sect_symtab (struct objfile *objfile,
3616                          struct minimal_symbol *msymbol,
3617                          CORE_ADDR pc,
3618                          struct obj_section *section,
3619                          int warn_if_readin)
3620 {
3621   struct dwarf2_per_cu_data *data;
3622   struct symtab *result;
3623
3624   dw2_setup (objfile);
3625
3626   if (!objfile->psymtabs_addrmap)
3627     return NULL;
3628
3629   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3630   if (!data)
3631     return NULL;
3632
3633   if (warn_if_readin && data->v.quick->symtab)
3634     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3635              paddress (get_objfile_arch (objfile), pc));
3636
3637   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3638   gdb_assert (result != NULL);
3639   return result;
3640 }
3641
3642 static void
3643 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3644                           void *data, int need_fullname)
3645 {
3646   int i;
3647   struct cleanup *cleanup;
3648   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3649                                       NULL, xcalloc, xfree);
3650
3651   cleanup = make_cleanup_htab_delete (visited);
3652   dw2_setup (objfile);
3653
3654   dw2_build_type_unit_groups ();
3655
3656   /* We can ignore file names coming from already-expanded CUs.  */
3657   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3658                    + dwarf2_per_objfile->n_type_units); ++i)
3659     {
3660       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3661
3662       if (per_cu->v.quick->symtab)
3663         {
3664           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3665                                         INSERT);
3666
3667           *slot = per_cu->v.quick->file_names;
3668         }
3669     }
3670
3671   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3672                    + dwarf2_per_objfile->n_type_unit_groups); ++i)
3673     {
3674       int j;
3675       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3676       struct quick_file_names *file_data;
3677       void **slot;
3678
3679       /* We only need to look at symtabs not already expanded.  */
3680       if (per_cu->v.quick->symtab)
3681         continue;
3682
3683       file_data = dw2_get_file_names (objfile, per_cu);
3684       if (file_data == NULL)
3685         continue;
3686
3687       slot = htab_find_slot (visited, file_data, INSERT);
3688       if (*slot)
3689         {
3690           /* Already visited.  */
3691           continue;
3692         }
3693       *slot = file_data;
3694
3695       for (j = 0; j < file_data->num_file_names; ++j)
3696         {
3697           const char *this_real_name;
3698
3699           if (need_fullname)
3700             this_real_name = dw2_get_real_path (objfile, file_data, j);
3701           else
3702             this_real_name = NULL;
3703           (*fun) (file_data->file_names[j], this_real_name, data);
3704         }
3705     }
3706
3707   do_cleanups (cleanup);
3708 }
3709
3710 static int
3711 dw2_has_symbols (struct objfile *objfile)
3712 {
3713   return 1;
3714 }
3715
3716 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3717 {
3718   dw2_has_symbols,
3719   dw2_find_last_source_symtab,
3720   dw2_forget_cached_source_info,
3721   dw2_map_symtabs_matching_filename,
3722   dw2_lookup_symbol,
3723   dw2_pre_expand_symtabs_matching,
3724   dw2_print_stats,
3725   dw2_dump,
3726   dw2_relocate,
3727   dw2_expand_symtabs_for_function,
3728   dw2_expand_all_symtabs,
3729   dw2_expand_symtabs_with_filename,
3730   dw2_find_symbol_file,
3731   dw2_map_matching_symbols,
3732   dw2_expand_symtabs_matching,
3733   dw2_find_pc_sect_symtab,
3734   dw2_map_symbol_filenames
3735 };
3736
3737 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3738    file will use psymtabs, or 1 if using the GNU index.  */
3739
3740 int
3741 dwarf2_initialize_objfile (struct objfile *objfile)
3742 {
3743   /* If we're about to read full symbols, don't bother with the
3744      indices.  In this case we also don't care if some other debug
3745      format is making psymtabs, because they are all about to be
3746      expanded anyway.  */
3747   if ((objfile->flags & OBJF_READNOW))
3748     {
3749       int i;
3750
3751       dwarf2_per_objfile->using_index = 1;
3752       create_all_comp_units (objfile);
3753       create_all_type_units (objfile);
3754       dwarf2_per_objfile->quick_file_names_table =
3755         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3756
3757       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3758                        + dwarf2_per_objfile->n_type_units); ++i)
3759         {
3760           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3761
3762           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3763                                             struct dwarf2_per_cu_quick_data);
3764         }
3765
3766       /* Return 1 so that gdb sees the "quick" functions.  However,
3767          these functions will be no-ops because we will have expanded
3768          all symtabs.  */
3769       return 1;
3770     }
3771
3772   if (dwarf2_read_index (objfile))
3773     return 1;
3774
3775   return 0;
3776 }
3777
3778 \f
3779
3780 /* Build a partial symbol table.  */
3781
3782 void
3783 dwarf2_build_psymtabs (struct objfile *objfile)
3784 {
3785   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3786     {
3787       init_psymbol_list (objfile, 1024);
3788     }
3789
3790   dwarf2_build_psymtabs_hard (objfile);
3791 }
3792
3793 /* Return the total length of the CU described by HEADER.  */
3794
3795 static unsigned int
3796 get_cu_length (const struct comp_unit_head *header)
3797 {
3798   return header->initial_length_size + header->length;
3799 }
3800
3801 /* Return TRUE if OFFSET is within CU_HEADER.  */
3802
3803 static inline int
3804 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3805 {
3806   sect_offset bottom = { cu_header->offset.sect_off };
3807   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3808
3809   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3810 }
3811
3812 /* Find the base address of the compilation unit for range lists and
3813    location lists.  It will normally be specified by DW_AT_low_pc.
3814    In DWARF-3 draft 4, the base address could be overridden by
3815    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3816    compilation units with discontinuous ranges.  */
3817
3818 static void
3819 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3820 {
3821   struct attribute *attr;
3822
3823   cu->base_known = 0;
3824   cu->base_address = 0;
3825
3826   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3827   if (attr)
3828     {
3829       cu->base_address = DW_ADDR (attr);
3830       cu->base_known = 1;
3831     }
3832   else
3833     {
3834       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3835       if (attr)
3836         {
3837           cu->base_address = DW_ADDR (attr);
3838           cu->base_known = 1;
3839         }
3840     }
3841 }
3842
3843 /* Read in the comp unit header information from the debug_info at info_ptr.
3844    NOTE: This leaves members offset, first_die_offset to be filled in
3845    by the caller.  */
3846
3847 static gdb_byte *
3848 read_comp_unit_head (struct comp_unit_head *cu_header,
3849                      gdb_byte *info_ptr, bfd *abfd)
3850 {
3851   int signed_addr;
3852   unsigned int bytes_read;
3853
3854   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3855   cu_header->initial_length_size = bytes_read;
3856   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3857   info_ptr += bytes_read;
3858   cu_header->version = read_2_bytes (abfd, info_ptr);
3859   info_ptr += 2;
3860   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3861                                              &bytes_read);
3862   info_ptr += bytes_read;
3863   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3864   info_ptr += 1;
3865   signed_addr = bfd_get_sign_extend_vma (abfd);
3866   if (signed_addr < 0)
3867     internal_error (__FILE__, __LINE__,
3868                     _("read_comp_unit_head: dwarf from non elf file"));
3869   cu_header->signed_addr_p = signed_addr;
3870
3871   return info_ptr;
3872 }
3873
3874 /* Helper function that returns the proper abbrev section for
3875    THIS_CU.  */
3876
3877 static struct dwarf2_section_info *
3878 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3879 {
3880   struct dwarf2_section_info *abbrev;
3881
3882   if (this_cu->is_dwz)
3883     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3884   else
3885     abbrev = &dwarf2_per_objfile->abbrev;
3886
3887   return abbrev;
3888 }
3889
3890 /* Subroutine of read_and_check_comp_unit_head and
3891    read_and_check_type_unit_head to simplify them.
3892    Perform various error checking on the header.  */
3893
3894 static void
3895 error_check_comp_unit_head (struct comp_unit_head *header,
3896                             struct dwarf2_section_info *section,
3897                             struct dwarf2_section_info *abbrev_section)
3898 {
3899   bfd *abfd = section->asection->owner;
3900   const char *filename = bfd_get_filename (abfd);
3901
3902   if (header->version != 2 && header->version != 3 && header->version != 4)
3903     error (_("Dwarf Error: wrong version in compilation unit header "
3904            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3905            filename);
3906
3907   if (header->abbrev_offset.sect_off
3908       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3909     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3910            "(offset 0x%lx + 6) [in module %s]"),
3911            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3912            filename);
3913
3914   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3915      avoid potential 32-bit overflow.  */
3916   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3917       > section->size)
3918     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3919            "(offset 0x%lx + 0) [in module %s]"),
3920            (long) header->length, (long) header->offset.sect_off,
3921            filename);
3922 }
3923
3924 /* Read in a CU/TU header and perform some basic error checking.
3925    The contents of the header are stored in HEADER.
3926    The result is a pointer to the start of the first DIE.  */
3927
3928 static gdb_byte *
3929 read_and_check_comp_unit_head (struct comp_unit_head *header,
3930                                struct dwarf2_section_info *section,
3931                                struct dwarf2_section_info *abbrev_section,
3932                                gdb_byte *info_ptr,
3933                                int is_debug_types_section)
3934 {
3935   gdb_byte *beg_of_comp_unit = info_ptr;
3936   bfd *abfd = section->asection->owner;
3937
3938   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3939
3940   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3941
3942   /* If we're reading a type unit, skip over the signature and
3943      type_offset fields.  */
3944   if (is_debug_types_section)
3945     info_ptr += 8 /*signature*/ + header->offset_size;
3946
3947   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3948
3949   error_check_comp_unit_head (header, section, abbrev_section);
3950
3951   return info_ptr;
3952 }
3953
3954 /* Read in the types comp unit header information from .debug_types entry at
3955    types_ptr.  The result is a pointer to one past the end of the header.  */
3956
3957 static gdb_byte *
3958 read_and_check_type_unit_head (struct comp_unit_head *header,
3959                                struct dwarf2_section_info *section,
3960                                struct dwarf2_section_info *abbrev_section,
3961                                gdb_byte *info_ptr,
3962                                ULONGEST *signature,
3963                                cu_offset *type_offset_in_tu)
3964 {
3965   gdb_byte *beg_of_comp_unit = info_ptr;
3966   bfd *abfd = section->asection->owner;
3967
3968   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3969
3970   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3971
3972   /* If we're reading a type unit, skip over the signature and
3973      type_offset fields.  */
3974   if (signature != NULL)
3975     *signature = read_8_bytes (abfd, info_ptr);
3976   info_ptr += 8;
3977   if (type_offset_in_tu != NULL)
3978     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
3979                                                header->offset_size);
3980   info_ptr += header->offset_size;
3981
3982   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3983
3984   error_check_comp_unit_head (header, section, abbrev_section);
3985
3986   return info_ptr;
3987 }
3988
3989 /* Fetch the abbreviation table offset from a comp or type unit header.  */
3990
3991 static sect_offset
3992 read_abbrev_offset (struct dwarf2_section_info *section,
3993                     sect_offset offset)
3994 {
3995   bfd *abfd = section->asection->owner;
3996   gdb_byte *info_ptr;
3997   unsigned int length, initial_length_size, offset_size;
3998   sect_offset abbrev_offset;
3999
4000   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4001   info_ptr = section->buffer + offset.sect_off;
4002   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4003   offset_size = initial_length_size == 4 ? 4 : 8;
4004   info_ptr += initial_length_size + 2 /*version*/;
4005   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4006   return abbrev_offset;
4007 }
4008
4009 /* Allocate a new partial symtab for file named NAME and mark this new
4010    partial symtab as being an include of PST.  */
4011
4012 static void
4013 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
4014                                struct objfile *objfile)
4015 {
4016   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4017
4018   subpst->section_offsets = pst->section_offsets;
4019   subpst->textlow = 0;
4020   subpst->texthigh = 0;
4021
4022   subpst->dependencies = (struct partial_symtab **)
4023     obstack_alloc (&objfile->objfile_obstack,
4024                    sizeof (struct partial_symtab *));
4025   subpst->dependencies[0] = pst;
4026   subpst->number_of_dependencies = 1;
4027
4028   subpst->globals_offset = 0;
4029   subpst->n_global_syms = 0;
4030   subpst->statics_offset = 0;
4031   subpst->n_static_syms = 0;
4032   subpst->symtab = NULL;
4033   subpst->read_symtab = pst->read_symtab;
4034   subpst->readin = 0;
4035
4036   /* No private part is necessary for include psymtabs.  This property
4037      can be used to differentiate between such include psymtabs and
4038      the regular ones.  */
4039   subpst->read_symtab_private = NULL;
4040 }
4041
4042 /* Read the Line Number Program data and extract the list of files
4043    included by the source file represented by PST.  Build an include
4044    partial symtab for each of these included files.  */
4045
4046 static void
4047 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4048                                struct die_info *die,
4049                                struct partial_symtab *pst)
4050 {
4051   struct line_header *lh = NULL;
4052   struct attribute *attr;
4053
4054   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4055   if (attr)
4056     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4057   if (lh == NULL)
4058     return;  /* No linetable, so no includes.  */
4059
4060   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4061   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4062
4063   free_line_header (lh);
4064 }
4065
4066 static hashval_t
4067 hash_signatured_type (const void *item)
4068 {
4069   const struct signatured_type *sig_type = item;
4070
4071   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4072   return sig_type->signature;
4073 }
4074
4075 static int
4076 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4077 {
4078   const struct signatured_type *lhs = item_lhs;
4079   const struct signatured_type *rhs = item_rhs;
4080
4081   return lhs->signature == rhs->signature;
4082 }
4083
4084 /* Allocate a hash table for signatured types.  */
4085
4086 static htab_t
4087 allocate_signatured_type_table (struct objfile *objfile)
4088 {
4089   return htab_create_alloc_ex (41,
4090                                hash_signatured_type,
4091                                eq_signatured_type,
4092                                NULL,
4093                                &objfile->objfile_obstack,
4094                                hashtab_obstack_allocate,
4095                                dummy_obstack_deallocate);
4096 }
4097
4098 /* A helper function to add a signatured type CU to a table.  */
4099
4100 static int
4101 add_signatured_type_cu_to_table (void **slot, void *datum)
4102 {
4103   struct signatured_type *sigt = *slot;
4104   struct signatured_type ***datap = datum;
4105
4106   **datap = sigt;
4107   ++*datap;
4108
4109   return 1;
4110 }
4111
4112 /* Create the hash table of all entries in the .debug_types section.
4113    DWO_FILE is a pointer to the DWO file for .debug_types.dwo,
4114    NULL otherwise.
4115    Note: This function processes DWO files only, not DWP files.
4116    The result is a pointer to the hash table or NULL if there are
4117    no types.  */
4118
4119 static htab_t
4120 create_debug_types_hash_table (struct dwo_file *dwo_file,
4121                                VEC (dwarf2_section_info_def) *types)
4122 {
4123   struct objfile *objfile = dwarf2_per_objfile->objfile;
4124   htab_t types_htab = NULL;
4125   int ix;
4126   struct dwarf2_section_info *section;
4127   struct dwarf2_section_info *abbrev_section;
4128
4129   if (VEC_empty (dwarf2_section_info_def, types))
4130     return NULL;
4131
4132   abbrev_section = (dwo_file != NULL
4133                     ? &dwo_file->sections.abbrev
4134                     : &dwarf2_per_objfile->abbrev);
4135
4136   if (dwarf2_read_debug)
4137     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4138                         dwo_file ? ".dwo" : "",
4139                         bfd_get_filename (abbrev_section->asection->owner));
4140
4141   for (ix = 0;
4142        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4143        ++ix)
4144     {
4145       bfd *abfd;
4146       gdb_byte *info_ptr, *end_ptr;
4147       struct dwarf2_section_info *abbrev_section;
4148
4149       dwarf2_read_section (objfile, section);
4150       info_ptr = section->buffer;
4151
4152       if (info_ptr == NULL)
4153         continue;
4154
4155       /* We can't set abfd until now because the section may be empty or
4156          not present, in which case section->asection will be NULL.  */
4157       abfd = section->asection->owner;
4158
4159       if (dwo_file)
4160         abbrev_section = &dwo_file->sections.abbrev;
4161       else
4162         abbrev_section = &dwarf2_per_objfile->abbrev;
4163
4164       if (types_htab == NULL)
4165         {
4166           if (dwo_file)
4167             types_htab = allocate_dwo_unit_table (objfile);
4168           else
4169             types_htab = allocate_signatured_type_table (objfile);
4170         }
4171
4172       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4173          because we don't need to read any dies: the signature is in the
4174          header.  */
4175
4176       end_ptr = info_ptr + section->size;
4177       while (info_ptr < end_ptr)
4178         {
4179           sect_offset offset;
4180           cu_offset type_offset_in_tu;
4181           ULONGEST signature;
4182           struct signatured_type *sig_type;
4183           struct dwo_unit *dwo_tu;
4184           void **slot;
4185           gdb_byte *ptr = info_ptr;
4186           struct comp_unit_head header;
4187           unsigned int length;
4188
4189           offset.sect_off = ptr - section->buffer;
4190
4191           /* We need to read the type's signature in order to build the hash
4192              table, but we don't need anything else just yet.  */
4193
4194           ptr = read_and_check_type_unit_head (&header, section,
4195                                                abbrev_section, ptr,
4196                                                &signature, &type_offset_in_tu);
4197
4198           length = get_cu_length (&header);
4199
4200           /* Skip dummy type units.  */
4201           if (ptr >= info_ptr + length
4202               || peek_abbrev_code (abfd, ptr) == 0)
4203             {
4204               info_ptr += length;
4205               continue;
4206             }
4207
4208           if (dwo_file)
4209             {
4210               sig_type = NULL;
4211               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4212                                        struct dwo_unit);
4213               dwo_tu->dwo_file = dwo_file;
4214               dwo_tu->signature = signature;
4215               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4216               dwo_tu->info_or_types_section = section;
4217               dwo_tu->offset = offset;
4218               dwo_tu->length = length;
4219             }
4220           else
4221             {
4222               /* N.B.: type_offset is not usable if this type uses a DWO file.
4223                  The real type_offset is in the DWO file.  */
4224               dwo_tu = NULL;
4225               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4226                                          struct signatured_type);
4227               sig_type->signature = signature;
4228               sig_type->type_offset_in_tu = type_offset_in_tu;
4229               sig_type->per_cu.objfile = objfile;
4230               sig_type->per_cu.is_debug_types = 1;
4231               sig_type->per_cu.info_or_types_section = section;
4232               sig_type->per_cu.offset = offset;
4233               sig_type->per_cu.length = length;
4234             }
4235
4236           slot = htab_find_slot (types_htab,
4237                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4238                                  INSERT);
4239           gdb_assert (slot != NULL);
4240           if (*slot != NULL)
4241             {
4242               sect_offset dup_offset;
4243
4244               if (dwo_file)
4245                 {
4246                   const struct dwo_unit *dup_tu = *slot;
4247
4248                   dup_offset = dup_tu->offset;
4249                 }
4250               else
4251                 {
4252                   const struct signatured_type *dup_tu = *slot;
4253
4254                   dup_offset = dup_tu->per_cu.offset;
4255                 }
4256
4257               complaint (&symfile_complaints,
4258                          _("debug type entry at offset 0x%x is duplicate to the "
4259                            "entry at offset 0x%x, signature 0x%s"),
4260                          offset.sect_off, dup_offset.sect_off,
4261                          phex (signature, sizeof (signature)));
4262             }
4263           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4264
4265           if (dwarf2_read_debug)
4266             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4267                                 offset.sect_off,
4268                                 phex (signature, sizeof (signature)));
4269
4270           info_ptr += length;
4271         }
4272     }
4273
4274   return types_htab;
4275 }
4276
4277 /* Create the hash table of all entries in the .debug_types section,
4278    and initialize all_type_units.
4279    The result is zero if there is an error (e.g. missing .debug_types section),
4280    otherwise non-zero.  */
4281
4282 static int
4283 create_all_type_units (struct objfile *objfile)
4284 {
4285   htab_t types_htab;
4286   struct signatured_type **iter;
4287
4288   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4289   if (types_htab == NULL)
4290     {
4291       dwarf2_per_objfile->signatured_types = NULL;
4292       return 0;
4293     }
4294
4295   dwarf2_per_objfile->signatured_types = types_htab;
4296
4297   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4298   dwarf2_per_objfile->all_type_units
4299     = obstack_alloc (&objfile->objfile_obstack,
4300                      dwarf2_per_objfile->n_type_units
4301                      * sizeof (struct signatured_type *));
4302   iter = &dwarf2_per_objfile->all_type_units[0];
4303   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4304   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4305               == dwarf2_per_objfile->n_type_units);
4306
4307   return 1;
4308 }
4309
4310 /* Lookup a signature based type for DW_FORM_ref_sig8.
4311    Returns NULL if signature SIG is not present in the table.  */
4312
4313 static struct signatured_type *
4314 lookup_signatured_type (ULONGEST sig)
4315 {
4316   struct signatured_type find_entry, *entry;
4317
4318   if (dwarf2_per_objfile->signatured_types == NULL)
4319     {
4320       complaint (&symfile_complaints,
4321                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4322       return NULL;
4323     }
4324
4325   find_entry.signature = sig;
4326   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4327   return entry;
4328 }
4329 \f
4330 /* Low level DIE reading support.  */
4331
4332 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4333
4334 static void
4335 init_cu_die_reader (struct die_reader_specs *reader,
4336                     struct dwarf2_cu *cu,
4337                     struct dwarf2_section_info *section,
4338                     struct dwo_file *dwo_file)
4339 {
4340   gdb_assert (section->readin && section->buffer != NULL);
4341   reader->abfd = section->asection->owner;
4342   reader->cu = cu;
4343   reader->dwo_file = dwo_file;
4344   reader->die_section = section;
4345   reader->buffer = section->buffer;
4346   reader->buffer_end = section->buffer + section->size;
4347 }
4348
4349 /* Initialize a CU (or TU) and read its DIEs.
4350    If the CU defers to a DWO file, read the DWO file as well.
4351
4352    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4353    Otherwise the table specified in the comp unit header is read in and used.
4354    This is an optimization for when we already have the abbrev table.
4355
4356    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4357    Otherwise, a new CU is allocated with xmalloc.
4358
4359    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4360    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4361
4362    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4363    linker) then DIE_READER_FUNC will not get called.  */
4364
4365 static void
4366 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4367                          struct abbrev_table *abbrev_table,
4368                          int use_existing_cu, int keep,
4369                          die_reader_func_ftype *die_reader_func,
4370                          void *data)
4371 {
4372   struct objfile *objfile = dwarf2_per_objfile->objfile;
4373   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4374   bfd *abfd = section->asection->owner;
4375   struct dwarf2_cu *cu;
4376   gdb_byte *begin_info_ptr, *info_ptr;
4377   struct die_reader_specs reader;
4378   struct die_info *comp_unit_die;
4379   int has_children;
4380   struct attribute *attr;
4381   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4382   struct signatured_type *sig_type = NULL;
4383   struct dwarf2_section_info *abbrev_section;
4384   /* Non-zero if CU currently points to a DWO file and we need to
4385      reread it.  When this happens we need to reread the skeleton die
4386      before we can reread the DWO file.  */
4387   int rereading_dwo_cu = 0;
4388
4389   if (dwarf2_die_debug)
4390     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4391                         this_cu->is_debug_types ? "type" : "comp",
4392                         this_cu->offset.sect_off);
4393
4394   if (use_existing_cu)
4395     gdb_assert (keep);
4396
4397   cleanups = make_cleanup (null_cleanup, NULL);
4398
4399   /* This is cheap if the section is already read in.  */
4400   dwarf2_read_section (objfile, section);
4401
4402   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4403
4404   abbrev_section = get_abbrev_section_for_cu (this_cu);
4405
4406   if (use_existing_cu && this_cu->cu != NULL)
4407     {
4408       cu = this_cu->cu;
4409
4410       /* If this CU is from a DWO file we need to start over, we need to
4411          refetch the attributes from the skeleton CU.
4412          This could be optimized by retrieving those attributes from when we
4413          were here the first time: the previous comp_unit_die was stored in
4414          comp_unit_obstack.  But there's no data yet that we need this
4415          optimization.  */
4416       if (cu->dwo_unit != NULL)
4417         rereading_dwo_cu = 1;
4418     }
4419   else
4420     {
4421       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4422       gdb_assert (this_cu->cu == NULL);
4423
4424       cu = xmalloc (sizeof (*cu));
4425       init_one_comp_unit (cu, this_cu);
4426
4427       /* If an error occurs while loading, release our storage.  */
4428       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4429     }
4430
4431   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4432     {
4433       /* We already have the header, there's no need to read it in again.  */
4434       info_ptr += cu->header.first_die_offset.cu_off;
4435     }
4436   else
4437     {
4438       if (this_cu->is_debug_types)
4439         {
4440           ULONGEST signature;
4441           cu_offset type_offset_in_tu;
4442
4443           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4444                                                     abbrev_section, info_ptr,
4445                                                     &signature,
4446                                                     &type_offset_in_tu);
4447
4448           /* Since per_cu is the first member of struct signatured_type,
4449              we can go from a pointer to one to a pointer to the other.  */
4450           sig_type = (struct signatured_type *) this_cu;
4451           gdb_assert (sig_type->signature == signature);
4452           gdb_assert (sig_type->type_offset_in_tu.cu_off
4453                       == type_offset_in_tu.cu_off);
4454           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4455
4456           /* LENGTH has not been set yet for type units if we're
4457              using .gdb_index.  */
4458           this_cu->length = get_cu_length (&cu->header);
4459
4460           /* Establish the type offset that can be used to lookup the type.  */
4461           sig_type->type_offset_in_section.sect_off =
4462             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4463         }
4464       else
4465         {
4466           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4467                                                     abbrev_section,
4468                                                     info_ptr, 0);
4469
4470           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4471           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4472         }
4473     }
4474
4475   /* Skip dummy compilation units.  */
4476   if (info_ptr >= begin_info_ptr + this_cu->length
4477       || peek_abbrev_code (abfd, info_ptr) == 0)
4478     {
4479       do_cleanups (cleanups);
4480       return;
4481     }
4482
4483   /* If we don't have them yet, read the abbrevs for this compilation unit.
4484      And if we need to read them now, make sure they're freed when we're
4485      done.  Note that it's important that if the CU had an abbrev table
4486      on entry we don't free it when we're done: Somewhere up the call stack
4487      it may be in use.  */
4488   if (abbrev_table != NULL)
4489     {
4490       gdb_assert (cu->abbrev_table == NULL);
4491       gdb_assert (cu->header.abbrev_offset.sect_off
4492                   == abbrev_table->offset.sect_off);
4493       cu->abbrev_table = abbrev_table;
4494     }
4495   else if (cu->abbrev_table == NULL)
4496     {
4497       dwarf2_read_abbrevs (cu, abbrev_section);
4498       make_cleanup (dwarf2_free_abbrev_table, cu);
4499     }
4500   else if (rereading_dwo_cu)
4501     {
4502       dwarf2_free_abbrev_table (cu);
4503       dwarf2_read_abbrevs (cu, abbrev_section);
4504     }
4505
4506   /* Read the top level CU/TU die.  */
4507   init_cu_die_reader (&reader, cu, section, NULL);
4508   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4509
4510   /* If we have a DWO stub, process it and then read in the DWO file.
4511      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4512      a DWO CU, that this test will fail.  */
4513   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4514   if (attr)
4515     {
4516       char *dwo_name = DW_STRING (attr);
4517       const char *comp_dir_string;
4518       struct dwo_unit *dwo_unit;
4519       ULONGEST signature; /* Or dwo_id.  */
4520       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4521       int i,num_extra_attrs;
4522       struct dwarf2_section_info *dwo_abbrev_section;
4523
4524       if (has_children)
4525         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4526                  " has children (offset 0x%x) [in module %s]"),
4527                this_cu->offset.sect_off, bfd_get_filename (abfd));
4528
4529       /* These attributes aren't processed until later:
4530          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4531          However, the attribute is found in the stub which we won't have later.
4532          In order to not impose this complication on the rest of the code,
4533          we read them here and copy them to the DWO CU/TU die.  */
4534
4535       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4536          DWO file.  */
4537       stmt_list = NULL;
4538       if (! this_cu->is_debug_types)
4539         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4540       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4541       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4542       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4543       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4544
4545       /* There should be a DW_AT_addr_base attribute here (if needed).
4546          We need the value before we can process DW_FORM_GNU_addr_index.  */
4547       cu->addr_base = 0;
4548       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4549       if (attr)
4550         cu->addr_base = DW_UNSND (attr);
4551
4552       /* There should be a DW_AT_ranges_base attribute here (if needed).
4553          We need the value before we can process DW_AT_ranges.  */
4554       cu->ranges_base = 0;
4555       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4556       if (attr)
4557         cu->ranges_base = DW_UNSND (attr);
4558
4559       if (this_cu->is_debug_types)
4560         {
4561           gdb_assert (sig_type != NULL);
4562           signature = sig_type->signature;
4563         }
4564       else
4565         {
4566           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4567           if (! attr)
4568             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4569                    dwo_name);
4570           signature = DW_UNSND (attr);
4571         }
4572
4573       /* We may need the comp_dir in order to find the DWO file.  */
4574       comp_dir_string = NULL;
4575       if (comp_dir)
4576         comp_dir_string = DW_STRING (comp_dir);
4577
4578       if (this_cu->is_debug_types)
4579         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4580       else
4581         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4582                                          signature);
4583
4584       if (dwo_unit == NULL)
4585         {
4586           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4587                    " with ID %s [in module %s]"),
4588                  this_cu->offset.sect_off,
4589                  phex (signature, sizeof (signature)),
4590                  objfile->name);
4591         }
4592
4593       /* Set up for reading the DWO CU/TU.  */
4594       cu->dwo_unit = dwo_unit;
4595       section = dwo_unit->info_or_types_section;
4596       dwarf2_read_section (objfile, section);
4597       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4598       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4599       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4600
4601       if (this_cu->is_debug_types)
4602         {
4603           ULONGEST signature;
4604           cu_offset type_offset_in_tu;
4605
4606           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4607                                                     dwo_abbrev_section,
4608                                                     info_ptr,
4609                                                     &signature,
4610                                                     &type_offset_in_tu);
4611           gdb_assert (sig_type->signature == signature);
4612           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4613           /* For DWOs coming from DWP files, we don't know the CU length
4614              nor the type's offset in the TU until now.  */
4615           dwo_unit->length = get_cu_length (&cu->header);
4616           dwo_unit->type_offset_in_tu = type_offset_in_tu;
4617
4618           /* Establish the type offset that can be used to lookup the type.
4619              For DWO files, we don't know it until now.  */
4620           sig_type->type_offset_in_section.sect_off =
4621             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4622         }
4623       else
4624         {
4625           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4626                                                     dwo_abbrev_section,
4627                                                     info_ptr, 0);
4628           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4629           /* For DWOs coming from DWP files, we don't know the CU length
4630              until now.  */
4631           dwo_unit->length = get_cu_length (&cu->header);
4632         }
4633
4634       /* Discard the original CU's abbrev table, and read the DWO's.  */
4635       if (abbrev_table == NULL)
4636         {
4637           dwarf2_free_abbrev_table (cu);
4638           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4639         }
4640       else
4641         {
4642           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4643           make_cleanup (dwarf2_free_abbrev_table, cu);
4644         }
4645
4646       /* Read in the die, but leave space to copy over the attributes
4647          from the stub.  This has the benefit of simplifying the rest of
4648          the code - all the real work is done here.  */
4649       num_extra_attrs = ((stmt_list != NULL)
4650                          + (low_pc != NULL)
4651                          + (high_pc != NULL)
4652                          + (ranges != NULL)
4653                          + (comp_dir != NULL));
4654       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4655                                   &has_children, num_extra_attrs);
4656
4657       /* Copy over the attributes from the stub to the DWO die.  */
4658       i = comp_unit_die->num_attrs;
4659       if (stmt_list != NULL)
4660         comp_unit_die->attrs[i++] = *stmt_list;
4661       if (low_pc != NULL)
4662         comp_unit_die->attrs[i++] = *low_pc;
4663       if (high_pc != NULL)
4664         comp_unit_die->attrs[i++] = *high_pc;
4665       if (ranges != NULL)
4666         comp_unit_die->attrs[i++] = *ranges;
4667       if (comp_dir != NULL)
4668         comp_unit_die->attrs[i++] = *comp_dir;
4669       comp_unit_die->num_attrs += num_extra_attrs;
4670
4671       /* Skip dummy compilation units.  */
4672       if (info_ptr >= begin_info_ptr + dwo_unit->length
4673           || peek_abbrev_code (abfd, info_ptr) == 0)
4674         {
4675           do_cleanups (cleanups);
4676           return;
4677         }
4678     }
4679
4680   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4681
4682   if (free_cu_cleanup != NULL)
4683     {
4684       if (keep)
4685         {
4686           /* We've successfully allocated this compilation unit.  Let our
4687              caller clean it up when finished with it.  */
4688           discard_cleanups (free_cu_cleanup);
4689
4690           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4691              So we have to manually free the abbrev table.  */
4692           dwarf2_free_abbrev_table (cu);
4693
4694           /* Link this CU into read_in_chain.  */
4695           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4696           dwarf2_per_objfile->read_in_chain = this_cu;
4697         }
4698       else
4699         do_cleanups (free_cu_cleanup);
4700     }
4701
4702   do_cleanups (cleanups);
4703 }
4704
4705 /* Read CU/TU THIS_CU in section SECTION,
4706    but do not follow DW_AT_GNU_dwo_name if present.
4707    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4708    to have already done the lookup to find the DWO/DWP file).
4709
4710    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4711    THIS_CU->is_debug_types, but nothing else.
4712
4713    We fill in THIS_CU->length.
4714
4715    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4716    linker) then DIE_READER_FUNC will not get called.
4717
4718    THIS_CU->cu is always freed when done.
4719    This is done in order to not leave THIS_CU->cu in a state where we have
4720    to care whether it refers to the "main" CU or the DWO CU.  */
4721
4722 static void
4723 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4724                                    struct dwarf2_section_info *abbrev_section,
4725                                    struct dwo_file *dwo_file,
4726                                    die_reader_func_ftype *die_reader_func,
4727                                    void *data)
4728 {
4729   struct objfile *objfile = dwarf2_per_objfile->objfile;
4730   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4731   bfd *abfd = section->asection->owner;
4732   struct dwarf2_cu cu;
4733   gdb_byte *begin_info_ptr, *info_ptr;
4734   struct die_reader_specs reader;
4735   struct cleanup *cleanups;
4736   struct die_info *comp_unit_die;
4737   int has_children;
4738
4739   if (dwarf2_die_debug)
4740     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4741                         this_cu->is_debug_types ? "type" : "comp",
4742                         this_cu->offset.sect_off);
4743
4744   gdb_assert (this_cu->cu == NULL);
4745
4746   /* This is cheap if the section is already read in.  */
4747   dwarf2_read_section (objfile, section);
4748
4749   init_one_comp_unit (&cu, this_cu);
4750
4751   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4752
4753   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4754   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4755                                             abbrev_section, info_ptr,
4756                                             this_cu->is_debug_types);
4757
4758   this_cu->length = get_cu_length (&cu.header);
4759
4760   /* Skip dummy compilation units.  */
4761   if (info_ptr >= begin_info_ptr + this_cu->length
4762       || peek_abbrev_code (abfd, info_ptr) == 0)
4763     {
4764       do_cleanups (cleanups);
4765       return;
4766     }
4767
4768   dwarf2_read_abbrevs (&cu, abbrev_section);
4769   make_cleanup (dwarf2_free_abbrev_table, &cu);
4770
4771   init_cu_die_reader (&reader, &cu, section, dwo_file);
4772   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4773
4774   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4775
4776   do_cleanups (cleanups);
4777 }
4778
4779 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4780    does not lookup the specified DWO file.
4781    This cannot be used to read DWO files.
4782
4783    THIS_CU->cu is always freed when done.
4784    This is done in order to not leave THIS_CU->cu in a state where we have
4785    to care whether it refers to the "main" CU or the DWO CU.
4786    We can revisit this if the data shows there's a performance issue.  */
4787
4788 static void
4789 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4790                                 die_reader_func_ftype *die_reader_func,
4791                                 void *data)
4792 {
4793   init_cutu_and_read_dies_no_follow (this_cu,
4794                                      get_abbrev_section_for_cu (this_cu),
4795                                      NULL,
4796                                      die_reader_func, data);
4797 }
4798
4799 /* Create a psymtab named NAME and assign it to PER_CU.
4800
4801    The caller must fill in the following details:
4802    dirname, textlow, texthigh.  */
4803
4804 static struct partial_symtab *
4805 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4806 {
4807   struct objfile *objfile = per_cu->objfile;
4808   struct partial_symtab *pst;
4809
4810   pst = start_psymtab_common (objfile, objfile->section_offsets,
4811                               name, 0,
4812                               objfile->global_psymbols.next,
4813                               objfile->static_psymbols.next);
4814
4815   pst->psymtabs_addrmap_supported = 1;
4816
4817   /* This is the glue that links PST into GDB's symbol API.  */
4818   pst->read_symtab_private = per_cu;
4819   pst->read_symtab = dwarf2_psymtab_to_symtab;
4820   per_cu->v.psymtab = pst;
4821
4822   return pst;
4823 }
4824
4825 /* die_reader_func for process_psymtab_comp_unit.  */
4826
4827 static void
4828 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4829                                   gdb_byte *info_ptr,
4830                                   struct die_info *comp_unit_die,
4831                                   int has_children,
4832                                   void *data)
4833 {
4834   struct dwarf2_cu *cu = reader->cu;
4835   struct objfile *objfile = cu->objfile;
4836   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4837   struct attribute *attr;
4838   CORE_ADDR baseaddr;
4839   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4840   struct partial_symtab *pst;
4841   int has_pc_info;
4842   const char *filename;
4843   int *want_partial_unit_ptr = data;
4844
4845   if (comp_unit_die->tag == DW_TAG_partial_unit
4846       && (want_partial_unit_ptr == NULL
4847           || !*want_partial_unit_ptr))
4848     return;
4849
4850   gdb_assert (! per_cu->is_debug_types);
4851
4852   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4853
4854   cu->list_in_scope = &file_symbols;
4855
4856   /* Allocate a new partial symbol table structure.  */
4857   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4858   if (attr == NULL || !DW_STRING (attr))
4859     filename = "";
4860   else
4861     filename = DW_STRING (attr);
4862
4863   pst = create_partial_symtab (per_cu, filename);
4864
4865   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4866   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4867   if (attr != NULL)
4868     pst->dirname = DW_STRING (attr);
4869
4870   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4871
4872   dwarf2_find_base_address (comp_unit_die, cu);
4873
4874   /* Possibly set the default values of LOWPC and HIGHPC from
4875      `DW_AT_ranges'.  */
4876   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4877                                       &best_highpc, cu, pst);
4878   if (has_pc_info == 1 && best_lowpc < best_highpc)
4879     /* Store the contiguous range if it is not empty; it can be empty for
4880        CUs with no code.  */
4881     addrmap_set_empty (objfile->psymtabs_addrmap,
4882                        best_lowpc + baseaddr,
4883                        best_highpc + baseaddr - 1, pst);
4884
4885   /* Check if comp unit has_children.
4886      If so, read the rest of the partial symbols from this comp unit.
4887      If not, there's no more debug_info for this comp unit.  */
4888   if (has_children)
4889     {
4890       struct partial_die_info *first_die;
4891       CORE_ADDR lowpc, highpc;
4892
4893       lowpc = ((CORE_ADDR) -1);
4894       highpc = ((CORE_ADDR) 0);
4895
4896       first_die = load_partial_dies (reader, info_ptr, 1);
4897
4898       scan_partial_symbols (first_die, &lowpc, &highpc,
4899                             ! has_pc_info, cu);
4900
4901       /* If we didn't find a lowpc, set it to highpc to avoid
4902          complaints from `maint check'.  */
4903       if (lowpc == ((CORE_ADDR) -1))
4904         lowpc = highpc;
4905
4906       /* If the compilation unit didn't have an explicit address range,
4907          then use the information extracted from its child dies.  */
4908       if (! has_pc_info)
4909         {
4910           best_lowpc = lowpc;
4911           best_highpc = highpc;
4912         }
4913     }
4914   pst->textlow = best_lowpc + baseaddr;
4915   pst->texthigh = best_highpc + baseaddr;
4916
4917   pst->n_global_syms = objfile->global_psymbols.next -
4918     (objfile->global_psymbols.list + pst->globals_offset);
4919   pst->n_static_syms = objfile->static_psymbols.next -
4920     (objfile->static_psymbols.list + pst->statics_offset);
4921   sort_pst_symbols (pst);
4922
4923   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs))
4924     {
4925       int i;
4926       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs);
4927       struct dwarf2_per_cu_data *iter;
4928
4929       /* Fill in 'dependencies' here; we fill in 'users' in a
4930          post-pass.  */
4931       pst->number_of_dependencies = len;
4932       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4933                                          len * sizeof (struct symtab *));
4934       for (i = 0;
4935            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs,
4936                         i, iter);
4937            ++i)
4938         pst->dependencies[i] = iter->v.psymtab;
4939
4940       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs);
4941     }
4942
4943   /* Get the list of files included in the current compilation unit,
4944      and build a psymtab for each of them.  */
4945   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4946
4947   if (dwarf2_read_debug)
4948     {
4949       struct gdbarch *gdbarch = get_objfile_arch (objfile);
4950
4951       fprintf_unfiltered (gdb_stdlog,
4952                           "Psymtab for %s unit @0x%x: %s - %s"
4953                           ", %d global, %d static syms\n",
4954                           per_cu->is_debug_types ? "type" : "comp",
4955                           per_cu->offset.sect_off,
4956                           paddress (gdbarch, pst->textlow),
4957                           paddress (gdbarch, pst->texthigh),
4958                           pst->n_global_syms, pst->n_static_syms);
4959     }
4960 }
4961
4962 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4963    Process compilation unit THIS_CU for a psymtab.  */
4964
4965 static void
4966 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
4967                            int want_partial_unit)
4968 {
4969   /* If this compilation unit was already read in, free the
4970      cached copy in order to read it in again.  This is
4971      necessary because we skipped some symbols when we first
4972      read in the compilation unit (see load_partial_dies).
4973      This problem could be avoided, but the benefit is unclear.  */
4974   if (this_cu->cu != NULL)
4975     free_one_cached_comp_unit (this_cu);
4976
4977   gdb_assert (! this_cu->is_debug_types);
4978   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
4979                            process_psymtab_comp_unit_reader,
4980                            &want_partial_unit);
4981
4982   /* Age out any secondary CUs.  */
4983   age_cached_comp_units ();
4984 }
4985
4986 static hashval_t
4987 hash_type_unit_group (const void *item)
4988 {
4989   const struct type_unit_group *tu_group = item;
4990
4991   return hash_stmt_list_entry (&tu_group->hash);
4992 }
4993
4994 static int
4995 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
4996 {
4997   const struct type_unit_group *lhs = item_lhs;
4998   const struct type_unit_group *rhs = item_rhs;
4999
5000   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5001 }
5002
5003 /* Allocate a hash table for type unit groups.  */
5004
5005 static htab_t
5006 allocate_type_unit_groups_table (void)
5007 {
5008   return htab_create_alloc_ex (3,
5009                                hash_type_unit_group,
5010                                eq_type_unit_group,
5011                                NULL,
5012                                &dwarf2_per_objfile->objfile->objfile_obstack,
5013                                hashtab_obstack_allocate,
5014                                dummy_obstack_deallocate);
5015 }
5016
5017 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5018    partial symtabs.  We combine several TUs per psymtab to not let the size
5019    of any one psymtab grow too big.  */
5020 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5021 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5022
5023 /* Helper routine for get_type_unit_group.
5024    Create the type_unit_group object used to hold one or more TUs.  */
5025
5026 static struct type_unit_group *
5027 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5028 {
5029   struct objfile *objfile = dwarf2_per_objfile->objfile;
5030   struct dwarf2_per_cu_data *per_cu;
5031   struct type_unit_group *tu_group;
5032
5033   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5034                              struct type_unit_group);
5035   per_cu = &tu_group->per_cu;
5036   per_cu->objfile = objfile;
5037   per_cu->is_debug_types = 1;
5038   per_cu->s.type_unit_group = tu_group;
5039
5040   if (dwarf2_per_objfile->using_index)
5041     {
5042       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5043                                         struct dwarf2_per_cu_quick_data);
5044       tu_group->t.first_tu = cu->per_cu;
5045     }
5046   else
5047     {
5048       unsigned int line_offset = line_offset_struct.sect_off;
5049       struct partial_symtab *pst;
5050       char *name;
5051
5052       /* Give the symtab a useful name for debug purposes.  */
5053       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5054         name = xstrprintf ("<type_units_%d>",
5055                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5056       else
5057         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5058
5059       pst = create_partial_symtab (per_cu, name);
5060       pst->anonymous = 1;
5061
5062       xfree (name);
5063     }
5064
5065   tu_group->hash.dwo_unit = cu->dwo_unit;
5066   tu_group->hash.line_offset = line_offset_struct;
5067
5068   return tu_group;
5069 }
5070
5071 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5072    STMT_LIST is a DW_AT_stmt_list attribute.  */
5073
5074 static struct type_unit_group *
5075 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5076 {
5077   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5078   struct type_unit_group *tu_group;
5079   void **slot;
5080   unsigned int line_offset;
5081   struct type_unit_group type_unit_group_for_lookup;
5082
5083   if (dwarf2_per_objfile->type_unit_groups == NULL)
5084     {
5085       dwarf2_per_objfile->type_unit_groups =
5086         allocate_type_unit_groups_table ();
5087     }
5088
5089   /* Do we need to create a new group, or can we use an existing one?  */
5090
5091   if (stmt_list)
5092     {
5093       line_offset = DW_UNSND (stmt_list);
5094       ++tu_stats->nr_symtab_sharers;
5095     }
5096   else
5097     {
5098       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5099          We can do various things here like create one group per TU or
5100          spread them over multiple groups to split up the expansion work.
5101          To avoid worst case scenarios (too many groups or too large groups)
5102          we, umm, group them in bunches.  */
5103       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5104                      | (tu_stats->nr_stmt_less_type_units
5105                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5106       ++tu_stats->nr_stmt_less_type_units;
5107     }
5108
5109   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5110   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5111   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5112                          &type_unit_group_for_lookup, INSERT);
5113   if (*slot != NULL)
5114     {
5115       tu_group = *slot;
5116       gdb_assert (tu_group != NULL);
5117     }
5118   else
5119     {
5120       sect_offset line_offset_struct;
5121
5122       line_offset_struct.sect_off = line_offset;
5123       tu_group = create_type_unit_group (cu, line_offset_struct);
5124       *slot = tu_group;
5125       ++tu_stats->nr_symtabs;
5126     }
5127
5128   return tu_group;
5129 }
5130
5131 /* Struct used to sort TUs by their abbreviation table offset.  */
5132
5133 struct tu_abbrev_offset
5134 {
5135   struct signatured_type *sig_type;
5136   sect_offset abbrev_offset;
5137 };
5138
5139 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5140
5141 static int
5142 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5143 {
5144   const struct tu_abbrev_offset * const *a = ap;
5145   const struct tu_abbrev_offset * const *b = bp;
5146   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5147   unsigned int boff = (*b)->abbrev_offset.sect_off;
5148
5149   return (aoff > boff) - (aoff < boff);
5150 }
5151
5152 /* A helper function to add a type_unit_group to a table.  */
5153
5154 static int
5155 add_type_unit_group_to_table (void **slot, void *datum)
5156 {
5157   struct type_unit_group *tu_group = *slot;
5158   struct type_unit_group ***datap = datum;
5159
5160   **datap = tu_group;
5161   ++*datap;
5162
5163   return 1;
5164 }
5165
5166 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5167    each one passing FUNC,DATA.
5168
5169    The efficiency is because we sort TUs by the abbrev table they use and
5170    only read each abbrev table once.  In one program there are 200K TUs
5171    sharing 8K abbrev tables.
5172
5173    The main purpose of this function is to support building the
5174    dwarf2_per_objfile->type_unit_groups table.
5175    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5176    can collapse the search space by grouping them by stmt_list.
5177    The savings can be significant, in the same program from above the 200K TUs
5178    share 8K stmt_list tables.
5179
5180    FUNC is expected to call get_type_unit_group, which will create the
5181    struct type_unit_group if necessary and add it to
5182    dwarf2_per_objfile->type_unit_groups.  */
5183
5184 static void
5185 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5186 {
5187   struct objfile *objfile = dwarf2_per_objfile->objfile;
5188   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5189   struct cleanup *cleanups;
5190   struct abbrev_table *abbrev_table;
5191   sect_offset abbrev_offset;
5192   struct tu_abbrev_offset *sorted_by_abbrev;
5193   struct type_unit_group **iter;
5194   int i;
5195
5196   /* It's up to the caller to not call us multiple times.  */
5197   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5198
5199   if (dwarf2_per_objfile->n_type_units == 0)
5200     return;
5201
5202   /* TUs typically share abbrev tables, and there can be way more TUs than
5203      abbrev tables.  Sort by abbrev table to reduce the number of times we
5204      read each abbrev table in.
5205      Alternatives are to punt or to maintain a cache of abbrev tables.
5206      This is simpler and efficient enough for now.
5207
5208      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5209      symtab to use).  Typically TUs with the same abbrev offset have the same
5210      stmt_list value too so in practice this should work well.
5211
5212      The basic algorithm here is:
5213
5214       sort TUs by abbrev table
5215       for each TU with same abbrev table:
5216         read abbrev table if first user
5217         read TU top level DIE
5218           [IWBN if DWO skeletons had DW_AT_stmt_list]
5219         call FUNC  */
5220
5221   if (dwarf2_read_debug)
5222     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5223
5224   /* Sort in a separate table to maintain the order of all_type_units
5225      for .gdb_index: TU indices directly index all_type_units.  */
5226   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5227                               dwarf2_per_objfile->n_type_units);
5228   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5229     {
5230       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5231
5232       sorted_by_abbrev[i].sig_type = sig_type;
5233       sorted_by_abbrev[i].abbrev_offset =
5234         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
5235                             sig_type->per_cu.offset);
5236     }
5237   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5238   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5239          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5240
5241   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5242      called any number of times, so we don't reset tu_stats here.  */
5243
5244   abbrev_offset.sect_off = ~(unsigned) 0;
5245   abbrev_table = NULL;
5246   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5247
5248   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5249     {
5250       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5251
5252       /* Switch to the next abbrev table if necessary.  */
5253       if (abbrev_table == NULL
5254           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5255         {
5256           if (abbrev_table != NULL)
5257             {
5258               abbrev_table_free (abbrev_table);
5259               /* Reset to NULL in case abbrev_table_read_table throws
5260                  an error: abbrev_table_free_cleanup will get called.  */
5261               abbrev_table = NULL;
5262             }
5263           abbrev_offset = tu->abbrev_offset;
5264           abbrev_table =
5265             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5266                                      abbrev_offset);
5267           ++tu_stats->nr_uniq_abbrev_tables;
5268         }
5269
5270       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5271                                func, data);
5272     }
5273
5274   /* Create a vector of pointers to primary type units to make it easy to
5275      iterate over them and CUs.  See dw2_get_primary_cu.  */
5276   dwarf2_per_objfile->n_type_unit_groups =
5277     htab_elements (dwarf2_per_objfile->type_unit_groups);
5278   dwarf2_per_objfile->all_type_unit_groups =
5279     obstack_alloc (&objfile->objfile_obstack,
5280                    dwarf2_per_objfile->n_type_unit_groups
5281                    * sizeof (struct type_unit_group *));
5282   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5283   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5284                           add_type_unit_group_to_table, &iter);
5285   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5286               == dwarf2_per_objfile->n_type_unit_groups);
5287
5288   do_cleanups (cleanups);
5289
5290   if (dwarf2_read_debug)
5291     {
5292       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5293       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5294                           dwarf2_per_objfile->n_type_units);
5295       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5296                           tu_stats->nr_uniq_abbrev_tables);
5297       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5298                           tu_stats->nr_symtabs);
5299       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5300                           tu_stats->nr_symtab_sharers);
5301       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5302                           tu_stats->nr_stmt_less_type_units);
5303     }
5304 }
5305
5306 /* Reader function for build_type_psymtabs.  */
5307
5308 static void
5309 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5310                             gdb_byte *info_ptr,
5311                             struct die_info *type_unit_die,
5312                             int has_children,
5313                             void *data)
5314 {
5315   struct objfile *objfile = dwarf2_per_objfile->objfile;
5316   struct dwarf2_cu *cu = reader->cu;
5317   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5318   struct type_unit_group *tu_group;
5319   struct attribute *attr;
5320   struct partial_die_info *first_die;
5321   CORE_ADDR lowpc, highpc;
5322   struct partial_symtab *pst;
5323
5324   gdb_assert (data == NULL);
5325
5326   if (! has_children)
5327     return;
5328
5329   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5330   tu_group = get_type_unit_group (cu, attr);
5331
5332   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5333
5334   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5335   cu->list_in_scope = &file_symbols;
5336   pst = create_partial_symtab (per_cu, "");
5337   pst->anonymous = 1;
5338
5339   first_die = load_partial_dies (reader, info_ptr, 1);
5340
5341   lowpc = (CORE_ADDR) -1;
5342   highpc = (CORE_ADDR) 0;
5343   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5344
5345   pst->n_global_syms = objfile->global_psymbols.next -
5346     (objfile->global_psymbols.list + pst->globals_offset);
5347   pst->n_static_syms = objfile->static_psymbols.next -
5348     (objfile->static_psymbols.list + pst->statics_offset);
5349   sort_pst_symbols (pst);
5350 }
5351
5352 /* Traversal function for build_type_psymtabs.  */
5353
5354 static int
5355 build_type_psymtab_dependencies (void **slot, void *info)
5356 {
5357   struct objfile *objfile = dwarf2_per_objfile->objfile;
5358   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5359   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5360   struct partial_symtab *pst = per_cu->v.psymtab;
5361   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5362   struct dwarf2_per_cu_data *iter;
5363   int i;
5364
5365   gdb_assert (len > 0);
5366
5367   pst->number_of_dependencies = len;
5368   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5369                                      len * sizeof (struct psymtab *));
5370   for (i = 0;
5371        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5372        ++i)
5373     {
5374       pst->dependencies[i] = iter->v.psymtab;
5375       iter->s.type_unit_group = tu_group;
5376     }
5377
5378   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5379
5380   return 1;
5381 }
5382
5383 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5384    Build partial symbol tables for the .debug_types comp-units.  */
5385
5386 static void
5387 build_type_psymtabs (struct objfile *objfile)
5388 {
5389   if (! create_all_type_units (objfile))
5390     return;
5391
5392   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5393
5394   /* Now that all TUs have been processed we can fill in the dependencies.  */
5395   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5396                           build_type_psymtab_dependencies, NULL);
5397 }
5398
5399 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5400
5401 static void
5402 psymtabs_addrmap_cleanup (void *o)
5403 {
5404   struct objfile *objfile = o;
5405
5406   objfile->psymtabs_addrmap = NULL;
5407 }
5408
5409 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5410
5411 static void
5412 set_partial_user (struct objfile *objfile)
5413 {
5414   int i;
5415
5416   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5417     {
5418       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5419       struct partial_symtab *pst = per_cu->v.psymtab;
5420       int j;
5421
5422       if (pst == NULL)
5423         continue;
5424
5425       for (j = 0; j < pst->number_of_dependencies; ++j)
5426         {
5427           /* Set the 'user' field only if it is not already set.  */
5428           if (pst->dependencies[j]->user == NULL)
5429             pst->dependencies[j]->user = pst;
5430         }
5431     }
5432 }
5433
5434 /* Build the partial symbol table by doing a quick pass through the
5435    .debug_info and .debug_abbrev sections.  */
5436
5437 static void
5438 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5439 {
5440   struct cleanup *back_to, *addrmap_cleanup;
5441   struct obstack temp_obstack;
5442   int i;
5443
5444   if (dwarf2_read_debug)
5445     {
5446       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5447                           objfile->name);
5448     }
5449
5450   dwarf2_per_objfile->reading_partial_symbols = 1;
5451
5452   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5453
5454   /* Any cached compilation units will be linked by the per-objfile
5455      read_in_chain.  Make sure to free them when we're done.  */
5456   back_to = make_cleanup (free_cached_comp_units, NULL);
5457
5458   build_type_psymtabs (objfile);
5459
5460   create_all_comp_units (objfile);
5461
5462   /* Create a temporary address map on a temporary obstack.  We later
5463      copy this to the final obstack.  */
5464   obstack_init (&temp_obstack);
5465   make_cleanup_obstack_free (&temp_obstack);
5466   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5467   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5468
5469   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5470     {
5471       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5472
5473       process_psymtab_comp_unit (per_cu, 0);
5474     }
5475
5476   set_partial_user (objfile);
5477
5478   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5479                                                     &objfile->objfile_obstack);
5480   discard_cleanups (addrmap_cleanup);
5481
5482   do_cleanups (back_to);
5483
5484   if (dwarf2_read_debug)
5485     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5486                         objfile->name);
5487 }
5488
5489 /* die_reader_func for load_partial_comp_unit.  */
5490
5491 static void
5492 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5493                                gdb_byte *info_ptr,
5494                                struct die_info *comp_unit_die,
5495                                int has_children,
5496                                void *data)
5497 {
5498   struct dwarf2_cu *cu = reader->cu;
5499
5500   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5501
5502   /* Check if comp unit has_children.
5503      If so, read the rest of the partial symbols from this comp unit.
5504      If not, there's no more debug_info for this comp unit.  */
5505   if (has_children)
5506     load_partial_dies (reader, info_ptr, 0);
5507 }
5508
5509 /* Load the partial DIEs for a secondary CU into memory.
5510    This is also used when rereading a primary CU with load_all_dies.  */
5511
5512 static void
5513 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5514 {
5515   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5516                            load_partial_comp_unit_reader, NULL);
5517 }
5518
5519 static void
5520 read_comp_units_from_section (struct objfile *objfile,
5521                               struct dwarf2_section_info *section,
5522                               unsigned int is_dwz,
5523                               int *n_allocated,
5524                               int *n_comp_units,
5525                               struct dwarf2_per_cu_data ***all_comp_units)
5526 {
5527   gdb_byte *info_ptr;
5528   bfd *abfd = section->asection->owner;
5529
5530   dwarf2_read_section (objfile, section);
5531
5532   info_ptr = section->buffer;
5533
5534   while (info_ptr < section->buffer + section->size)
5535     {
5536       unsigned int length, initial_length_size;
5537       struct dwarf2_per_cu_data *this_cu;
5538       sect_offset offset;
5539
5540       offset.sect_off = info_ptr - section->buffer;
5541
5542       /* Read just enough information to find out where the next
5543          compilation unit is.  */
5544       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5545
5546       /* Save the compilation unit for later lookup.  */
5547       this_cu = obstack_alloc (&objfile->objfile_obstack,
5548                                sizeof (struct dwarf2_per_cu_data));
5549       memset (this_cu, 0, sizeof (*this_cu));
5550       this_cu->offset = offset;
5551       this_cu->length = length + initial_length_size;
5552       this_cu->is_dwz = is_dwz;
5553       this_cu->objfile = objfile;
5554       this_cu->info_or_types_section = section;
5555
5556       if (*n_comp_units == *n_allocated)
5557         {
5558           *n_allocated *= 2;
5559           *all_comp_units = xrealloc (*all_comp_units,
5560                                       *n_allocated
5561                                       * sizeof (struct dwarf2_per_cu_data *));
5562         }
5563       (*all_comp_units)[*n_comp_units] = this_cu;
5564       ++*n_comp_units;
5565
5566       info_ptr = info_ptr + this_cu->length;
5567     }
5568 }
5569
5570 /* Create a list of all compilation units in OBJFILE.
5571    This is only done for -readnow and building partial symtabs.  */
5572
5573 static void
5574 create_all_comp_units (struct objfile *objfile)
5575 {
5576   int n_allocated;
5577   int n_comp_units;
5578   struct dwarf2_per_cu_data **all_comp_units;
5579
5580   n_comp_units = 0;
5581   n_allocated = 10;
5582   all_comp_units = xmalloc (n_allocated
5583                             * sizeof (struct dwarf2_per_cu_data *));
5584
5585   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5586                                 &n_allocated, &n_comp_units, &all_comp_units);
5587
5588   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5589     {
5590       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5591
5592       read_comp_units_from_section (objfile, &dwz->info, 1,
5593                                     &n_allocated, &n_comp_units,
5594                                     &all_comp_units);
5595     }
5596
5597   dwarf2_per_objfile->all_comp_units
5598     = obstack_alloc (&objfile->objfile_obstack,
5599                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5600   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5601           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5602   xfree (all_comp_units);
5603   dwarf2_per_objfile->n_comp_units = n_comp_units;
5604 }
5605
5606 /* Process all loaded DIEs for compilation unit CU, starting at
5607    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5608    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5609    DW_AT_ranges).  If NEED_PC is set, then this function will set
5610    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5611    and record the covered ranges in the addrmap.  */
5612
5613 static void
5614 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5615                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5616 {
5617   struct partial_die_info *pdi;
5618
5619   /* Now, march along the PDI's, descending into ones which have
5620      interesting children but skipping the children of the other ones,
5621      until we reach the end of the compilation unit.  */
5622
5623   pdi = first_die;
5624
5625   while (pdi != NULL)
5626     {
5627       fixup_partial_die (pdi, cu);
5628
5629       /* Anonymous namespaces or modules have no name but have interesting
5630          children, so we need to look at them.  Ditto for anonymous
5631          enums.  */
5632
5633       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5634           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5635           || pdi->tag == DW_TAG_imported_unit)
5636         {
5637           switch (pdi->tag)
5638             {
5639             case DW_TAG_subprogram:
5640               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5641               break;
5642             case DW_TAG_constant:
5643             case DW_TAG_variable:
5644             case DW_TAG_typedef:
5645             case DW_TAG_union_type:
5646               if (!pdi->is_declaration)
5647                 {
5648                   add_partial_symbol (pdi, cu);
5649                 }
5650               break;
5651             case DW_TAG_class_type:
5652             case DW_TAG_interface_type:
5653             case DW_TAG_structure_type:
5654               if (!pdi->is_declaration)
5655                 {
5656                   add_partial_symbol (pdi, cu);
5657                 }
5658               break;
5659             case DW_TAG_enumeration_type:
5660               if (!pdi->is_declaration)
5661                 add_partial_enumeration (pdi, cu);
5662               break;
5663             case DW_TAG_base_type:
5664             case DW_TAG_subrange_type:
5665               /* File scope base type definitions are added to the partial
5666                  symbol table.  */
5667               add_partial_symbol (pdi, cu);
5668               break;
5669             case DW_TAG_namespace:
5670               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5671               break;
5672             case DW_TAG_module:
5673               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5674               break;
5675             case DW_TAG_imported_unit:
5676               {
5677                 struct dwarf2_per_cu_data *per_cu;
5678
5679                 /* For now we don't handle imported units in type units.  */
5680                 if (cu->per_cu->is_debug_types)
5681                   {
5682                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5683                              " supported in type units [in module %s]"),
5684                            cu->objfile->name);
5685                   }
5686
5687                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5688                                                            pdi->is_dwz,
5689                                                            cu->objfile);
5690
5691                 /* Go read the partial unit, if needed.  */
5692                 if (per_cu->v.psymtab == NULL)
5693                   process_psymtab_comp_unit (per_cu, 1);
5694
5695                 VEC_safe_push (dwarf2_per_cu_ptr,
5696                                cu->per_cu->s.imported_symtabs, per_cu);
5697               }
5698               break;
5699             default:
5700               break;
5701             }
5702         }
5703
5704       /* If the die has a sibling, skip to the sibling.  */
5705
5706       pdi = pdi->die_sibling;
5707     }
5708 }
5709
5710 /* Functions used to compute the fully scoped name of a partial DIE.
5711
5712    Normally, this is simple.  For C++, the parent DIE's fully scoped
5713    name is concatenated with "::" and the partial DIE's name.  For
5714    Java, the same thing occurs except that "." is used instead of "::".
5715    Enumerators are an exception; they use the scope of their parent
5716    enumeration type, i.e. the name of the enumeration type is not
5717    prepended to the enumerator.
5718
5719    There are two complexities.  One is DW_AT_specification; in this
5720    case "parent" means the parent of the target of the specification,
5721    instead of the direct parent of the DIE.  The other is compilers
5722    which do not emit DW_TAG_namespace; in this case we try to guess
5723    the fully qualified name of structure types from their members'
5724    linkage names.  This must be done using the DIE's children rather
5725    than the children of any DW_AT_specification target.  We only need
5726    to do this for structures at the top level, i.e. if the target of
5727    any DW_AT_specification (if any; otherwise the DIE itself) does not
5728    have a parent.  */
5729
5730 /* Compute the scope prefix associated with PDI's parent, in
5731    compilation unit CU.  The result will be allocated on CU's
5732    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5733    field.  NULL is returned if no prefix is necessary.  */
5734 static char *
5735 partial_die_parent_scope (struct partial_die_info *pdi,
5736                           struct dwarf2_cu *cu)
5737 {
5738   char *grandparent_scope;
5739   struct partial_die_info *parent, *real_pdi;
5740
5741   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5742      then this means the parent of the specification DIE.  */
5743
5744   real_pdi = pdi;
5745   while (real_pdi->has_specification)
5746     real_pdi = find_partial_die (real_pdi->spec_offset,
5747                                  real_pdi->spec_is_dwz, cu);
5748
5749   parent = real_pdi->die_parent;
5750   if (parent == NULL)
5751     return NULL;
5752
5753   if (parent->scope_set)
5754     return parent->scope;
5755
5756   fixup_partial_die (parent, cu);
5757
5758   grandparent_scope = partial_die_parent_scope (parent, cu);
5759
5760   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5761      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5762      Work around this problem here.  */
5763   if (cu->language == language_cplus
5764       && parent->tag == DW_TAG_namespace
5765       && strcmp (parent->name, "::") == 0
5766       && grandparent_scope == NULL)
5767     {
5768       parent->scope = NULL;
5769       parent->scope_set = 1;
5770       return NULL;
5771     }
5772
5773   if (pdi->tag == DW_TAG_enumerator)
5774     /* Enumerators should not get the name of the enumeration as a prefix.  */
5775     parent->scope = grandparent_scope;
5776   else if (parent->tag == DW_TAG_namespace
5777       || parent->tag == DW_TAG_module
5778       || parent->tag == DW_TAG_structure_type
5779       || parent->tag == DW_TAG_class_type
5780       || parent->tag == DW_TAG_interface_type
5781       || parent->tag == DW_TAG_union_type
5782       || parent->tag == DW_TAG_enumeration_type)
5783     {
5784       if (grandparent_scope == NULL)
5785         parent->scope = parent->name;
5786       else
5787         parent->scope = typename_concat (&cu->comp_unit_obstack,
5788                                          grandparent_scope,
5789                                          parent->name, 0, cu);
5790     }
5791   else
5792     {
5793       /* FIXME drow/2004-04-01: What should we be doing with
5794          function-local names?  For partial symbols, we should probably be
5795          ignoring them.  */
5796       complaint (&symfile_complaints,
5797                  _("unhandled containing DIE tag %d for DIE at %d"),
5798                  parent->tag, pdi->offset.sect_off);
5799       parent->scope = grandparent_scope;
5800     }
5801
5802   parent->scope_set = 1;
5803   return parent->scope;
5804 }
5805
5806 /* Return the fully scoped name associated with PDI, from compilation unit
5807    CU.  The result will be allocated with malloc.  */
5808
5809 static char *
5810 partial_die_full_name (struct partial_die_info *pdi,
5811                        struct dwarf2_cu *cu)
5812 {
5813   char *parent_scope;
5814
5815   /* If this is a template instantiation, we can not work out the
5816      template arguments from partial DIEs.  So, unfortunately, we have
5817      to go through the full DIEs.  At least any work we do building
5818      types here will be reused if full symbols are loaded later.  */
5819   if (pdi->has_template_arguments)
5820     {
5821       fixup_partial_die (pdi, cu);
5822
5823       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5824         {
5825           struct die_info *die;
5826           struct attribute attr;
5827           struct dwarf2_cu *ref_cu = cu;
5828
5829           /* DW_FORM_ref_addr is using section offset.  */
5830           attr.name = 0;
5831           attr.form = DW_FORM_ref_addr;
5832           attr.u.unsnd = pdi->offset.sect_off;
5833           die = follow_die_ref (NULL, &attr, &ref_cu);
5834
5835           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5836         }
5837     }
5838
5839   parent_scope = partial_die_parent_scope (pdi, cu);
5840   if (parent_scope == NULL)
5841     return NULL;
5842   else
5843     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5844 }
5845
5846 static void
5847 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5848 {
5849   struct objfile *objfile = cu->objfile;
5850   CORE_ADDR addr = 0;
5851   char *actual_name = NULL;
5852   CORE_ADDR baseaddr;
5853   int built_actual_name = 0;
5854
5855   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5856
5857   actual_name = partial_die_full_name (pdi, cu);
5858   if (actual_name)
5859     built_actual_name = 1;
5860
5861   if (actual_name == NULL)
5862     actual_name = pdi->name;
5863
5864   switch (pdi->tag)
5865     {
5866     case DW_TAG_subprogram:
5867       if (pdi->is_external || cu->language == language_ada)
5868         {
5869           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5870              of the global scope.  But in Ada, we want to be able to access
5871              nested procedures globally.  So all Ada subprograms are stored
5872              in the global scope.  */
5873           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5874              mst_text, objfile); */
5875           add_psymbol_to_list (actual_name, strlen (actual_name),
5876                                built_actual_name,
5877                                VAR_DOMAIN, LOC_BLOCK,
5878                                &objfile->global_psymbols,
5879                                0, pdi->lowpc + baseaddr,
5880                                cu->language, objfile);
5881         }
5882       else
5883         {
5884           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5885              mst_file_text, objfile); */
5886           add_psymbol_to_list (actual_name, strlen (actual_name),
5887                                built_actual_name,
5888                                VAR_DOMAIN, LOC_BLOCK,
5889                                &objfile->static_psymbols,
5890                                0, pdi->lowpc + baseaddr,
5891                                cu->language, objfile);
5892         }
5893       break;
5894     case DW_TAG_constant:
5895       {
5896         struct psymbol_allocation_list *list;
5897
5898         if (pdi->is_external)
5899           list = &objfile->global_psymbols;
5900         else
5901           list = &objfile->static_psymbols;
5902         add_psymbol_to_list (actual_name, strlen (actual_name),
5903                              built_actual_name, VAR_DOMAIN, LOC_STATIC,
5904                              list, 0, 0, cu->language, objfile);
5905       }
5906       break;
5907     case DW_TAG_variable:
5908       if (pdi->d.locdesc)
5909         addr = decode_locdesc (pdi->d.locdesc, cu);
5910
5911       if (pdi->d.locdesc
5912           && addr == 0
5913           && !dwarf2_per_objfile->has_section_at_zero)
5914         {
5915           /* A global or static variable may also have been stripped
5916              out by the linker if unused, in which case its address
5917              will be nullified; do not add such variables into partial
5918              symbol table then.  */
5919         }
5920       else if (pdi->is_external)
5921         {
5922           /* Global Variable.
5923              Don't enter into the minimal symbol tables as there is
5924              a minimal symbol table entry from the ELF symbols already.
5925              Enter into partial symbol table if it has a location
5926              descriptor or a type.
5927              If the location descriptor is missing, new_symbol will create
5928              a LOC_UNRESOLVED symbol, the address of the variable will then
5929              be determined from the minimal symbol table whenever the variable
5930              is referenced.
5931              The address for the partial symbol table entry is not
5932              used by GDB, but it comes in handy for debugging partial symbol
5933              table building.  */
5934
5935           if (pdi->d.locdesc || pdi->has_type)
5936             add_psymbol_to_list (actual_name, strlen (actual_name),
5937                                  built_actual_name,
5938                                  VAR_DOMAIN, LOC_STATIC,
5939                                  &objfile->global_psymbols,
5940                                  0, addr + baseaddr,
5941                                  cu->language, objfile);
5942         }
5943       else
5944         {
5945           /* Static Variable.  Skip symbols without location descriptors.  */
5946           if (pdi->d.locdesc == NULL)
5947             {
5948               if (built_actual_name)
5949                 xfree (actual_name);
5950               return;
5951             }
5952           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
5953              mst_file_data, objfile); */
5954           add_psymbol_to_list (actual_name, strlen (actual_name),
5955                                built_actual_name,
5956                                VAR_DOMAIN, LOC_STATIC,
5957                                &objfile->static_psymbols,
5958                                0, addr + baseaddr,
5959                                cu->language, objfile);
5960         }
5961       break;
5962     case DW_TAG_typedef:
5963     case DW_TAG_base_type:
5964     case DW_TAG_subrange_type:
5965       add_psymbol_to_list (actual_name, strlen (actual_name),
5966                            built_actual_name,
5967                            VAR_DOMAIN, LOC_TYPEDEF,
5968                            &objfile->static_psymbols,
5969                            0, (CORE_ADDR) 0, cu->language, objfile);
5970       break;
5971     case DW_TAG_namespace:
5972       add_psymbol_to_list (actual_name, strlen (actual_name),
5973                            built_actual_name,
5974                            VAR_DOMAIN, LOC_TYPEDEF,
5975                            &objfile->global_psymbols,
5976                            0, (CORE_ADDR) 0, cu->language, objfile);
5977       break;
5978     case DW_TAG_class_type:
5979     case DW_TAG_interface_type:
5980     case DW_TAG_structure_type:
5981     case DW_TAG_union_type:
5982     case DW_TAG_enumeration_type:
5983       /* Skip external references.  The DWARF standard says in the section
5984          about "Structure, Union, and Class Type Entries": "An incomplete
5985          structure, union or class type is represented by a structure,
5986          union or class entry that does not have a byte size attribute
5987          and that has a DW_AT_declaration attribute."  */
5988       if (!pdi->has_byte_size && pdi->is_declaration)
5989         {
5990           if (built_actual_name)
5991             xfree (actual_name);
5992           return;
5993         }
5994
5995       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
5996          static vs. global.  */
5997       add_psymbol_to_list (actual_name, strlen (actual_name),
5998                            built_actual_name,
5999                            STRUCT_DOMAIN, LOC_TYPEDEF,
6000                            (cu->language == language_cplus
6001                             || cu->language == language_java)
6002                            ? &objfile->global_psymbols
6003                            : &objfile->static_psymbols,
6004                            0, (CORE_ADDR) 0, cu->language, objfile);
6005
6006       break;
6007     case DW_TAG_enumerator:
6008       add_psymbol_to_list (actual_name, strlen (actual_name),
6009                            built_actual_name,
6010                            VAR_DOMAIN, LOC_CONST,
6011                            (cu->language == language_cplus
6012                             || cu->language == language_java)
6013                            ? &objfile->global_psymbols
6014                            : &objfile->static_psymbols,
6015                            0, (CORE_ADDR) 0, cu->language, objfile);
6016       break;
6017     default:
6018       break;
6019     }
6020
6021   if (built_actual_name)
6022     xfree (actual_name);
6023 }
6024
6025 /* Read a partial die corresponding to a namespace; also, add a symbol
6026    corresponding to that namespace to the symbol table.  NAMESPACE is
6027    the name of the enclosing namespace.  */
6028
6029 static void
6030 add_partial_namespace (struct partial_die_info *pdi,
6031                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6032                        int need_pc, struct dwarf2_cu *cu)
6033 {
6034   /* Add a symbol for the namespace.  */
6035
6036   add_partial_symbol (pdi, cu);
6037
6038   /* Now scan partial symbols in that namespace.  */
6039
6040   if (pdi->has_children)
6041     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6042 }
6043
6044 /* Read a partial die corresponding to a Fortran module.  */
6045
6046 static void
6047 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6048                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6049 {
6050   /* Now scan partial symbols in that module.  */
6051
6052   if (pdi->has_children)
6053     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6054 }
6055
6056 /* Read a partial die corresponding to a subprogram and create a partial
6057    symbol for that subprogram.  When the CU language allows it, this
6058    routine also defines a partial symbol for each nested subprogram
6059    that this subprogram contains.
6060
6061    DIE my also be a lexical block, in which case we simply search
6062    recursively for suprograms defined inside that lexical block.
6063    Again, this is only performed when the CU language allows this
6064    type of definitions.  */
6065
6066 static void
6067 add_partial_subprogram (struct partial_die_info *pdi,
6068                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6069                         int need_pc, struct dwarf2_cu *cu)
6070 {
6071   if (pdi->tag == DW_TAG_subprogram)
6072     {
6073       if (pdi->has_pc_info)
6074         {
6075           if (pdi->lowpc < *lowpc)
6076             *lowpc = pdi->lowpc;
6077           if (pdi->highpc > *highpc)
6078             *highpc = pdi->highpc;
6079           if (need_pc)
6080             {
6081               CORE_ADDR baseaddr;
6082               struct objfile *objfile = cu->objfile;
6083
6084               baseaddr = ANOFFSET (objfile->section_offsets,
6085                                    SECT_OFF_TEXT (objfile));
6086               addrmap_set_empty (objfile->psymtabs_addrmap,
6087                                  pdi->lowpc + baseaddr,
6088                                  pdi->highpc - 1 + baseaddr,
6089                                  cu->per_cu->v.psymtab);
6090             }
6091         }
6092
6093       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6094         {
6095           if (!pdi->is_declaration)
6096             /* Ignore subprogram DIEs that do not have a name, they are
6097                illegal.  Do not emit a complaint at this point, we will
6098                do so when we convert this psymtab into a symtab.  */
6099             if (pdi->name)
6100               add_partial_symbol (pdi, cu);
6101         }
6102     }
6103
6104   if (! pdi->has_children)
6105     return;
6106
6107   if (cu->language == language_ada)
6108     {
6109       pdi = pdi->die_child;
6110       while (pdi != NULL)
6111         {
6112           fixup_partial_die (pdi, cu);
6113           if (pdi->tag == DW_TAG_subprogram
6114               || pdi->tag == DW_TAG_lexical_block)
6115             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6116           pdi = pdi->die_sibling;
6117         }
6118     }
6119 }
6120
6121 /* Read a partial die corresponding to an enumeration type.  */
6122
6123 static void
6124 add_partial_enumeration (struct partial_die_info *enum_pdi,
6125                          struct dwarf2_cu *cu)
6126 {
6127   struct partial_die_info *pdi;
6128
6129   if (enum_pdi->name != NULL)
6130     add_partial_symbol (enum_pdi, cu);
6131
6132   pdi = enum_pdi->die_child;
6133   while (pdi)
6134     {
6135       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6136         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6137       else
6138         add_partial_symbol (pdi, cu);
6139       pdi = pdi->die_sibling;
6140     }
6141 }
6142
6143 /* Return the initial uleb128 in the die at INFO_PTR.  */
6144
6145 static unsigned int
6146 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
6147 {
6148   unsigned int bytes_read;
6149
6150   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6151 }
6152
6153 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6154    Return the corresponding abbrev, or NULL if the number is zero (indicating
6155    an empty DIE).  In either case *BYTES_READ will be set to the length of
6156    the initial number.  */
6157
6158 static struct abbrev_info *
6159 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
6160                  struct dwarf2_cu *cu)
6161 {
6162   bfd *abfd = cu->objfile->obfd;
6163   unsigned int abbrev_number;
6164   struct abbrev_info *abbrev;
6165
6166   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6167
6168   if (abbrev_number == 0)
6169     return NULL;
6170
6171   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6172   if (!abbrev)
6173     {
6174       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6175              abbrev_number, bfd_get_filename (abfd));
6176     }
6177
6178   return abbrev;
6179 }
6180
6181 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6182    Returns a pointer to the end of a series of DIEs, terminated by an empty
6183    DIE.  Any children of the skipped DIEs will also be skipped.  */
6184
6185 static gdb_byte *
6186 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
6187 {
6188   struct dwarf2_cu *cu = reader->cu;
6189   struct abbrev_info *abbrev;
6190   unsigned int bytes_read;
6191
6192   while (1)
6193     {
6194       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6195       if (abbrev == NULL)
6196         return info_ptr + bytes_read;
6197       else
6198         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6199     }
6200 }
6201
6202 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6203    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6204    abbrev corresponding to that skipped uleb128 should be passed in
6205    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6206    children.  */
6207
6208 static gdb_byte *
6209 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
6210               struct abbrev_info *abbrev)
6211 {
6212   unsigned int bytes_read;
6213   struct attribute attr;
6214   bfd *abfd = reader->abfd;
6215   struct dwarf2_cu *cu = reader->cu;
6216   gdb_byte *buffer = reader->buffer;
6217   const gdb_byte *buffer_end = reader->buffer_end;
6218   gdb_byte *start_info_ptr = info_ptr;
6219   unsigned int form, i;
6220
6221   for (i = 0; i < abbrev->num_attrs; i++)
6222     {
6223       /* The only abbrev we care about is DW_AT_sibling.  */
6224       if (abbrev->attrs[i].name == DW_AT_sibling)
6225         {
6226           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6227           if (attr.form == DW_FORM_ref_addr)
6228             complaint (&symfile_complaints,
6229                        _("ignoring absolute DW_AT_sibling"));
6230           else
6231             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6232         }
6233
6234       /* If it isn't DW_AT_sibling, skip this attribute.  */
6235       form = abbrev->attrs[i].form;
6236     skip_attribute:
6237       switch (form)
6238         {
6239         case DW_FORM_ref_addr:
6240           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6241              and later it is offset sized.  */
6242           if (cu->header.version == 2)
6243             info_ptr += cu->header.addr_size;
6244           else
6245             info_ptr += cu->header.offset_size;
6246           break;
6247         case DW_FORM_GNU_ref_alt:
6248           info_ptr += cu->header.offset_size;
6249           break;
6250         case DW_FORM_addr:
6251           info_ptr += cu->header.addr_size;
6252           break;
6253         case DW_FORM_data1:
6254         case DW_FORM_ref1:
6255         case DW_FORM_flag:
6256           info_ptr += 1;
6257           break;
6258         case DW_FORM_flag_present:
6259           break;
6260         case DW_FORM_data2:
6261         case DW_FORM_ref2:
6262           info_ptr += 2;
6263           break;
6264         case DW_FORM_data4:
6265         case DW_FORM_ref4:
6266           info_ptr += 4;
6267           break;
6268         case DW_FORM_data8:
6269         case DW_FORM_ref8:
6270         case DW_FORM_ref_sig8:
6271           info_ptr += 8;
6272           break;
6273         case DW_FORM_string:
6274           read_direct_string (abfd, info_ptr, &bytes_read);
6275           info_ptr += bytes_read;
6276           break;
6277         case DW_FORM_sec_offset:
6278         case DW_FORM_strp:
6279         case DW_FORM_GNU_strp_alt:
6280           info_ptr += cu->header.offset_size;
6281           break;
6282         case DW_FORM_exprloc:
6283         case DW_FORM_block:
6284           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6285           info_ptr += bytes_read;
6286           break;
6287         case DW_FORM_block1:
6288           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6289           break;
6290         case DW_FORM_block2:
6291           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6292           break;
6293         case DW_FORM_block4:
6294           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6295           break;
6296         case DW_FORM_sdata:
6297         case DW_FORM_udata:
6298         case DW_FORM_ref_udata:
6299         case DW_FORM_GNU_addr_index:
6300         case DW_FORM_GNU_str_index:
6301           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6302           break;
6303         case DW_FORM_indirect:
6304           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6305           info_ptr += bytes_read;
6306           /* We need to continue parsing from here, so just go back to
6307              the top.  */
6308           goto skip_attribute;
6309
6310         default:
6311           error (_("Dwarf Error: Cannot handle %s "
6312                    "in DWARF reader [in module %s]"),
6313                  dwarf_form_name (form),
6314                  bfd_get_filename (abfd));
6315         }
6316     }
6317
6318   if (abbrev->has_children)
6319     return skip_children (reader, info_ptr);
6320   else
6321     return info_ptr;
6322 }
6323
6324 /* Locate ORIG_PDI's sibling.
6325    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6326
6327 static gdb_byte *
6328 locate_pdi_sibling (const struct die_reader_specs *reader,
6329                     struct partial_die_info *orig_pdi,
6330                     gdb_byte *info_ptr)
6331 {
6332   /* Do we know the sibling already?  */
6333
6334   if (orig_pdi->sibling)
6335     return orig_pdi->sibling;
6336
6337   /* Are there any children to deal with?  */
6338
6339   if (!orig_pdi->has_children)
6340     return info_ptr;
6341
6342   /* Skip the children the long way.  */
6343
6344   return skip_children (reader, info_ptr);
6345 }
6346
6347 /* Expand this partial symbol table into a full symbol table.  */
6348
6349 static void
6350 dwarf2_psymtab_to_symtab (struct partial_symtab *pst)
6351 {
6352   if (pst != NULL)
6353     {
6354       if (pst->readin)
6355         {
6356           warning (_("bug: psymtab for %s is already read in."),
6357                    pst->filename);
6358         }
6359       else
6360         {
6361           if (info_verbose)
6362             {
6363               printf_filtered (_("Reading in symbols for %s..."),
6364                                pst->filename);
6365               gdb_flush (gdb_stdout);
6366             }
6367
6368           /* Restore our global data.  */
6369           dwarf2_per_objfile = objfile_data (pst->objfile,
6370                                              dwarf2_objfile_data_key);
6371
6372           /* If this psymtab is constructed from a debug-only objfile, the
6373              has_section_at_zero flag will not necessarily be correct.  We
6374              can get the correct value for this flag by looking at the data
6375              associated with the (presumably stripped) associated objfile.  */
6376           if (pst->objfile->separate_debug_objfile_backlink)
6377             {
6378               struct dwarf2_per_objfile *dpo_backlink
6379                 = objfile_data (pst->objfile->separate_debug_objfile_backlink,
6380                                 dwarf2_objfile_data_key);
6381
6382               dwarf2_per_objfile->has_section_at_zero
6383                 = dpo_backlink->has_section_at_zero;
6384             }
6385
6386           dwarf2_per_objfile->reading_partial_symbols = 0;
6387
6388           psymtab_to_symtab_1 (pst);
6389
6390           /* Finish up the debug error message.  */
6391           if (info_verbose)
6392             printf_filtered (_("done.\n"));
6393         }
6394     }
6395
6396   process_cu_includes ();
6397 }
6398 \f
6399 /* Reading in full CUs.  */
6400
6401 /* Add PER_CU to the queue.  */
6402
6403 static void
6404 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6405                  enum language pretend_language)
6406 {
6407   struct dwarf2_queue_item *item;
6408
6409   per_cu->queued = 1;
6410   item = xmalloc (sizeof (*item));
6411   item->per_cu = per_cu;
6412   item->pretend_language = pretend_language;
6413   item->next = NULL;
6414
6415   if (dwarf2_queue == NULL)
6416     dwarf2_queue = item;
6417   else
6418     dwarf2_queue_tail->next = item;
6419
6420   dwarf2_queue_tail = item;
6421 }
6422
6423 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6424    unit and add it to our queue.
6425    The result is non-zero if PER_CU was queued, otherwise the result is zero
6426    meaning either PER_CU is already queued or it is already loaded.  */
6427
6428 static int
6429 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6430                        struct dwarf2_per_cu_data *per_cu,
6431                        enum language pretend_language)
6432 {
6433   /* We may arrive here during partial symbol reading, if we need full
6434      DIEs to process an unusual case (e.g. template arguments).  Do
6435      not queue PER_CU, just tell our caller to load its DIEs.  */
6436   if (dwarf2_per_objfile->reading_partial_symbols)
6437     {
6438       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6439         return 1;
6440       return 0;
6441     }
6442
6443   /* Mark the dependence relation so that we don't flush PER_CU
6444      too early.  */
6445   dwarf2_add_dependence (this_cu, per_cu);
6446
6447   /* If it's already on the queue, we have nothing to do.  */
6448   if (per_cu->queued)
6449     return 0;
6450
6451   /* If the compilation unit is already loaded, just mark it as
6452      used.  */
6453   if (per_cu->cu != NULL)
6454     {
6455       per_cu->cu->last_used = 0;
6456       return 0;
6457     }
6458
6459   /* Add it to the queue.  */
6460   queue_comp_unit (per_cu, pretend_language);
6461
6462   return 1;
6463 }
6464
6465 /* Process the queue.  */
6466
6467 static void
6468 process_queue (void)
6469 {
6470   struct dwarf2_queue_item *item, *next_item;
6471
6472   if (dwarf2_read_debug)
6473     {
6474       fprintf_unfiltered (gdb_stdlog,
6475                           "Expanding one or more symtabs of objfile %s ...\n",
6476                           dwarf2_per_objfile->objfile->name);
6477     }
6478
6479   /* The queue starts out with one item, but following a DIE reference
6480      may load a new CU, adding it to the end of the queue.  */
6481   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6482     {
6483       if (dwarf2_per_objfile->using_index
6484           ? !item->per_cu->v.quick->symtab
6485           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6486         {
6487           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6488
6489           if (dwarf2_read_debug)
6490             {
6491               fprintf_unfiltered (gdb_stdlog,
6492                                   "Expanding symtab of %s at offset 0x%x\n",
6493                                   per_cu->is_debug_types ? "TU" : "CU",
6494                                   per_cu->offset.sect_off);
6495             }
6496
6497           if (per_cu->is_debug_types)
6498             process_full_type_unit (per_cu, item->pretend_language);
6499           else
6500             process_full_comp_unit (per_cu, item->pretend_language);
6501
6502           if (dwarf2_read_debug)
6503             {
6504               fprintf_unfiltered (gdb_stdlog,
6505                                   "Done expanding %s at offset 0x%x\n",
6506                                   per_cu->is_debug_types ? "TU" : "CU",
6507                                   per_cu->offset.sect_off);
6508             }
6509         }
6510
6511       item->per_cu->queued = 0;
6512       next_item = item->next;
6513       xfree (item);
6514     }
6515
6516   dwarf2_queue_tail = NULL;
6517
6518   if (dwarf2_read_debug)
6519     {
6520       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6521                           dwarf2_per_objfile->objfile->name);
6522     }
6523 }
6524
6525 /* Free all allocated queue entries.  This function only releases anything if
6526    an error was thrown; if the queue was processed then it would have been
6527    freed as we went along.  */
6528
6529 static void
6530 dwarf2_release_queue (void *dummy)
6531 {
6532   struct dwarf2_queue_item *item, *last;
6533
6534   item = dwarf2_queue;
6535   while (item)
6536     {
6537       /* Anything still marked queued is likely to be in an
6538          inconsistent state, so discard it.  */
6539       if (item->per_cu->queued)
6540         {
6541           if (item->per_cu->cu != NULL)
6542             free_one_cached_comp_unit (item->per_cu);
6543           item->per_cu->queued = 0;
6544         }
6545
6546       last = item;
6547       item = item->next;
6548       xfree (last);
6549     }
6550
6551   dwarf2_queue = dwarf2_queue_tail = NULL;
6552 }
6553
6554 /* Read in full symbols for PST, and anything it depends on.  */
6555
6556 static void
6557 psymtab_to_symtab_1 (struct partial_symtab *pst)
6558 {
6559   struct dwarf2_per_cu_data *per_cu;
6560   int i;
6561
6562   if (pst->readin)
6563     return;
6564
6565   for (i = 0; i < pst->number_of_dependencies; i++)
6566     if (!pst->dependencies[i]->readin
6567         && pst->dependencies[i]->user == NULL)
6568       {
6569         /* Inform about additional files that need to be read in.  */
6570         if (info_verbose)
6571           {
6572             /* FIXME: i18n: Need to make this a single string.  */
6573             fputs_filtered (" ", gdb_stdout);
6574             wrap_here ("");
6575             fputs_filtered ("and ", gdb_stdout);
6576             wrap_here ("");
6577             printf_filtered ("%s...", pst->dependencies[i]->filename);
6578             wrap_here ("");     /* Flush output.  */
6579             gdb_flush (gdb_stdout);
6580           }
6581         psymtab_to_symtab_1 (pst->dependencies[i]);
6582       }
6583
6584   per_cu = pst->read_symtab_private;
6585
6586   if (per_cu == NULL)
6587     {
6588       /* It's an include file, no symbols to read for it.
6589          Everything is in the parent symtab.  */
6590       pst->readin = 1;
6591       return;
6592     }
6593
6594   dw2_do_instantiate_symtab (per_cu);
6595 }
6596
6597 /* Trivial hash function for die_info: the hash value of a DIE
6598    is its offset in .debug_info for this objfile.  */
6599
6600 static hashval_t
6601 die_hash (const void *item)
6602 {
6603   const struct die_info *die = item;
6604
6605   return die->offset.sect_off;
6606 }
6607
6608 /* Trivial comparison function for die_info structures: two DIEs
6609    are equal if they have the same offset.  */
6610
6611 static int
6612 die_eq (const void *item_lhs, const void *item_rhs)
6613 {
6614   const struct die_info *die_lhs = item_lhs;
6615   const struct die_info *die_rhs = item_rhs;
6616
6617   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6618 }
6619
6620 /* die_reader_func for load_full_comp_unit.
6621    This is identical to read_signatured_type_reader,
6622    but is kept separate for now.  */
6623
6624 static void
6625 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6626                             gdb_byte *info_ptr,
6627                             struct die_info *comp_unit_die,
6628                             int has_children,
6629                             void *data)
6630 {
6631   struct dwarf2_cu *cu = reader->cu;
6632   enum language *language_ptr = data;
6633
6634   gdb_assert (cu->die_hash == NULL);
6635   cu->die_hash =
6636     htab_create_alloc_ex (cu->header.length / 12,
6637                           die_hash,
6638                           die_eq,
6639                           NULL,
6640                           &cu->comp_unit_obstack,
6641                           hashtab_obstack_allocate,
6642                           dummy_obstack_deallocate);
6643
6644   if (has_children)
6645     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6646                                                   &info_ptr, comp_unit_die);
6647   cu->dies = comp_unit_die;
6648   /* comp_unit_die is not stored in die_hash, no need.  */
6649
6650   /* We try not to read any attributes in this function, because not
6651      all CUs needed for references have been loaded yet, and symbol
6652      table processing isn't initialized.  But we have to set the CU language,
6653      or we won't be able to build types correctly.
6654      Similarly, if we do not read the producer, we can not apply
6655      producer-specific interpretation.  */
6656   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6657 }
6658
6659 /* Load the DIEs associated with PER_CU into memory.  */
6660
6661 static void
6662 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6663                      enum language pretend_language)
6664 {
6665   gdb_assert (! this_cu->is_debug_types);
6666
6667   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6668                            load_full_comp_unit_reader, &pretend_language);
6669 }
6670
6671 /* Add a DIE to the delayed physname list.  */
6672
6673 static void
6674 add_to_method_list (struct type *type, int fnfield_index, int index,
6675                     const char *name, struct die_info *die,
6676                     struct dwarf2_cu *cu)
6677 {
6678   struct delayed_method_info mi;
6679   mi.type = type;
6680   mi.fnfield_index = fnfield_index;
6681   mi.index = index;
6682   mi.name = name;
6683   mi.die = die;
6684   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6685 }
6686
6687 /* A cleanup for freeing the delayed method list.  */
6688
6689 static void
6690 free_delayed_list (void *ptr)
6691 {
6692   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6693   if (cu->method_list != NULL)
6694     {
6695       VEC_free (delayed_method_info, cu->method_list);
6696       cu->method_list = NULL;
6697     }
6698 }
6699
6700 /* Compute the physnames of any methods on the CU's method list.
6701
6702    The computation of method physnames is delayed in order to avoid the
6703    (bad) condition that one of the method's formal parameters is of an as yet
6704    incomplete type.  */
6705
6706 static void
6707 compute_delayed_physnames (struct dwarf2_cu *cu)
6708 {
6709   int i;
6710   struct delayed_method_info *mi;
6711   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6712     {
6713       const char *physname;
6714       struct fn_fieldlist *fn_flp
6715         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6716       physname = dwarf2_physname ((char *) mi->name, mi->die, cu);
6717       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6718     }
6719 }
6720
6721 /* Go objects should be embedded in a DW_TAG_module DIE,
6722    and it's not clear if/how imported objects will appear.
6723    To keep Go support simple until that's worked out,
6724    go back through what we've read and create something usable.
6725    We could do this while processing each DIE, and feels kinda cleaner,
6726    but that way is more invasive.
6727    This is to, for example, allow the user to type "p var" or "b main"
6728    without having to specify the package name, and allow lookups
6729    of module.object to work in contexts that use the expression
6730    parser.  */
6731
6732 static void
6733 fixup_go_packaging (struct dwarf2_cu *cu)
6734 {
6735   char *package_name = NULL;
6736   struct pending *list;
6737   int i;
6738
6739   for (list = global_symbols; list != NULL; list = list->next)
6740     {
6741       for (i = 0; i < list->nsyms; ++i)
6742         {
6743           struct symbol *sym = list->symbol[i];
6744
6745           if (SYMBOL_LANGUAGE (sym) == language_go
6746               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6747             {
6748               char *this_package_name = go_symbol_package_name (sym);
6749
6750               if (this_package_name == NULL)
6751                 continue;
6752               if (package_name == NULL)
6753                 package_name = this_package_name;
6754               else
6755                 {
6756                   if (strcmp (package_name, this_package_name) != 0)
6757                     complaint (&symfile_complaints,
6758                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6759                                (SYMBOL_SYMTAB (sym)
6760                                 && SYMBOL_SYMTAB (sym)->filename
6761                                 ? SYMBOL_SYMTAB (sym)->filename
6762                                 : cu->objfile->name),
6763                                this_package_name, package_name);
6764                   xfree (this_package_name);
6765                 }
6766             }
6767         }
6768     }
6769
6770   if (package_name != NULL)
6771     {
6772       struct objfile *objfile = cu->objfile;
6773       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6774                                      package_name, objfile);
6775       struct symbol *sym;
6776
6777       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6778
6779       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6780       SYMBOL_SET_LANGUAGE (sym, language_go);
6781       SYMBOL_SET_NAMES (sym, package_name, strlen (package_name), 1, objfile);
6782       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6783          e.g., "main" finds the "main" module and not C's main().  */
6784       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6785       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
6786       SYMBOL_TYPE (sym) = type;
6787
6788       add_symbol_to_list (sym, &global_symbols);
6789
6790       xfree (package_name);
6791     }
6792 }
6793
6794 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
6795
6796 /* Return the symtab for PER_CU.  This works properly regardless of
6797    whether we're using the index or psymtabs.  */
6798
6799 static struct symtab *
6800 get_symtab (struct dwarf2_per_cu_data *per_cu)
6801 {
6802   return (dwarf2_per_objfile->using_index
6803           ? per_cu->v.quick->symtab
6804           : per_cu->v.psymtab->symtab);
6805 }
6806
6807 /* A helper function for computing the list of all symbol tables
6808    included by PER_CU.  */
6809
6810 static void
6811 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6812                                 htab_t all_children,
6813                                 struct dwarf2_per_cu_data *per_cu)
6814 {
6815   void **slot;
6816   int ix;
6817   struct dwarf2_per_cu_data *iter;
6818
6819   slot = htab_find_slot (all_children, per_cu, INSERT);
6820   if (*slot != NULL)
6821     {
6822       /* This inclusion and its children have been processed.  */
6823       return;
6824     }
6825
6826   *slot = per_cu;
6827   /* Only add a CU if it has a symbol table.  */
6828   if (get_symtab (per_cu) != NULL)
6829     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6830
6831   for (ix = 0;
6832        VEC_iterate (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs, ix, iter);
6833        ++ix)
6834     recursively_compute_inclusions (result, all_children, iter);
6835 }
6836
6837 /* Compute the symtab 'includes' fields for the symtab related to
6838    PER_CU.  */
6839
6840 static void
6841 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6842 {
6843   gdb_assert (! per_cu->is_debug_types);
6844
6845   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs))
6846     {
6847       int ix, len;
6848       struct dwarf2_per_cu_data *iter;
6849       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6850       htab_t all_children;
6851       struct symtab *symtab = get_symtab (per_cu);
6852
6853       /* If we don't have a symtab, we can just skip this case.  */
6854       if (symtab == NULL)
6855         return;
6856
6857       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6858                                         NULL, xcalloc, xfree);
6859
6860       for (ix = 0;
6861            VEC_iterate (dwarf2_per_cu_ptr, per_cu->s.imported_symtabs,
6862                         ix, iter);
6863            ++ix)
6864         recursively_compute_inclusions (&result_children, all_children, iter);
6865
6866       /* Now we have a transitive closure of all the included CUs, so
6867          we can convert it to a list of symtabs.  */
6868       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6869       symtab->includes
6870         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6871                          (len + 1) * sizeof (struct symtab *));
6872       for (ix = 0;
6873            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6874            ++ix)
6875         symtab->includes[ix] = get_symtab (iter);
6876       symtab->includes[len] = NULL;
6877
6878       VEC_free (dwarf2_per_cu_ptr, result_children);
6879       htab_delete (all_children);
6880     }
6881 }
6882
6883 /* Compute the 'includes' field for the symtabs of all the CUs we just
6884    read.  */
6885
6886 static void
6887 process_cu_includes (void)
6888 {
6889   int ix;
6890   struct dwarf2_per_cu_data *iter;
6891
6892   for (ix = 0;
6893        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6894                     ix, iter);
6895        ++ix)
6896     {
6897       if (! iter->is_debug_types)
6898         compute_symtab_includes (iter);
6899     }
6900
6901   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6902 }
6903
6904 /* Generate full symbol information for PER_CU, whose DIEs have
6905    already been loaded into memory.  */
6906
6907 static void
6908 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6909                         enum language pretend_language)
6910 {
6911   struct dwarf2_cu *cu = per_cu->cu;
6912   struct objfile *objfile = per_cu->objfile;
6913   CORE_ADDR lowpc, highpc;
6914   struct symtab *symtab;
6915   struct cleanup *back_to, *delayed_list_cleanup;
6916   CORE_ADDR baseaddr;
6917   struct block *static_block;
6918
6919   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6920
6921   buildsym_init ();
6922   back_to = make_cleanup (really_free_pendings, NULL);
6923   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6924
6925   cu->list_in_scope = &file_symbols;
6926
6927   cu->language = pretend_language;
6928   cu->language_defn = language_def (cu->language);
6929
6930   /* Do line number decoding in read_file_scope () */
6931   process_die (cu->dies, cu);
6932
6933   /* For now fudge the Go package.  */
6934   if (cu->language == language_go)
6935     fixup_go_packaging (cu);
6936
6937   /* Now that we have processed all the DIEs in the CU, all the types 
6938      should be complete, and it should now be safe to compute all of the
6939      physnames.  */
6940   compute_delayed_physnames (cu);
6941   do_cleanups (delayed_list_cleanup);
6942
6943   /* Some compilers don't define a DW_AT_high_pc attribute for the
6944      compilation unit.  If the DW_AT_high_pc is missing, synthesize
6945      it, by scanning the DIE's below the compilation unit.  */
6946   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
6947
6948   static_block
6949     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
6950                                    per_cu->s.imported_symtabs != NULL);
6951
6952   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
6953      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
6954      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
6955      addrmap to help ensure it has an accurate map of pc values belonging to
6956      this comp unit.  */
6957   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
6958
6959   symtab = end_symtab_from_static_block (static_block, objfile,
6960                                          SECT_OFF_TEXT (objfile), 0);
6961
6962   if (symtab != NULL)
6963     {
6964       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
6965
6966       /* Set symtab language to language from DW_AT_language.  If the
6967          compilation is from a C file generated by language preprocessors, do
6968          not set the language if it was already deduced by start_subfile.  */
6969       if (!(cu->language == language_c && symtab->language != language_c))
6970         symtab->language = cu->language;
6971
6972       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
6973          produce DW_AT_location with location lists but it can be possibly
6974          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
6975          there were bugs in prologue debug info, fixed later in GCC-4.5
6976          by "unwind info for epilogues" patch (which is not directly related).
6977
6978          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
6979          needed, it would be wrong due to missing DW_AT_producer there.
6980
6981          Still one can confuse GDB by using non-standard GCC compilation
6982          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
6983          */ 
6984       if (cu->has_loclist && gcc_4_minor >= 5)
6985         symtab->locations_valid = 1;
6986
6987       if (gcc_4_minor >= 5)
6988         symtab->epilogue_unwind_valid = 1;
6989
6990       symtab->call_site_htab = cu->call_site_htab;
6991     }
6992
6993   if (dwarf2_per_objfile->using_index)
6994     per_cu->v.quick->symtab = symtab;
6995   else
6996     {
6997       struct partial_symtab *pst = per_cu->v.psymtab;
6998       pst->symtab = symtab;
6999       pst->readin = 1;
7000     }
7001
7002   /* Push it for inclusion processing later.  */
7003   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7004
7005   do_cleanups (back_to);
7006 }
7007
7008 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7009    already been loaded into memory.  */
7010
7011 static void
7012 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7013                         enum language pretend_language)
7014 {
7015   struct dwarf2_cu *cu = per_cu->cu;
7016   struct objfile *objfile = per_cu->objfile;
7017   struct symtab *symtab;
7018   struct cleanup *back_to, *delayed_list_cleanup;
7019
7020   buildsym_init ();
7021   back_to = make_cleanup (really_free_pendings, NULL);
7022   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7023
7024   cu->list_in_scope = &file_symbols;
7025
7026   cu->language = pretend_language;
7027   cu->language_defn = language_def (cu->language);
7028
7029   /* The symbol tables are set up in read_type_unit_scope.  */
7030   process_die (cu->dies, cu);
7031
7032   /* For now fudge the Go package.  */
7033   if (cu->language == language_go)
7034     fixup_go_packaging (cu);
7035
7036   /* Now that we have processed all the DIEs in the CU, all the types 
7037      should be complete, and it should now be safe to compute all of the
7038      physnames.  */
7039   compute_delayed_physnames (cu);
7040   do_cleanups (delayed_list_cleanup);
7041
7042   /* TUs share symbol tables.
7043      If this is the first TU to use this symtab, complete the construction
7044      of it with end_expandable_symtab.  Otherwise, complete the addition of
7045      this TU's symbols to the existing symtab.  */
7046   if (per_cu->s.type_unit_group->primary_symtab == NULL)
7047     {
7048       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7049       per_cu->s.type_unit_group->primary_symtab = symtab;
7050
7051       if (symtab != NULL)
7052         {
7053           /* Set symtab language to language from DW_AT_language.  If the
7054              compilation is from a C file generated by language preprocessors,
7055              do not set the language if it was already deduced by
7056              start_subfile.  */
7057           if (!(cu->language == language_c && symtab->language != language_c))
7058             symtab->language = cu->language;
7059         }
7060     }
7061   else
7062     {
7063       augment_type_symtab (objfile,
7064                            per_cu->s.type_unit_group->primary_symtab);
7065       symtab = per_cu->s.type_unit_group->primary_symtab;
7066     }
7067
7068   if (dwarf2_per_objfile->using_index)
7069     per_cu->v.quick->symtab = symtab;
7070   else
7071     {
7072       struct partial_symtab *pst = per_cu->v.psymtab;
7073       pst->symtab = symtab;
7074       pst->readin = 1;
7075     }
7076
7077   do_cleanups (back_to);
7078 }
7079
7080 /* Process an imported unit DIE.  */
7081
7082 static void
7083 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7084 {
7085   struct attribute *attr;
7086
7087   /* For now we don't handle imported units in type units.  */
7088   if (cu->per_cu->is_debug_types)
7089     {
7090       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7091                " supported in type units [in module %s]"),
7092              cu->objfile->name);
7093     }
7094
7095   attr = dwarf2_attr (die, DW_AT_import, cu);
7096   if (attr != NULL)
7097     {
7098       struct dwarf2_per_cu_data *per_cu;
7099       struct symtab *imported_symtab;
7100       sect_offset offset;
7101       int is_dwz;
7102
7103       offset = dwarf2_get_ref_die_offset (attr);
7104       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7105       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7106
7107       /* Queue the unit, if needed.  */
7108       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7109         load_full_comp_unit (per_cu, cu->language);
7110
7111       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->s.imported_symtabs,
7112                      per_cu);
7113     }
7114 }
7115
7116 /* Process a die and its children.  */
7117
7118 static void
7119 process_die (struct die_info *die, struct dwarf2_cu *cu)
7120 {
7121   switch (die->tag)
7122     {
7123     case DW_TAG_padding:
7124       break;
7125     case DW_TAG_compile_unit:
7126     case DW_TAG_partial_unit:
7127       read_file_scope (die, cu);
7128       break;
7129     case DW_TAG_type_unit:
7130       read_type_unit_scope (die, cu);
7131       break;
7132     case DW_TAG_subprogram:
7133     case DW_TAG_inlined_subroutine:
7134       read_func_scope (die, cu);
7135       break;
7136     case DW_TAG_lexical_block:
7137     case DW_TAG_try_block:
7138     case DW_TAG_catch_block:
7139       read_lexical_block_scope (die, cu);
7140       break;
7141     case DW_TAG_GNU_call_site:
7142       read_call_site_scope (die, cu);
7143       break;
7144     case DW_TAG_class_type:
7145     case DW_TAG_interface_type:
7146     case DW_TAG_structure_type:
7147     case DW_TAG_union_type:
7148       process_structure_scope (die, cu);
7149       break;
7150     case DW_TAG_enumeration_type:
7151       process_enumeration_scope (die, cu);
7152       break;
7153
7154     /* These dies have a type, but processing them does not create
7155        a symbol or recurse to process the children.  Therefore we can
7156        read them on-demand through read_type_die.  */
7157     case DW_TAG_subroutine_type:
7158     case DW_TAG_set_type:
7159     case DW_TAG_array_type:
7160     case DW_TAG_pointer_type:
7161     case DW_TAG_ptr_to_member_type:
7162     case DW_TAG_reference_type:
7163     case DW_TAG_string_type:
7164       break;
7165
7166     case DW_TAG_base_type:
7167     case DW_TAG_subrange_type:
7168     case DW_TAG_typedef:
7169       /* Add a typedef symbol for the type definition, if it has a
7170          DW_AT_name.  */
7171       new_symbol (die, read_type_die (die, cu), cu);
7172       break;
7173     case DW_TAG_common_block:
7174       read_common_block (die, cu);
7175       break;
7176     case DW_TAG_common_inclusion:
7177       break;
7178     case DW_TAG_namespace:
7179       processing_has_namespace_info = 1;
7180       read_namespace (die, cu);
7181       break;
7182     case DW_TAG_module:
7183       processing_has_namespace_info = 1;
7184       read_module (die, cu);
7185       break;
7186     case DW_TAG_imported_declaration:
7187     case DW_TAG_imported_module:
7188       processing_has_namespace_info = 1;
7189       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7190                                  || cu->language != language_fortran))
7191         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7192                    dwarf_tag_name (die->tag));
7193       read_import_statement (die, cu);
7194       break;
7195
7196     case DW_TAG_imported_unit:
7197       process_imported_unit_die (die, cu);
7198       break;
7199
7200     default:
7201       new_symbol (die, NULL, cu);
7202       break;
7203     }
7204 }
7205
7206 /* A helper function for dwarf2_compute_name which determines whether DIE
7207    needs to have the name of the scope prepended to the name listed in the
7208    die.  */
7209
7210 static int
7211 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7212 {
7213   struct attribute *attr;
7214
7215   switch (die->tag)
7216     {
7217     case DW_TAG_namespace:
7218     case DW_TAG_typedef:
7219     case DW_TAG_class_type:
7220     case DW_TAG_interface_type:
7221     case DW_TAG_structure_type:
7222     case DW_TAG_union_type:
7223     case DW_TAG_enumeration_type:
7224     case DW_TAG_enumerator:
7225     case DW_TAG_subprogram:
7226     case DW_TAG_member:
7227       return 1;
7228
7229     case DW_TAG_variable:
7230     case DW_TAG_constant:
7231       /* We only need to prefix "globally" visible variables.  These include
7232          any variable marked with DW_AT_external or any variable that
7233          lives in a namespace.  [Variables in anonymous namespaces
7234          require prefixing, but they are not DW_AT_external.]  */
7235
7236       if (dwarf2_attr (die, DW_AT_specification, cu))
7237         {
7238           struct dwarf2_cu *spec_cu = cu;
7239
7240           return die_needs_namespace (die_specification (die, &spec_cu),
7241                                       spec_cu);
7242         }
7243
7244       attr = dwarf2_attr (die, DW_AT_external, cu);
7245       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7246           && die->parent->tag != DW_TAG_module)
7247         return 0;
7248       /* A variable in a lexical block of some kind does not need a
7249          namespace, even though in C++ such variables may be external
7250          and have a mangled name.  */
7251       if (die->parent->tag ==  DW_TAG_lexical_block
7252           || die->parent->tag ==  DW_TAG_try_block
7253           || die->parent->tag ==  DW_TAG_catch_block
7254           || die->parent->tag == DW_TAG_subprogram)
7255         return 0;
7256       return 1;
7257
7258     default:
7259       return 0;
7260     }
7261 }
7262
7263 /* Retrieve the last character from a mem_file.  */
7264
7265 static void
7266 do_ui_file_peek_last (void *object, const char *buffer, long length)
7267 {
7268   char *last_char_p = (char *) object;
7269
7270   if (length > 0)
7271     *last_char_p = buffer[length - 1];
7272 }
7273
7274 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7275    compute the physname for the object, which include a method's:
7276    - formal parameters (C++/Java),
7277    - receiver type (Go),
7278    - return type (Java).
7279
7280    The term "physname" is a bit confusing.
7281    For C++, for example, it is the demangled name.
7282    For Go, for example, it's the mangled name.
7283
7284    For Ada, return the DIE's linkage name rather than the fully qualified
7285    name.  PHYSNAME is ignored..
7286
7287    The result is allocated on the objfile_obstack and canonicalized.  */
7288
7289 static const char *
7290 dwarf2_compute_name (char *name, struct die_info *die, struct dwarf2_cu *cu,
7291                      int physname)
7292 {
7293   struct objfile *objfile = cu->objfile;
7294
7295   if (name == NULL)
7296     name = dwarf2_name (die, cu);
7297
7298   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7299      compute it by typename_concat inside GDB.  */
7300   if (cu->language == language_ada
7301       || (cu->language == language_fortran && physname))
7302     {
7303       /* For Ada unit, we prefer the linkage name over the name, as
7304          the former contains the exported name, which the user expects
7305          to be able to reference.  Ideally, we want the user to be able
7306          to reference this entity using either natural or linkage name,
7307          but we haven't started looking at this enhancement yet.  */
7308       struct attribute *attr;
7309
7310       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7311       if (attr == NULL)
7312         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7313       if (attr && DW_STRING (attr))
7314         return DW_STRING (attr);
7315     }
7316
7317   /* These are the only languages we know how to qualify names in.  */
7318   if (name != NULL
7319       && (cu->language == language_cplus || cu->language == language_java
7320           || cu->language == language_fortran))
7321     {
7322       if (die_needs_namespace (die, cu))
7323         {
7324           long length;
7325           const char *prefix;
7326           struct ui_file *buf;
7327
7328           prefix = determine_prefix (die, cu);
7329           buf = mem_fileopen ();
7330           if (*prefix != '\0')
7331             {
7332               char *prefixed_name = typename_concat (NULL, prefix, name,
7333                                                      physname, cu);
7334
7335               fputs_unfiltered (prefixed_name, buf);
7336               xfree (prefixed_name);
7337             }
7338           else
7339             fputs_unfiltered (name, buf);
7340
7341           /* Template parameters may be specified in the DIE's DW_AT_name, or
7342              as children with DW_TAG_template_type_param or
7343              DW_TAG_value_type_param.  If the latter, add them to the name
7344              here.  If the name already has template parameters, then
7345              skip this step; some versions of GCC emit both, and
7346              it is more efficient to use the pre-computed name.
7347
7348              Something to keep in mind about this process: it is very
7349              unlikely, or in some cases downright impossible, to produce
7350              something that will match the mangled name of a function.
7351              If the definition of the function has the same debug info,
7352              we should be able to match up with it anyway.  But fallbacks
7353              using the minimal symbol, for instance to find a method
7354              implemented in a stripped copy of libstdc++, will not work.
7355              If we do not have debug info for the definition, we will have to
7356              match them up some other way.
7357
7358              When we do name matching there is a related problem with function
7359              templates; two instantiated function templates are allowed to
7360              differ only by their return types, which we do not add here.  */
7361
7362           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7363             {
7364               struct attribute *attr;
7365               struct die_info *child;
7366               int first = 1;
7367
7368               die->building_fullname = 1;
7369
7370               for (child = die->child; child != NULL; child = child->sibling)
7371                 {
7372                   struct type *type;
7373                   LONGEST value;
7374                   gdb_byte *bytes;
7375                   struct dwarf2_locexpr_baton *baton;
7376                   struct value *v;
7377
7378                   if (child->tag != DW_TAG_template_type_param
7379                       && child->tag != DW_TAG_template_value_param)
7380                     continue;
7381
7382                   if (first)
7383                     {
7384                       fputs_unfiltered ("<", buf);
7385                       first = 0;
7386                     }
7387                   else
7388                     fputs_unfiltered (", ", buf);
7389
7390                   attr = dwarf2_attr (child, DW_AT_type, cu);
7391                   if (attr == NULL)
7392                     {
7393                       complaint (&symfile_complaints,
7394                                  _("template parameter missing DW_AT_type"));
7395                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7396                       continue;
7397                     }
7398                   type = die_type (child, cu);
7399
7400                   if (child->tag == DW_TAG_template_type_param)
7401                     {
7402                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7403                       continue;
7404                     }
7405
7406                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7407                   if (attr == NULL)
7408                     {
7409                       complaint (&symfile_complaints,
7410                                  _("template parameter missing "
7411                                    "DW_AT_const_value"));
7412                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7413                       continue;
7414                     }
7415
7416                   dwarf2_const_value_attr (attr, type, name,
7417                                            &cu->comp_unit_obstack, cu,
7418                                            &value, &bytes, &baton);
7419
7420                   if (TYPE_NOSIGN (type))
7421                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7422                        changed, this can use value_print instead.  */
7423                     c_printchar (value, type, buf);
7424                   else
7425                     {
7426                       struct value_print_options opts;
7427
7428                       if (baton != NULL)
7429                         v = dwarf2_evaluate_loc_desc (type, NULL,
7430                                                       baton->data,
7431                                                       baton->size,
7432                                                       baton->per_cu);
7433                       else if (bytes != NULL)
7434                         {
7435                           v = allocate_value (type);
7436                           memcpy (value_contents_writeable (v), bytes,
7437                                   TYPE_LENGTH (type));
7438                         }
7439                       else
7440                         v = value_from_longest (type, value);
7441
7442                       /* Specify decimal so that we do not depend on
7443                          the radix.  */
7444                       get_formatted_print_options (&opts, 'd');
7445                       opts.raw = 1;
7446                       value_print (v, buf, &opts);
7447                       release_value (v);
7448                       value_free (v);
7449                     }
7450                 }
7451
7452               die->building_fullname = 0;
7453
7454               if (!first)
7455                 {
7456                   /* Close the argument list, with a space if necessary
7457                      (nested templates).  */
7458                   char last_char = '\0';
7459                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7460                   if (last_char == '>')
7461                     fputs_unfiltered (" >", buf);
7462                   else
7463                     fputs_unfiltered (">", buf);
7464                 }
7465             }
7466
7467           /* For Java and C++ methods, append formal parameter type
7468              information, if PHYSNAME.  */
7469
7470           if (physname && die->tag == DW_TAG_subprogram
7471               && (cu->language == language_cplus
7472                   || cu->language == language_java))
7473             {
7474               struct type *type = read_type_die (die, cu);
7475
7476               c_type_print_args (type, buf, 1, cu->language,
7477                                  &type_print_raw_options);
7478
7479               if (cu->language == language_java)
7480                 {
7481                   /* For java, we must append the return type to method
7482                      names.  */
7483                   if (die->tag == DW_TAG_subprogram)
7484                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7485                                      0, 0, &type_print_raw_options);
7486                 }
7487               else if (cu->language == language_cplus)
7488                 {
7489                   /* Assume that an artificial first parameter is
7490                      "this", but do not crash if it is not.  RealView
7491                      marks unnamed (and thus unused) parameters as
7492                      artificial; there is no way to differentiate
7493                      the two cases.  */
7494                   if (TYPE_NFIELDS (type) > 0
7495                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7496                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7497                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7498                                                                         0))))
7499                     fputs_unfiltered (" const", buf);
7500                 }
7501             }
7502
7503           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7504                                        &length);
7505           ui_file_delete (buf);
7506
7507           if (cu->language == language_cplus)
7508             {
7509               char *cname
7510                 = dwarf2_canonicalize_name (name, cu,
7511                                             &objfile->objfile_obstack);
7512
7513               if (cname != NULL)
7514                 name = cname;
7515             }
7516         }
7517     }
7518
7519   return name;
7520 }
7521
7522 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7523    If scope qualifiers are appropriate they will be added.  The result
7524    will be allocated on the objfile_obstack, or NULL if the DIE does
7525    not have a name.  NAME may either be from a previous call to
7526    dwarf2_name or NULL.
7527
7528    The output string will be canonicalized (if C++/Java).  */
7529
7530 static const char *
7531 dwarf2_full_name (char *name, struct die_info *die, struct dwarf2_cu *cu)
7532 {
7533   return dwarf2_compute_name (name, die, cu, 0);
7534 }
7535
7536 /* Construct a physname for the given DIE in CU.  NAME may either be
7537    from a previous call to dwarf2_name or NULL.  The result will be
7538    allocated on the objfile_objstack or NULL if the DIE does not have a
7539    name.
7540
7541    The output string will be canonicalized (if C++/Java).  */
7542
7543 static const char *
7544 dwarf2_physname (char *name, struct die_info *die, struct dwarf2_cu *cu)
7545 {
7546   struct objfile *objfile = cu->objfile;
7547   struct attribute *attr;
7548   const char *retval, *mangled = NULL, *canon = NULL;
7549   struct cleanup *back_to;
7550   int need_copy = 1;
7551
7552   /* In this case dwarf2_compute_name is just a shortcut not building anything
7553      on its own.  */
7554   if (!die_needs_namespace (die, cu))
7555     return dwarf2_compute_name (name, die, cu, 1);
7556
7557   back_to = make_cleanup (null_cleanup, NULL);
7558
7559   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7560   if (!attr)
7561     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7562
7563   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7564      has computed.  */
7565   if (attr && DW_STRING (attr))
7566     {
7567       char *demangled;
7568
7569       mangled = DW_STRING (attr);
7570
7571       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7572          type.  It is easier for GDB users to search for such functions as
7573          `name(params)' than `long name(params)'.  In such case the minimal
7574          symbol names do not match the full symbol names but for template
7575          functions there is never a need to look up their definition from their
7576          declaration so the only disadvantage remains the minimal symbol
7577          variant `long name(params)' does not have the proper inferior type.
7578          */
7579
7580       if (cu->language == language_go)
7581         {
7582           /* This is a lie, but we already lie to the caller new_symbol_full.
7583              new_symbol_full assumes we return the mangled name.
7584              This just undoes that lie until things are cleaned up.  */
7585           demangled = NULL;
7586         }
7587       else
7588         {
7589           demangled = cplus_demangle (mangled,
7590                                       (DMGL_PARAMS | DMGL_ANSI
7591                                        | (cu->language == language_java
7592                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7593                                           : DMGL_RET_DROP)));
7594         }
7595       if (demangled)
7596         {
7597           make_cleanup (xfree, demangled);
7598           canon = demangled;
7599         }
7600       else
7601         {
7602           canon = mangled;
7603           need_copy = 0;
7604         }
7605     }
7606
7607   if (canon == NULL || check_physname)
7608     {
7609       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7610
7611       if (canon != NULL && strcmp (physname, canon) != 0)
7612         {
7613           /* It may not mean a bug in GDB.  The compiler could also
7614              compute DW_AT_linkage_name incorrectly.  But in such case
7615              GDB would need to be bug-to-bug compatible.  */
7616
7617           complaint (&symfile_complaints,
7618                      _("Computed physname <%s> does not match demangled <%s> "
7619                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7620                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7621
7622           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7623              is available here - over computed PHYSNAME.  It is safer
7624              against both buggy GDB and buggy compilers.  */
7625
7626           retval = canon;
7627         }
7628       else
7629         {
7630           retval = physname;
7631           need_copy = 0;
7632         }
7633     }
7634   else
7635     retval = canon;
7636
7637   if (need_copy)
7638     retval = obsavestring (retval, strlen (retval),
7639                            &objfile->objfile_obstack);
7640
7641   do_cleanups (back_to);
7642   return retval;
7643 }
7644
7645 /* Read the import statement specified by the given die and record it.  */
7646
7647 static void
7648 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7649 {
7650   struct objfile *objfile = cu->objfile;
7651   struct attribute *import_attr;
7652   struct die_info *imported_die, *child_die;
7653   struct dwarf2_cu *imported_cu;
7654   const char *imported_name;
7655   const char *imported_name_prefix;
7656   const char *canonical_name;
7657   const char *import_alias;
7658   const char *imported_declaration = NULL;
7659   const char *import_prefix;
7660   VEC (const_char_ptr) *excludes = NULL;
7661   struct cleanup *cleanups;
7662
7663   char *temp;
7664
7665   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7666   if (import_attr == NULL)
7667     {
7668       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7669                  dwarf_tag_name (die->tag));
7670       return;
7671     }
7672
7673   imported_cu = cu;
7674   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7675   imported_name = dwarf2_name (imported_die, imported_cu);
7676   if (imported_name == NULL)
7677     {
7678       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7679
7680         The import in the following code:
7681         namespace A
7682           {
7683             typedef int B;
7684           }
7685
7686         int main ()
7687           {
7688             using A::B;
7689             B b;
7690             return b;
7691           }
7692
7693         ...
7694          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7695             <52>   DW_AT_decl_file   : 1
7696             <53>   DW_AT_decl_line   : 6
7697             <54>   DW_AT_import      : <0x75>
7698          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7699             <59>   DW_AT_name        : B
7700             <5b>   DW_AT_decl_file   : 1
7701             <5c>   DW_AT_decl_line   : 2
7702             <5d>   DW_AT_type        : <0x6e>
7703         ...
7704          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7705             <76>   DW_AT_byte_size   : 4
7706             <77>   DW_AT_encoding    : 5        (signed)
7707
7708         imports the wrong die ( 0x75 instead of 0x58 ).
7709         This case will be ignored until the gcc bug is fixed.  */
7710       return;
7711     }
7712
7713   /* Figure out the local name after import.  */
7714   import_alias = dwarf2_name (die, cu);
7715
7716   /* Figure out where the statement is being imported to.  */
7717   import_prefix = determine_prefix (die, cu);
7718
7719   /* Figure out what the scope of the imported die is and prepend it
7720      to the name of the imported die.  */
7721   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7722
7723   if (imported_die->tag != DW_TAG_namespace
7724       && imported_die->tag != DW_TAG_module)
7725     {
7726       imported_declaration = imported_name;
7727       canonical_name = imported_name_prefix;
7728     }
7729   else if (strlen (imported_name_prefix) > 0)
7730     {
7731       temp = alloca (strlen (imported_name_prefix)
7732                      + 2 + strlen (imported_name) + 1);
7733       strcpy (temp, imported_name_prefix);
7734       strcat (temp, "::");
7735       strcat (temp, imported_name);
7736       canonical_name = temp;
7737     }
7738   else
7739     canonical_name = imported_name;
7740
7741   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7742
7743   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7744     for (child_die = die->child; child_die && child_die->tag;
7745          child_die = sibling_die (child_die))
7746       {
7747         /* DWARF-4: A Fortran use statement with a “rename list” may be
7748            represented by an imported module entry with an import attribute
7749            referring to the module and owned entries corresponding to those
7750            entities that are renamed as part of being imported.  */
7751
7752         if (child_die->tag != DW_TAG_imported_declaration)
7753           {
7754             complaint (&symfile_complaints,
7755                        _("child DW_TAG_imported_declaration expected "
7756                          "- DIE at 0x%x [in module %s]"),
7757                        child_die->offset.sect_off, objfile->name);
7758             continue;
7759           }
7760
7761         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7762         if (import_attr == NULL)
7763           {
7764             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7765                        dwarf_tag_name (child_die->tag));
7766             continue;
7767           }
7768
7769         imported_cu = cu;
7770         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7771                                               &imported_cu);
7772         imported_name = dwarf2_name (imported_die, imported_cu);
7773         if (imported_name == NULL)
7774           {
7775             complaint (&symfile_complaints,
7776                        _("child DW_TAG_imported_declaration has unknown "
7777                          "imported name - DIE at 0x%x [in module %s]"),
7778                        child_die->offset.sect_off, objfile->name);
7779             continue;
7780           }
7781
7782         VEC_safe_push (const_char_ptr, excludes, imported_name);
7783
7784         process_die (child_die, cu);
7785       }
7786
7787   cp_add_using_directive (import_prefix,
7788                           canonical_name,
7789                           import_alias,
7790                           imported_declaration,
7791                           excludes,
7792                           &objfile->objfile_obstack);
7793
7794   do_cleanups (cleanups);
7795 }
7796
7797 /* Cleanup function for handle_DW_AT_stmt_list.  */
7798
7799 static void
7800 free_cu_line_header (void *arg)
7801 {
7802   struct dwarf2_cu *cu = arg;
7803
7804   free_line_header (cu->line_header);
7805   cu->line_header = NULL;
7806 }
7807
7808 static void
7809 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7810                          char **name, char **comp_dir)
7811 {
7812   struct attribute *attr;
7813
7814   *name = NULL;
7815   *comp_dir = NULL;
7816
7817   /* Find the filename.  Do not use dwarf2_name here, since the filename
7818      is not a source language identifier.  */
7819   attr = dwarf2_attr (die, DW_AT_name, cu);
7820   if (attr)
7821     {
7822       *name = DW_STRING (attr);
7823     }
7824
7825   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7826   if (attr)
7827     *comp_dir = DW_STRING (attr);
7828   else if (*name != NULL && IS_ABSOLUTE_PATH (*name))
7829     {
7830       *comp_dir = ldirname (*name);
7831       if (*comp_dir != NULL)
7832         make_cleanup (xfree, *comp_dir);
7833     }
7834   if (*comp_dir != NULL)
7835     {
7836       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7837          directory, get rid of it.  */
7838       char *cp = strchr (*comp_dir, ':');
7839
7840       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7841         *comp_dir = cp + 1;
7842     }
7843
7844   if (*name == NULL)
7845     *name = "<unknown>";
7846 }
7847
7848 /* Handle DW_AT_stmt_list for a compilation unit.
7849    DIE is the DW_TAG_compile_unit die for CU.
7850    COMP_DIR is the compilation directory.
7851    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7852
7853 static void
7854 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7855                         const char *comp_dir)
7856 {
7857   struct attribute *attr;
7858
7859   gdb_assert (! cu->per_cu->is_debug_types);
7860
7861   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7862   if (attr)
7863     {
7864       unsigned int line_offset = DW_UNSND (attr);
7865       struct line_header *line_header
7866         = dwarf_decode_line_header (line_offset, cu);
7867
7868       if (line_header)
7869         {
7870           cu->line_header = line_header;
7871           make_cleanup (free_cu_line_header, cu);
7872           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7873         }
7874     }
7875 }
7876
7877 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7878
7879 static void
7880 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7881 {
7882   struct objfile *objfile = dwarf2_per_objfile->objfile;
7883   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7884   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7885   CORE_ADDR highpc = ((CORE_ADDR) 0);
7886   struct attribute *attr;
7887   char *name = NULL;
7888   char *comp_dir = NULL;
7889   struct die_info *child_die;
7890   bfd *abfd = objfile->obfd;
7891   CORE_ADDR baseaddr;
7892
7893   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7894
7895   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7896
7897   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7898      from finish_block.  */
7899   if (lowpc == ((CORE_ADDR) -1))
7900     lowpc = highpc;
7901   lowpc += baseaddr;
7902   highpc += baseaddr;
7903
7904   find_file_and_directory (die, cu, &name, &comp_dir);
7905
7906   prepare_one_comp_unit (cu, die, cu->language);
7907
7908   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7909      standardised yet.  As a workaround for the language detection we fall
7910      back to the DW_AT_producer string.  */
7911   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7912     cu->language = language_opencl;
7913
7914   /* Similar hack for Go.  */
7915   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
7916     set_cu_language (DW_LANG_Go, cu);
7917
7918   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
7919
7920   /* Decode line number information if present.  We do this before
7921      processing child DIEs, so that the line header table is available
7922      for DW_AT_decl_file.  */
7923   handle_DW_AT_stmt_list (die, cu, comp_dir);
7924
7925   /* Process all dies in compilation unit.  */
7926   if (die->child != NULL)
7927     {
7928       child_die = die->child;
7929       while (child_die && child_die->tag)
7930         {
7931           process_die (child_die, cu);
7932           child_die = sibling_die (child_die);
7933         }
7934     }
7935
7936   /* Decode macro information, if present.  Dwarf 2 macro information
7937      refers to information in the line number info statement program
7938      header, so we can only read it if we've read the header
7939      successfully.  */
7940   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
7941   if (attr && cu->line_header)
7942     {
7943       if (dwarf2_attr (die, DW_AT_macro_info, cu))
7944         complaint (&symfile_complaints,
7945                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
7946
7947       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
7948     }
7949   else
7950     {
7951       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
7952       if (attr && cu->line_header)
7953         {
7954           unsigned int macro_offset = DW_UNSND (attr);
7955
7956           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
7957         }
7958     }
7959
7960   do_cleanups (back_to);
7961 }
7962
7963 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
7964    Create the set of symtabs used by this TU, or if this TU is sharing
7965    symtabs with another TU and the symtabs have already been created
7966    then restore those symtabs in the line header.
7967    We don't need the pc/line-number mapping for type units.  */
7968
7969 static void
7970 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
7971 {
7972   struct objfile *objfile = dwarf2_per_objfile->objfile;
7973   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7974   struct type_unit_group *tu_group;
7975   int first_time;
7976   struct line_header *lh;
7977   struct attribute *attr;
7978   unsigned int i, line_offset;
7979
7980   gdb_assert (per_cu->is_debug_types);
7981
7982   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7983
7984   /* If we're using .gdb_index (includes -readnow) then
7985      per_cu->s.type_unit_group may not have been set up yet.  */
7986   if (per_cu->s.type_unit_group == NULL)
7987     per_cu->s.type_unit_group = get_type_unit_group (cu, attr);
7988   tu_group = per_cu->s.type_unit_group;
7989
7990   /* If we've already processed this stmt_list there's no real need to
7991      do it again, we could fake it and just recreate the part we need
7992      (file name,index -> symtab mapping).  If data shows this optimization
7993      is useful we can do it then.  */
7994   first_time = tu_group->primary_symtab == NULL;
7995
7996   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
7997      debug info.  */
7998   lh = NULL;
7999   if (attr != NULL)
8000     {
8001       line_offset = DW_UNSND (attr);
8002       lh = dwarf_decode_line_header (line_offset, cu);
8003     }
8004   if (lh == NULL)
8005     {
8006       if (first_time)
8007         dwarf2_start_symtab (cu, "", NULL, 0);
8008       else
8009         {
8010           gdb_assert (tu_group->symtabs == NULL);
8011           restart_symtab (0);
8012         }
8013       /* Note: The primary symtab will get allocated at the end.  */
8014       return;
8015     }
8016
8017   cu->line_header = lh;
8018   make_cleanup (free_cu_line_header, cu);
8019
8020   if (first_time)
8021     {
8022       dwarf2_start_symtab (cu, "", NULL, 0);
8023
8024       tu_group->num_symtabs = lh->num_file_names;
8025       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8026
8027       for (i = 0; i < lh->num_file_names; ++i)
8028         {
8029           char *dir = NULL;
8030           struct file_entry *fe = &lh->file_names[i];
8031
8032           if (fe->dir_index)
8033             dir = lh->include_dirs[fe->dir_index - 1];
8034           dwarf2_start_subfile (fe->name, dir, NULL);
8035
8036           /* Note: We don't have to watch for the main subfile here, type units
8037              don't have DW_AT_name.  */
8038
8039           if (current_subfile->symtab == NULL)
8040             {
8041               /* NOTE: start_subfile will recognize when it's been passed
8042                  a file it has already seen.  So we can't assume there's a
8043                  simple mapping from lh->file_names to subfiles,
8044                  lh->file_names may contain dups.  */
8045               current_subfile->symtab = allocate_symtab (current_subfile->name,
8046                                                          objfile);
8047             }
8048
8049           fe->symtab = current_subfile->symtab;
8050           tu_group->symtabs[i] = fe->symtab;
8051         }
8052     }
8053   else
8054     {
8055       restart_symtab (0);
8056
8057       for (i = 0; i < lh->num_file_names; ++i)
8058         {
8059           struct file_entry *fe = &lh->file_names[i];
8060
8061           fe->symtab = tu_group->symtabs[i];
8062         }
8063     }
8064
8065   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8066      so they don't have a "real" (so to speak) symtab anyway.
8067      There is later code that will assign the main symtab to all symbols
8068      that don't have one.  We need to handle the case of a symbol with a
8069      missing symtab (DW_AT_decl_file) anyway.  */
8070 }
8071
8072 /* Process DW_TAG_type_unit.
8073    For TUs we want to skip the first top level sibling if it's not the
8074    actual type being defined by this TU.  In this case the first top
8075    level sibling is there to provide context only.  */
8076
8077 static void
8078 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8079 {
8080   struct die_info *child_die;
8081
8082   prepare_one_comp_unit (cu, die, language_minimal);
8083
8084   /* Initialize (or reinitialize) the machinery for building symtabs.
8085      We do this before processing child DIEs, so that the line header table
8086      is available for DW_AT_decl_file.  */
8087   setup_type_unit_groups (die, cu);
8088
8089   if (die->child != NULL)
8090     {
8091       child_die = die->child;
8092       while (child_die && child_die->tag)
8093         {
8094           process_die (child_die, cu);
8095           child_die = sibling_die (child_die);
8096         }
8097     }
8098 }
8099 \f
8100 /* DWO/DWP files.
8101
8102    http://gcc.gnu.org/wiki/DebugFission
8103    http://gcc.gnu.org/wiki/DebugFissionDWP
8104
8105    To simplify handling of both DWO files ("object" files with the DWARF info)
8106    and DWP files (a file with the DWOs packaged up into one file), we treat
8107    DWP files as having a collection of virtual DWO files.  */
8108
8109 static hashval_t
8110 hash_dwo_file (const void *item)
8111 {
8112   const struct dwo_file *dwo_file = item;
8113
8114   return htab_hash_string (dwo_file->name);
8115 }
8116
8117 static int
8118 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8119 {
8120   const struct dwo_file *lhs = item_lhs;
8121   const struct dwo_file *rhs = item_rhs;
8122
8123   return strcmp (lhs->name, rhs->name) == 0;
8124 }
8125
8126 /* Allocate a hash table for DWO files.  */
8127
8128 static htab_t
8129 allocate_dwo_file_hash_table (void)
8130 {
8131   struct objfile *objfile = dwarf2_per_objfile->objfile;
8132
8133   return htab_create_alloc_ex (41,
8134                                hash_dwo_file,
8135                                eq_dwo_file,
8136                                NULL,
8137                                &objfile->objfile_obstack,
8138                                hashtab_obstack_allocate,
8139                                dummy_obstack_deallocate);
8140 }
8141
8142 /* Lookup DWO file DWO_NAME.  */
8143
8144 static void **
8145 lookup_dwo_file_slot (const char *dwo_name)
8146 {
8147   struct dwo_file find_entry;
8148   void **slot;
8149
8150   if (dwarf2_per_objfile->dwo_files == NULL)
8151     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8152
8153   memset (&find_entry, 0, sizeof (find_entry));
8154   find_entry.name = dwo_name;
8155   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8156
8157   return slot;
8158 }
8159
8160 static hashval_t
8161 hash_dwo_unit (const void *item)
8162 {
8163   const struct dwo_unit *dwo_unit = item;
8164
8165   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8166   return dwo_unit->signature;
8167 }
8168
8169 static int
8170 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8171 {
8172   const struct dwo_unit *lhs = item_lhs;
8173   const struct dwo_unit *rhs = item_rhs;
8174
8175   /* The signature is assumed to be unique within the DWO file.
8176      So while object file CU dwo_id's always have the value zero,
8177      that's OK, assuming each object file DWO file has only one CU,
8178      and that's the rule for now.  */
8179   return lhs->signature == rhs->signature;
8180 }
8181
8182 /* Allocate a hash table for DWO CUs,TUs.
8183    There is one of these tables for each of CUs,TUs for each DWO file.  */
8184
8185 static htab_t
8186 allocate_dwo_unit_table (struct objfile *objfile)
8187 {
8188   /* Start out with a pretty small number.
8189      Generally DWO files contain only one CU and maybe some TUs.  */
8190   return htab_create_alloc_ex (3,
8191                                hash_dwo_unit,
8192                                eq_dwo_unit,
8193                                NULL,
8194                                &objfile->objfile_obstack,
8195                                hashtab_obstack_allocate,
8196                                dummy_obstack_deallocate);
8197 }
8198
8199 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8200
8201 struct create_dwo_info_table_data
8202 {
8203   struct dwo_file *dwo_file;
8204   htab_t cu_htab;
8205 };
8206
8207 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8208
8209 static void
8210 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8211                                          gdb_byte *info_ptr,
8212                                          struct die_info *comp_unit_die,
8213                                          int has_children,
8214                                          void *datap)
8215 {
8216   struct dwarf2_cu *cu = reader->cu;
8217   struct objfile *objfile = dwarf2_per_objfile->objfile;
8218   sect_offset offset = cu->per_cu->offset;
8219   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
8220   struct create_dwo_info_table_data *data = datap;
8221   struct dwo_file *dwo_file = data->dwo_file;
8222   htab_t cu_htab = data->cu_htab;
8223   void **slot;
8224   struct attribute *attr;
8225   struct dwo_unit *dwo_unit;
8226
8227   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8228   if (attr == NULL)
8229     {
8230       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8231                " its dwo_id [in module %s]"),
8232              offset.sect_off, dwo_file->name);
8233       return;
8234     }
8235
8236   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8237   dwo_unit->dwo_file = dwo_file;
8238   dwo_unit->signature = DW_UNSND (attr);
8239   dwo_unit->info_or_types_section = section;
8240   dwo_unit->offset = offset;
8241   dwo_unit->length = cu->per_cu->length;
8242
8243   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8244   gdb_assert (slot != NULL);
8245   if (*slot != NULL)
8246     {
8247       const struct dwo_unit *dup_dwo_unit = *slot;
8248
8249       complaint (&symfile_complaints,
8250                  _("debug entry at offset 0x%x is duplicate to the entry at"
8251                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8252                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8253                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8254                  dwo_file->name);
8255     }
8256   else
8257     *slot = dwo_unit;
8258
8259   if (dwarf2_read_debug)
8260     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8261                         offset.sect_off,
8262                         phex (dwo_unit->signature,
8263                               sizeof (dwo_unit->signature)));
8264 }
8265
8266 /* Create a hash table to map DWO IDs to their CU entry in
8267    .debug_info.dwo in DWO_FILE.
8268    Note: This function processes DWO files only, not DWP files.  */
8269
8270 static htab_t
8271 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8272 {
8273   struct objfile *objfile = dwarf2_per_objfile->objfile;
8274   struct dwarf2_section_info *section = &dwo_file->sections.info;
8275   bfd *abfd;
8276   htab_t cu_htab;
8277   gdb_byte *info_ptr, *end_ptr;
8278   struct create_dwo_info_table_data create_dwo_info_table_data;
8279
8280   dwarf2_read_section (objfile, section);
8281   info_ptr = section->buffer;
8282
8283   if (info_ptr == NULL)
8284     return NULL;
8285
8286   /* We can't set abfd until now because the section may be empty or
8287      not present, in which case section->asection will be NULL.  */
8288   abfd = section->asection->owner;
8289
8290   if (dwarf2_read_debug)
8291     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8292                         bfd_get_filename (abfd));
8293
8294   cu_htab = allocate_dwo_unit_table (objfile);
8295
8296   create_dwo_info_table_data.dwo_file = dwo_file;
8297   create_dwo_info_table_data.cu_htab = cu_htab;
8298
8299   end_ptr = info_ptr + section->size;
8300   while (info_ptr < end_ptr)
8301     {
8302       struct dwarf2_per_cu_data per_cu;
8303
8304       memset (&per_cu, 0, sizeof (per_cu));
8305       per_cu.objfile = objfile;
8306       per_cu.is_debug_types = 0;
8307       per_cu.offset.sect_off = info_ptr - section->buffer;
8308       per_cu.info_or_types_section = section;
8309
8310       init_cutu_and_read_dies_no_follow (&per_cu,
8311                                          &dwo_file->sections.abbrev,
8312                                          dwo_file,
8313                                          create_dwo_debug_info_hash_table_reader,
8314                                          &create_dwo_info_table_data);
8315
8316       info_ptr += per_cu.length;
8317     }
8318
8319   return cu_htab;
8320 }
8321
8322 /* DWP file .debug_{cu,tu}_index section format:
8323    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8324
8325    Both index sections have the same format, and serve to map a 64-bit
8326    signature to a set of section numbers.  Each section begins with a header,
8327    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8328    indexes, and a pool of 32-bit section numbers.  The index sections will be
8329    aligned at 8-byte boundaries in the file.
8330
8331    The index section header contains two unsigned 32-bit values (using the
8332    byte order of the application binary):
8333
8334     N, the number of compilation units or type units in the index
8335     M, the number of slots in the hash table
8336
8337   (We assume that N and M will not exceed 2^32 - 1.)
8338
8339   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8340
8341   The hash table begins at offset 8 in the section, and consists of an array
8342   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8343   order of the application binary).  Unused slots in the hash table are 0.
8344   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8345
8346   The parallel table begins immediately after the hash table
8347   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8348   array of 32-bit indexes (using the byte order of the application binary),
8349   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8350   table contains a 32-bit index into the pool of section numbers.  For unused
8351   hash table slots, the corresponding entry in the parallel table will be 0.
8352
8353   Given a 64-bit compilation unit signature or a type signature S, an entry
8354   in the hash table is located as follows:
8355
8356   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8357      the low-order k bits all set to 1.
8358
8359   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8360
8361   3) If the hash table entry at index H matches the signature, use that
8362      entry.  If the hash table entry at index H is unused (all zeroes),
8363      terminate the search: the signature is not present in the table.
8364
8365   4) Let H = (H + H') modulo M. Repeat at Step 3.
8366
8367   Because M > N and H' and M are relatively prime, the search is guaranteed
8368   to stop at an unused slot or find the match.
8369
8370   The pool of section numbers begins immediately following the hash table
8371   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8372   section numbers consists of an array of 32-bit words (using the byte order
8373   of the application binary).  Each item in the array is indexed starting
8374   from 0.  The hash table entry provides the index of the first section
8375   number in the set.  Additional section numbers in the set follow, and the
8376   set is terminated by a 0 entry (section number 0 is not used in ELF).
8377
8378   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8379   section must be the first entry in the set, and the .debug_abbrev.dwo must
8380   be the second entry. Other members of the set may follow in any order.  */
8381
8382 /* Create a hash table to map DWO IDs to their CU/TU entry in
8383    .debug_{info,types}.dwo in DWP_FILE.
8384    Returns NULL if there isn't one.
8385    Note: This function processes DWP files only, not DWO files.  */
8386
8387 static struct dwp_hash_table *
8388 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8389 {
8390   struct objfile *objfile = dwarf2_per_objfile->objfile;
8391   bfd *dbfd = dwp_file->dbfd;
8392   char *index_ptr, *index_end;
8393   struct dwarf2_section_info *index;
8394   uint32_t version, nr_units, nr_slots;
8395   struct dwp_hash_table *htab;
8396
8397   if (is_debug_types)
8398     index = &dwp_file->sections.tu_index;
8399   else
8400     index = &dwp_file->sections.cu_index;
8401
8402   if (dwarf2_section_empty_p (index))
8403     return NULL;
8404   dwarf2_read_section (objfile, index);
8405
8406   index_ptr = index->buffer;
8407   index_end = index_ptr + index->size;
8408
8409   version = read_4_bytes (dbfd, index_ptr);
8410   index_ptr += 8; /* Skip the unused word.  */
8411   nr_units = read_4_bytes (dbfd, index_ptr);
8412   index_ptr += 4;
8413   nr_slots = read_4_bytes (dbfd, index_ptr);
8414   index_ptr += 4;
8415
8416   if (version != 1)
8417     {
8418       error (_("Dwarf Error: unsupported DWP file version (%u)"
8419                " [in module %s]"),
8420              version, dwp_file->name);
8421     }
8422   if (nr_slots != (nr_slots & -nr_slots))
8423     {
8424       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8425                " is not power of 2 [in module %s]"),
8426              nr_slots, dwp_file->name);
8427     }
8428
8429   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8430   htab->nr_units = nr_units;
8431   htab->nr_slots = nr_slots;
8432   htab->hash_table = index_ptr;
8433   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8434   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8435
8436   return htab;
8437 }
8438
8439 /* Update SECTIONS with the data from SECTP.
8440
8441    This function is like the other "locate" section routines that are
8442    passed to bfd_map_over_sections, but in this context the sections to
8443    read comes from the DWP hash table, not the full ELF section table.
8444
8445    The result is non-zero for success, or zero if an error was found.  */
8446
8447 static int
8448 locate_virtual_dwo_sections (asection *sectp,
8449                              struct virtual_dwo_sections *sections)
8450 {
8451   const struct dwop_section_names *names = &dwop_section_names;
8452
8453   if (section_is_p (sectp->name, &names->abbrev_dwo))
8454     {
8455       /* There can be only one.  */
8456       if (sections->abbrev.asection != NULL)
8457         return 0;
8458       sections->abbrev.asection = sectp;
8459       sections->abbrev.size = bfd_get_section_size (sectp);
8460     }
8461   else if (section_is_p (sectp->name, &names->info_dwo)
8462            || section_is_p (sectp->name, &names->types_dwo))
8463     {
8464       /* There can be only one.  */
8465       if (sections->info_or_types.asection != NULL)
8466         return 0;
8467       sections->info_or_types.asection = sectp;
8468       sections->info_or_types.size = bfd_get_section_size (sectp);
8469     }
8470   else if (section_is_p (sectp->name, &names->line_dwo))
8471     {
8472       /* There can be only one.  */
8473       if (sections->line.asection != NULL)
8474         return 0;
8475       sections->line.asection = sectp;
8476       sections->line.size = bfd_get_section_size (sectp);
8477     }
8478   else if (section_is_p (sectp->name, &names->loc_dwo))
8479     {
8480       /* There can be only one.  */
8481       if (sections->loc.asection != NULL)
8482         return 0;
8483       sections->loc.asection = sectp;
8484       sections->loc.size = bfd_get_section_size (sectp);
8485     }
8486   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8487     {
8488       /* There can be only one.  */
8489       if (sections->macinfo.asection != NULL)
8490         return 0;
8491       sections->macinfo.asection = sectp;
8492       sections->macinfo.size = bfd_get_section_size (sectp);
8493     }
8494   else if (section_is_p (sectp->name, &names->macro_dwo))
8495     {
8496       /* There can be only one.  */
8497       if (sections->macro.asection != NULL)
8498         return 0;
8499       sections->macro.asection = sectp;
8500       sections->macro.size = bfd_get_section_size (sectp);
8501     }
8502   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8503     {
8504       /* There can be only one.  */
8505       if (sections->str_offsets.asection != NULL)
8506         return 0;
8507       sections->str_offsets.asection = sectp;
8508       sections->str_offsets.size = bfd_get_section_size (sectp);
8509     }
8510   else
8511     {
8512       /* No other kind of section is valid.  */
8513       return 0;
8514     }
8515
8516   return 1;
8517 }
8518
8519 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8520    HTAB is the hash table from the DWP file.
8521    SECTION_INDEX is the index of the DWO in HTAB.  */
8522
8523 static struct dwo_unit *
8524 create_dwo_in_dwp (struct dwp_file *dwp_file,
8525                    const struct dwp_hash_table *htab,
8526                    uint32_t section_index,
8527                    ULONGEST signature, int is_debug_types)
8528 {
8529   struct objfile *objfile = dwarf2_per_objfile->objfile;
8530   bfd *dbfd = dwp_file->dbfd;
8531   const char *kind = is_debug_types ? "TU" : "CU";
8532   struct dwo_file *dwo_file;
8533   struct dwo_unit *dwo_unit;
8534   struct virtual_dwo_sections sections;
8535   void **dwo_file_slot;
8536   char *virtual_dwo_name;
8537   struct dwarf2_section_info *cutu;
8538   struct cleanup *cleanups;
8539   int i;
8540
8541   if (dwarf2_read_debug)
8542     {
8543       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8544                           kind,
8545                           section_index, phex (signature, sizeof (signature)),
8546                           dwp_file->name);
8547     }
8548
8549   /* Fetch the sections of this DWO.
8550      Put a limit on the number of sections we look for so that bad data
8551      doesn't cause us to loop forever.  */
8552
8553 #define MAX_NR_DWO_SECTIONS \
8554   (1 /* .debug_info or .debug_types */ \
8555    + 1 /* .debug_abbrev */ \
8556    + 1 /* .debug_line */ \
8557    + 1 /* .debug_loc */ \
8558    + 1 /* .debug_str_offsets */ \
8559    + 1 /* .debug_macro */ \
8560    + 1 /* .debug_macinfo */ \
8561    + 1 /* trailing zero */)
8562
8563   memset (&sections, 0, sizeof (sections));
8564   cleanups = make_cleanup (null_cleanup, 0);
8565
8566   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8567     {
8568       asection *sectp;
8569       uint32_t section_nr =
8570         read_4_bytes (dbfd,
8571                       htab->section_pool
8572                       + (section_index + i) * sizeof (uint32_t));
8573
8574       if (section_nr == 0)
8575         break;
8576       if (section_nr >= dwp_file->num_sections)
8577         {
8578           error (_("Dwarf Error: bad DWP hash table, section number too large"
8579                    " [in module %s]"),
8580                  dwp_file->name);
8581         }
8582
8583       sectp = dwp_file->elf_sections[section_nr];
8584       if (! locate_virtual_dwo_sections (sectp, &sections))
8585         {
8586           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8587                    " [in module %s]"),
8588                  dwp_file->name);
8589         }
8590     }
8591
8592   if (i < 2
8593       || sections.info_or_types.asection == NULL
8594       || sections.abbrev.asection == NULL)
8595     {
8596       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8597                " [in module %s]"),
8598              dwp_file->name);
8599     }
8600   if (i == MAX_NR_DWO_SECTIONS)
8601     {
8602       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8603                " [in module %s]"),
8604              dwp_file->name);
8605     }
8606
8607   /* It's easier for the rest of the code if we fake a struct dwo_file and
8608      have dwo_unit "live" in that.  At least for now.
8609
8610      The DWP file can be made up of a random collection of CUs and TUs.
8611      However, for each CU + set of TUs that came from the same original
8612      DWO file, we want combine them back into a virtual DWO file to save space
8613      (fewer struct dwo_file objects to allocated).  Remember that for really
8614      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8615
8616   virtual_dwo_name =
8617     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8618                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8619                 sections.line.asection ? sections.line.asection->id : 0,
8620                 sections.loc.asection ? sections.loc.asection->id : 0,
8621                 (sections.str_offsets.asection
8622                 ? sections.str_offsets.asection->id
8623                 : 0));
8624   make_cleanup (xfree, virtual_dwo_name);
8625   /* Can we use an existing virtual DWO file?  */
8626   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name);
8627   /* Create one if necessary.  */
8628   if (*dwo_file_slot == NULL)
8629     {
8630       if (dwarf2_read_debug)
8631         {
8632           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8633                               virtual_dwo_name);
8634         }
8635       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8636       dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8637                                       virtual_dwo_name,
8638                                       strlen (virtual_dwo_name));
8639       dwo_file->sections.abbrev = sections.abbrev;
8640       dwo_file->sections.line = sections.line;
8641       dwo_file->sections.loc = sections.loc;
8642       dwo_file->sections.macinfo = sections.macinfo;
8643       dwo_file->sections.macro = sections.macro;
8644       dwo_file->sections.str_offsets = sections.str_offsets;
8645       /* The "str" section is global to the entire DWP file.  */
8646       dwo_file->sections.str = dwp_file->sections.str;
8647       /* The info or types section is assigned later to dwo_unit,
8648          there's no need to record it in dwo_file.
8649          Also, we can't simply record type sections in dwo_file because
8650          we record a pointer into the vector in dwo_unit.  As we collect more
8651          types we'll grow the vector and eventually have to reallocate space
8652          for it, invalidating all the pointers into the current copy.  */
8653       *dwo_file_slot = dwo_file;
8654     }
8655   else
8656     {
8657       if (dwarf2_read_debug)
8658         {
8659           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8660                               virtual_dwo_name);
8661         }
8662       dwo_file = *dwo_file_slot;
8663     }
8664   do_cleanups (cleanups);
8665
8666   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8667   dwo_unit->dwo_file = dwo_file;
8668   dwo_unit->signature = signature;
8669   dwo_unit->info_or_types_section =
8670     obstack_alloc (&objfile->objfile_obstack,
8671                    sizeof (struct dwarf2_section_info));
8672   *dwo_unit->info_or_types_section = sections.info_or_types;
8673   /* offset, length, type_offset_in_tu are set later.  */
8674
8675   return dwo_unit;
8676 }
8677
8678 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8679
8680 static struct dwo_unit *
8681 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8682                    const struct dwp_hash_table *htab,
8683                    ULONGEST signature, int is_debug_types)
8684 {
8685   bfd *dbfd = dwp_file->dbfd;
8686   uint32_t mask = htab->nr_slots - 1;
8687   uint32_t hash = signature & mask;
8688   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8689   unsigned int i;
8690   void **slot;
8691   struct dwo_unit find_dwo_cu, *dwo_cu;
8692
8693   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8694   find_dwo_cu.signature = signature;
8695   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8696
8697   if (*slot != NULL)
8698     return *slot;
8699
8700   /* Use a for loop so that we don't loop forever on bad debug info.  */
8701   for (i = 0; i < htab->nr_slots; ++i)
8702     {
8703       ULONGEST signature_in_table;
8704
8705       signature_in_table =
8706         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8707       if (signature_in_table == signature)
8708         {
8709           uint32_t section_index =
8710             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8711
8712           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8713                                      signature, is_debug_types);
8714           return *slot;
8715         }
8716       if (signature_in_table == 0)
8717         return NULL;
8718       hash = (hash + hash2) & mask;
8719     }
8720
8721   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8722            " [in module %s]"),
8723          dwp_file->name);
8724 }
8725
8726 /* Subroutine of open_dwop_file to simplify it.
8727    Open the file specified by FILE_NAME and hand it off to BFD for
8728    preliminary analysis.  Return a newly initialized bfd *, which
8729    includes a canonicalized copy of FILE_NAME.
8730    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8731    In case of trouble, return NULL.
8732    NOTE: This function is derived from symfile_bfd_open.  */
8733
8734 static bfd *
8735 try_open_dwop_file (const char *file_name, int is_dwp)
8736 {
8737   bfd *sym_bfd;
8738   int desc, flags;
8739   char *absolute_name;
8740
8741   flags = OPF_TRY_CWD_FIRST;
8742   if (is_dwp)
8743     flags |= OPF_SEARCH_IN_PATH;
8744   desc = openp (debug_file_directory, flags, file_name,
8745                 O_RDONLY | O_BINARY, &absolute_name);
8746   if (desc < 0)
8747     return NULL;
8748
8749   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8750   if (!sym_bfd)
8751     {
8752       xfree (absolute_name);
8753       return NULL;
8754     }
8755   xfree (absolute_name);
8756   bfd_set_cacheable (sym_bfd, 1);
8757
8758   if (!bfd_check_format (sym_bfd, bfd_object))
8759     {
8760       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8761       return NULL;
8762     }
8763
8764   return sym_bfd;
8765 }
8766
8767 /* Try to open DWO/DWP file FILE_NAME.
8768    COMP_DIR is the DW_AT_comp_dir attribute.
8769    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8770    The result is the bfd handle of the file.
8771    If there is a problem finding or opening the file, return NULL.
8772    Upon success, the canonicalized path of the file is stored in the bfd,
8773    same as symfile_bfd_open.  */
8774
8775 static bfd *
8776 open_dwop_file (const char *file_name, const char *comp_dir, int is_dwp)
8777 {
8778   bfd *abfd;
8779
8780   if (IS_ABSOLUTE_PATH (file_name))
8781     return try_open_dwop_file (file_name, is_dwp);
8782
8783   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8784
8785   if (comp_dir != NULL)
8786     {
8787       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8788
8789       /* NOTE: If comp_dir is a relative path, this will also try the
8790          search path, which seems useful.  */
8791       abfd = try_open_dwop_file (path_to_try, is_dwp);
8792       xfree (path_to_try);
8793       if (abfd != NULL)
8794         return abfd;
8795     }
8796
8797   /* That didn't work, try debug-file-directory, which, despite its name,
8798      is a list of paths.  */
8799
8800   if (*debug_file_directory == '\0')
8801     return NULL;
8802
8803   return try_open_dwop_file (file_name, is_dwp);
8804 }
8805
8806 /* This function is mapped across the sections and remembers the offset and
8807    size of each of the DWO debugging sections we are interested in.  */
8808
8809 static void
8810 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
8811 {
8812   struct dwo_sections *dwo_sections = dwo_sections_ptr;
8813   const struct dwop_section_names *names = &dwop_section_names;
8814
8815   if (section_is_p (sectp->name, &names->abbrev_dwo))
8816     {
8817       dwo_sections->abbrev.asection = sectp;
8818       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
8819     }
8820   else if (section_is_p (sectp->name, &names->info_dwo))
8821     {
8822       dwo_sections->info.asection = sectp;
8823       dwo_sections->info.size = bfd_get_section_size (sectp);
8824     }
8825   else if (section_is_p (sectp->name, &names->line_dwo))
8826     {
8827       dwo_sections->line.asection = sectp;
8828       dwo_sections->line.size = bfd_get_section_size (sectp);
8829     }
8830   else if (section_is_p (sectp->name, &names->loc_dwo))
8831     {
8832       dwo_sections->loc.asection = sectp;
8833       dwo_sections->loc.size = bfd_get_section_size (sectp);
8834     }
8835   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8836     {
8837       dwo_sections->macinfo.asection = sectp;
8838       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
8839     }
8840   else if (section_is_p (sectp->name, &names->macro_dwo))
8841     {
8842       dwo_sections->macro.asection = sectp;
8843       dwo_sections->macro.size = bfd_get_section_size (sectp);
8844     }
8845   else if (section_is_p (sectp->name, &names->str_dwo))
8846     {
8847       dwo_sections->str.asection = sectp;
8848       dwo_sections->str.size = bfd_get_section_size (sectp);
8849     }
8850   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8851     {
8852       dwo_sections->str_offsets.asection = sectp;
8853       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
8854     }
8855   else if (section_is_p (sectp->name, &names->types_dwo))
8856     {
8857       struct dwarf2_section_info type_section;
8858
8859       memset (&type_section, 0, sizeof (type_section));
8860       type_section.asection = sectp;
8861       type_section.size = bfd_get_section_size (sectp);
8862       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
8863                      &type_section);
8864     }
8865 }
8866
8867 /* Initialize the use of the DWO file specified by DWO_NAME.
8868    The result is NULL if DWO_NAME can't be found.  */
8869
8870 static struct dwo_file *
8871 open_and_init_dwo_file (const char *dwo_name, const char *comp_dir)
8872 {
8873   struct objfile *objfile = dwarf2_per_objfile->objfile;
8874   struct dwo_file *dwo_file;
8875   bfd *dbfd;
8876   struct cleanup *cleanups;
8877
8878   dbfd = open_dwop_file (dwo_name, comp_dir, 0);
8879   if (dbfd == NULL)
8880     {
8881       if (dwarf2_read_debug)
8882         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
8883       return NULL;
8884     }
8885   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8886   dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8887                                   dwo_name, strlen (dwo_name));
8888   dwo_file->dbfd = dbfd;
8889
8890   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8891
8892   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
8893
8894   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
8895
8896   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8897                                                  dwo_file->sections.types);
8898
8899   discard_cleanups (cleanups);
8900
8901   if (dwarf2_read_debug)
8902     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
8903
8904   return dwo_file;
8905 }
8906
8907 /* This function is mapped across the sections and remembers the offset and
8908    size of each of the DWP debugging sections we are interested in.  */
8909
8910 static void
8911 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
8912 {
8913   struct dwp_file *dwp_file = dwp_file_ptr;
8914   const struct dwop_section_names *names = &dwop_section_names;
8915   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
8916
8917   /* Record the ELF section number for later lookup: this is what the
8918      .debug_cu_index,.debug_tu_index tables use.  */
8919   gdb_assert (elf_section_nr < dwp_file->num_sections);
8920   dwp_file->elf_sections[elf_section_nr] = sectp;
8921
8922   /* Look for specific sections that we need.  */
8923   if (section_is_p (sectp->name, &names->str_dwo))
8924     {
8925       dwp_file->sections.str.asection = sectp;
8926       dwp_file->sections.str.size = bfd_get_section_size (sectp);
8927     }
8928   else if (section_is_p (sectp->name, &names->cu_index))
8929     {
8930       dwp_file->sections.cu_index.asection = sectp;
8931       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
8932     }
8933   else if (section_is_p (sectp->name, &names->tu_index))
8934     {
8935       dwp_file->sections.tu_index.asection = sectp;
8936       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
8937     }
8938 }
8939
8940 /* Hash function for dwp_file loaded CUs/TUs.  */
8941
8942 static hashval_t
8943 hash_dwp_loaded_cutus (const void *item)
8944 {
8945   const struct dwo_unit *dwo_unit = item;
8946
8947   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
8948   return dwo_unit->signature;
8949 }
8950
8951 /* Equality function for dwp_file loaded CUs/TUs.  */
8952
8953 static int
8954 eq_dwp_loaded_cutus (const void *a, const void *b)
8955 {
8956   const struct dwo_unit *dua = a;
8957   const struct dwo_unit *dub = b;
8958
8959   return dua->signature == dub->signature;
8960 }
8961
8962 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
8963
8964 static htab_t
8965 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
8966 {
8967   return htab_create_alloc_ex (3,
8968                                hash_dwp_loaded_cutus,
8969                                eq_dwp_loaded_cutus,
8970                                NULL,
8971                                &objfile->objfile_obstack,
8972                                hashtab_obstack_allocate,
8973                                dummy_obstack_deallocate);
8974 }
8975
8976 /* Initialize the use of the DWP file for the current objfile.
8977    By convention the name of the DWP file is ${objfile}.dwp.
8978    The result is NULL if it can't be found.  */
8979
8980 static struct dwp_file *
8981 open_and_init_dwp_file (const char *comp_dir)
8982 {
8983   struct objfile *objfile = dwarf2_per_objfile->objfile;
8984   struct dwp_file *dwp_file;
8985   char *dwp_name;
8986   bfd *dbfd;
8987   struct cleanup *cleanups;
8988
8989   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
8990   cleanups = make_cleanup (xfree, dwp_name);
8991
8992   dbfd = open_dwop_file (dwp_name, comp_dir, 1);
8993   if (dbfd == NULL)
8994     {
8995       if (dwarf2_read_debug)
8996         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
8997       do_cleanups (cleanups);
8998       return NULL;
8999     }
9000   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9001   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9002                                   dwp_name, strlen (dwp_name));
9003   dwp_file->dbfd = dbfd;
9004   do_cleanups (cleanups);
9005
9006   cleanups = make_cleanup (free_dwo_file_cleanup, dwp_file);
9007
9008   /* +1: section 0 is unused */
9009   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9010   dwp_file->elf_sections =
9011     OBSTACK_CALLOC (&objfile->objfile_obstack,
9012                     dwp_file->num_sections, asection *);
9013
9014   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9015
9016   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9017
9018   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9019
9020   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9021
9022   discard_cleanups (cleanups);
9023
9024   if (dwarf2_read_debug)
9025     {
9026       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9027       fprintf_unfiltered (gdb_stdlog,
9028                           "    %u CUs, %u TUs\n",
9029                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9030                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9031     }
9032
9033   return dwp_file;
9034 }
9035
9036 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9037    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9038    or in the DWP file for the objfile, referenced by THIS_UNIT.
9039    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9040    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9041
9042    This is called, for example, when wanting to read a variable with a
9043    complex location.  Therefore we don't want to do file i/o for every call.
9044    Therefore we don't want to look for a DWO file on every call.
9045    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9046    then we check if we've already seen DWO_NAME, and only THEN do we check
9047    for a DWO file.
9048
9049    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9050    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9051
9052 static struct dwo_unit *
9053 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9054                  const char *dwo_name, const char *comp_dir,
9055                  ULONGEST signature, int is_debug_types)
9056 {
9057   struct objfile *objfile = dwarf2_per_objfile->objfile;
9058   const char *kind = is_debug_types ? "TU" : "CU";
9059   void **dwo_file_slot;
9060   struct dwo_file *dwo_file;
9061   struct dwp_file *dwp_file;
9062
9063   /* Have we already read SIGNATURE from a DWP file?  */
9064
9065   if (! dwarf2_per_objfile->dwp_checked)
9066     {
9067       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file (comp_dir);
9068       dwarf2_per_objfile->dwp_checked = 1;
9069     }
9070   dwp_file = dwarf2_per_objfile->dwp_file;
9071
9072   if (dwp_file != NULL)
9073     {
9074       const struct dwp_hash_table *dwp_htab =
9075         is_debug_types ? dwp_file->tus : dwp_file->cus;
9076
9077       if (dwp_htab != NULL)
9078         {
9079           struct dwo_unit *dwo_cutu =
9080             lookup_dwo_in_dwp (dwp_file, dwp_htab, signature, is_debug_types);
9081
9082           if (dwo_cutu != NULL)
9083             {
9084               if (dwarf2_read_debug)
9085                 {
9086                   fprintf_unfiltered (gdb_stdlog,
9087                                       "Virtual DWO %s %s found: @%s\n",
9088                                       kind, hex_string (signature),
9089                                       host_address_to_string (dwo_cutu));
9090                 }
9091               return dwo_cutu;
9092             }
9093         }
9094     }
9095
9096   /* Have we already seen DWO_NAME?  */
9097
9098   dwo_file_slot = lookup_dwo_file_slot (dwo_name);
9099   if (*dwo_file_slot == NULL)
9100     {
9101       /* Read in the file and build a table of the DWOs it contains.  */
9102       *dwo_file_slot = open_and_init_dwo_file (dwo_name, comp_dir);
9103     }
9104   /* NOTE: This will be NULL if unable to open the file.  */
9105   dwo_file = *dwo_file_slot;
9106
9107   if (dwo_file != NULL)
9108     {
9109       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9110
9111       if (htab != NULL)
9112         {
9113           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9114
9115           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9116           find_dwo_cutu.signature = signature;
9117           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9118
9119           if (dwo_cutu != NULL)
9120             {
9121               if (dwarf2_read_debug)
9122                 {
9123                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9124                                       kind, dwo_name, hex_string (signature),
9125                                       host_address_to_string (dwo_cutu));
9126                 }
9127               return dwo_cutu;
9128             }
9129         }
9130     }
9131
9132   /* We didn't find it.  This could mean a dwo_id mismatch, or
9133      someone deleted the DWO/DWP file, or the search path isn't set up
9134      correctly to find the file.  */
9135
9136   if (dwarf2_read_debug)
9137     {
9138       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9139                           kind, dwo_name, hex_string (signature));
9140     }
9141
9142   complaint (&symfile_complaints,
9143              _("Could not find DWO CU referenced by CU at offset 0x%x"
9144                " [in module %s]"),
9145              this_unit->offset.sect_off, objfile->name);
9146   return NULL;
9147 }
9148
9149 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9150    See lookup_dwo_cutu_unit for details.  */
9151
9152 static struct dwo_unit *
9153 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9154                       const char *dwo_name, const char *comp_dir,
9155                       ULONGEST signature)
9156 {
9157   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9158 }
9159
9160 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9161    See lookup_dwo_cutu_unit for details.  */
9162
9163 static struct dwo_unit *
9164 lookup_dwo_type_unit (struct signatured_type *this_tu,
9165                       const char *dwo_name, const char *comp_dir)
9166 {
9167   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9168 }
9169
9170 /* Free all resources associated with DWO_FILE.
9171    Close the DWO file and munmap the sections.
9172    All memory should be on the objfile obstack.  */
9173
9174 static void
9175 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9176 {
9177   int ix;
9178   struct dwarf2_section_info *section;
9179
9180   gdb_assert (dwo_file->dbfd != objfile->obfd);
9181   gdb_bfd_unref (dwo_file->dbfd);
9182
9183   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9184 }
9185
9186 /* Wrapper for free_dwo_file for use in cleanups.  */
9187
9188 static void
9189 free_dwo_file_cleanup (void *arg)
9190 {
9191   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9192   struct objfile *objfile = dwarf2_per_objfile->objfile;
9193
9194   free_dwo_file (dwo_file, objfile);
9195 }
9196
9197 /* Traversal function for free_dwo_files.  */
9198
9199 static int
9200 free_dwo_file_from_slot (void **slot, void *info)
9201 {
9202   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9203   struct objfile *objfile = (struct objfile *) info;
9204
9205   free_dwo_file (dwo_file, objfile);
9206
9207   return 1;
9208 }
9209
9210 /* Free all resources associated with DWO_FILES.  */
9211
9212 static void
9213 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9214 {
9215   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9216 }
9217 \f
9218 /* Read in various DIEs.  */
9219
9220 /* qsort helper for inherit_abstract_dies.  */
9221
9222 static int
9223 unsigned_int_compar (const void *ap, const void *bp)
9224 {
9225   unsigned int a = *(unsigned int *) ap;
9226   unsigned int b = *(unsigned int *) bp;
9227
9228   return (a > b) - (b > a);
9229 }
9230
9231 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9232    Inherit only the children of the DW_AT_abstract_origin DIE not being
9233    already referenced by DW_AT_abstract_origin from the children of the
9234    current DIE.  */
9235
9236 static void
9237 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9238 {
9239   struct die_info *child_die;
9240   unsigned die_children_count;
9241   /* CU offsets which were referenced by children of the current DIE.  */
9242   sect_offset *offsets;
9243   sect_offset *offsets_end, *offsetp;
9244   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9245   struct die_info *origin_die;
9246   /* Iterator of the ORIGIN_DIE children.  */
9247   struct die_info *origin_child_die;
9248   struct cleanup *cleanups;
9249   struct attribute *attr;
9250   struct dwarf2_cu *origin_cu;
9251   struct pending **origin_previous_list_in_scope;
9252
9253   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9254   if (!attr)
9255     return;
9256
9257   /* Note that following die references may follow to a die in a
9258      different cu.  */
9259
9260   origin_cu = cu;
9261   origin_die = follow_die_ref (die, attr, &origin_cu);
9262
9263   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9264      symbols in.  */
9265   origin_previous_list_in_scope = origin_cu->list_in_scope;
9266   origin_cu->list_in_scope = cu->list_in_scope;
9267
9268   if (die->tag != origin_die->tag
9269       && !(die->tag == DW_TAG_inlined_subroutine
9270            && origin_die->tag == DW_TAG_subprogram))
9271     complaint (&symfile_complaints,
9272                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9273                die->offset.sect_off, origin_die->offset.sect_off);
9274
9275   child_die = die->child;
9276   die_children_count = 0;
9277   while (child_die && child_die->tag)
9278     {
9279       child_die = sibling_die (child_die);
9280       die_children_count++;
9281     }
9282   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9283   cleanups = make_cleanup (xfree, offsets);
9284
9285   offsets_end = offsets;
9286   child_die = die->child;
9287   while (child_die && child_die->tag)
9288     {
9289       /* For each CHILD_DIE, find the corresponding child of
9290          ORIGIN_DIE.  If there is more than one layer of
9291          DW_AT_abstract_origin, follow them all; there shouldn't be,
9292          but GCC versions at least through 4.4 generate this (GCC PR
9293          40573).  */
9294       struct die_info *child_origin_die = child_die;
9295       struct dwarf2_cu *child_origin_cu = cu;
9296
9297       while (1)
9298         {
9299           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9300                               child_origin_cu);
9301           if (attr == NULL)
9302             break;
9303           child_origin_die = follow_die_ref (child_origin_die, attr,
9304                                              &child_origin_cu);
9305         }
9306
9307       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9308          counterpart may exist.  */
9309       if (child_origin_die != child_die)
9310         {
9311           if (child_die->tag != child_origin_die->tag
9312               && !(child_die->tag == DW_TAG_inlined_subroutine
9313                    && child_origin_die->tag == DW_TAG_subprogram))
9314             complaint (&symfile_complaints,
9315                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9316                          "different tags"), child_die->offset.sect_off,
9317                        child_origin_die->offset.sect_off);
9318           if (child_origin_die->parent != origin_die)
9319             complaint (&symfile_complaints,
9320                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9321                          "different parents"), child_die->offset.sect_off,
9322                        child_origin_die->offset.sect_off);
9323           else
9324             *offsets_end++ = child_origin_die->offset;
9325         }
9326       child_die = sibling_die (child_die);
9327     }
9328   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9329          unsigned_int_compar);
9330   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9331     if (offsetp[-1].sect_off == offsetp->sect_off)
9332       complaint (&symfile_complaints,
9333                  _("Multiple children of DIE 0x%x refer "
9334                    "to DIE 0x%x as their abstract origin"),
9335                  die->offset.sect_off, offsetp->sect_off);
9336
9337   offsetp = offsets;
9338   origin_child_die = origin_die->child;
9339   while (origin_child_die && origin_child_die->tag)
9340     {
9341       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9342       while (offsetp < offsets_end
9343              && offsetp->sect_off < origin_child_die->offset.sect_off)
9344         offsetp++;
9345       if (offsetp >= offsets_end
9346           || offsetp->sect_off > origin_child_die->offset.sect_off)
9347         {
9348           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9349           process_die (origin_child_die, origin_cu);
9350         }
9351       origin_child_die = sibling_die (origin_child_die);
9352     }
9353   origin_cu->list_in_scope = origin_previous_list_in_scope;
9354
9355   do_cleanups (cleanups);
9356 }
9357
9358 static void
9359 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9360 {
9361   struct objfile *objfile = cu->objfile;
9362   struct context_stack *new;
9363   CORE_ADDR lowpc;
9364   CORE_ADDR highpc;
9365   struct die_info *child_die;
9366   struct attribute *attr, *call_line, *call_file;
9367   char *name;
9368   CORE_ADDR baseaddr;
9369   struct block *block;
9370   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9371   VEC (symbolp) *template_args = NULL;
9372   struct template_symbol *templ_func = NULL;
9373
9374   if (inlined_func)
9375     {
9376       /* If we do not have call site information, we can't show the
9377          caller of this inlined function.  That's too confusing, so
9378          only use the scope for local variables.  */
9379       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9380       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9381       if (call_line == NULL || call_file == NULL)
9382         {
9383           read_lexical_block_scope (die, cu);
9384           return;
9385         }
9386     }
9387
9388   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9389
9390   name = dwarf2_name (die, cu);
9391
9392   /* Ignore functions with missing or empty names.  These are actually
9393      illegal according to the DWARF standard.  */
9394   if (name == NULL)
9395     {
9396       complaint (&symfile_complaints,
9397                  _("missing name for subprogram DIE at %d"),
9398                  die->offset.sect_off);
9399       return;
9400     }
9401
9402   /* Ignore functions with missing or invalid low and high pc attributes.  */
9403   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9404     {
9405       attr = dwarf2_attr (die, DW_AT_external, cu);
9406       if (!attr || !DW_UNSND (attr))
9407         complaint (&symfile_complaints,
9408                    _("cannot get low and high bounds "
9409                      "for subprogram DIE at %d"),
9410                    die->offset.sect_off);
9411       return;
9412     }
9413
9414   lowpc += baseaddr;
9415   highpc += baseaddr;
9416
9417   /* If we have any template arguments, then we must allocate a
9418      different sort of symbol.  */
9419   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9420     {
9421       if (child_die->tag == DW_TAG_template_type_param
9422           || child_die->tag == DW_TAG_template_value_param)
9423         {
9424           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9425                                        struct template_symbol);
9426           templ_func->base.is_cplus_template_function = 1;
9427           break;
9428         }
9429     }
9430
9431   new = push_context (0, lowpc);
9432   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9433                                (struct symbol *) templ_func);
9434
9435   /* If there is a location expression for DW_AT_frame_base, record
9436      it.  */
9437   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9438   if (attr)
9439     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
9440        expression is being recorded directly in the function's symbol
9441        and not in a separate frame-base object.  I guess this hack is
9442        to avoid adding some sort of frame-base adjunct/annex to the
9443        function's symbol :-(.  The problem with doing this is that it
9444        results in a function symbol with a location expression that
9445        has nothing to do with the location of the function, ouch!  The
9446        relationship should be: a function's symbol has-a frame base; a
9447        frame-base has-a location expression.  */
9448     dwarf2_symbol_mark_computed (attr, new->name, cu);
9449
9450   cu->list_in_scope = &local_symbols;
9451
9452   if (die->child != NULL)
9453     {
9454       child_die = die->child;
9455       while (child_die && child_die->tag)
9456         {
9457           if (child_die->tag == DW_TAG_template_type_param
9458               || child_die->tag == DW_TAG_template_value_param)
9459             {
9460               struct symbol *arg = new_symbol (child_die, NULL, cu);
9461
9462               if (arg != NULL)
9463                 VEC_safe_push (symbolp, template_args, arg);
9464             }
9465           else
9466             process_die (child_die, cu);
9467           child_die = sibling_die (child_die);
9468         }
9469     }
9470
9471   inherit_abstract_dies (die, cu);
9472
9473   /* If we have a DW_AT_specification, we might need to import using
9474      directives from the context of the specification DIE.  See the
9475      comment in determine_prefix.  */
9476   if (cu->language == language_cplus
9477       && dwarf2_attr (die, DW_AT_specification, cu))
9478     {
9479       struct dwarf2_cu *spec_cu = cu;
9480       struct die_info *spec_die = die_specification (die, &spec_cu);
9481
9482       while (spec_die)
9483         {
9484           child_die = spec_die->child;
9485           while (child_die && child_die->tag)
9486             {
9487               if (child_die->tag == DW_TAG_imported_module)
9488                 process_die (child_die, spec_cu);
9489               child_die = sibling_die (child_die);
9490             }
9491
9492           /* In some cases, GCC generates specification DIEs that
9493              themselves contain DW_AT_specification attributes.  */
9494           spec_die = die_specification (spec_die, &spec_cu);
9495         }
9496     }
9497
9498   new = pop_context ();
9499   /* Make a block for the local symbols within.  */
9500   block = finish_block (new->name, &local_symbols, new->old_blocks,
9501                         lowpc, highpc, objfile);
9502
9503   /* For C++, set the block's scope.  */
9504   if (cu->language == language_cplus || cu->language == language_fortran)
9505     cp_set_block_scope (new->name, block, &objfile->objfile_obstack,
9506                         determine_prefix (die, cu),
9507                         processing_has_namespace_info);
9508
9509   /* If we have address ranges, record them.  */
9510   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9511
9512   /* Attach template arguments to function.  */
9513   if (! VEC_empty (symbolp, template_args))
9514     {
9515       gdb_assert (templ_func != NULL);
9516
9517       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9518       templ_func->template_arguments
9519         = obstack_alloc (&objfile->objfile_obstack,
9520                          (templ_func->n_template_arguments
9521                           * sizeof (struct symbol *)));
9522       memcpy (templ_func->template_arguments,
9523               VEC_address (symbolp, template_args),
9524               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9525       VEC_free (symbolp, template_args);
9526     }
9527
9528   /* In C++, we can have functions nested inside functions (e.g., when
9529      a function declares a class that has methods).  This means that
9530      when we finish processing a function scope, we may need to go
9531      back to building a containing block's symbol lists.  */
9532   local_symbols = new->locals;
9533   using_directives = new->using_directives;
9534
9535   /* If we've finished processing a top-level function, subsequent
9536      symbols go in the file symbol list.  */
9537   if (outermost_context_p ())
9538     cu->list_in_scope = &file_symbols;
9539 }
9540
9541 /* Process all the DIES contained within a lexical block scope.  Start
9542    a new scope, process the dies, and then close the scope.  */
9543
9544 static void
9545 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9546 {
9547   struct objfile *objfile = cu->objfile;
9548   struct context_stack *new;
9549   CORE_ADDR lowpc, highpc;
9550   struct die_info *child_die;
9551   CORE_ADDR baseaddr;
9552
9553   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9554
9555   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9556   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9557      as multiple lexical blocks?  Handling children in a sane way would
9558      be nasty.  Might be easier to properly extend generic blocks to
9559      describe ranges.  */
9560   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9561     return;
9562   lowpc += baseaddr;
9563   highpc += baseaddr;
9564
9565   push_context (0, lowpc);
9566   if (die->child != NULL)
9567     {
9568       child_die = die->child;
9569       while (child_die && child_die->tag)
9570         {
9571           process_die (child_die, cu);
9572           child_die = sibling_die (child_die);
9573         }
9574     }
9575   new = pop_context ();
9576
9577   if (local_symbols != NULL || using_directives != NULL)
9578     {
9579       struct block *block
9580         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9581                         highpc, objfile);
9582
9583       /* Note that recording ranges after traversing children, as we
9584          do here, means that recording a parent's ranges entails
9585          walking across all its children's ranges as they appear in
9586          the address map, which is quadratic behavior.
9587
9588          It would be nicer to record the parent's ranges before
9589          traversing its children, simply overriding whatever you find
9590          there.  But since we don't even decide whether to create a
9591          block until after we've traversed its children, that's hard
9592          to do.  */
9593       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9594     }
9595   local_symbols = new->locals;
9596   using_directives = new->using_directives;
9597 }
9598
9599 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9600
9601 static void
9602 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9603 {
9604   struct objfile *objfile = cu->objfile;
9605   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9606   CORE_ADDR pc, baseaddr;
9607   struct attribute *attr;
9608   struct call_site *call_site, call_site_local;
9609   void **slot;
9610   int nparams;
9611   struct die_info *child_die;
9612
9613   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9614
9615   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9616   if (!attr)
9617     {
9618       complaint (&symfile_complaints,
9619                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9620                    "DIE 0x%x [in module %s]"),
9621                  die->offset.sect_off, objfile->name);
9622       return;
9623     }
9624   pc = DW_ADDR (attr) + baseaddr;
9625
9626   if (cu->call_site_htab == NULL)
9627     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9628                                                NULL, &objfile->objfile_obstack,
9629                                                hashtab_obstack_allocate, NULL);
9630   call_site_local.pc = pc;
9631   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9632   if (*slot != NULL)
9633     {
9634       complaint (&symfile_complaints,
9635                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9636                    "DIE 0x%x [in module %s]"),
9637                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9638       return;
9639     }
9640
9641   /* Count parameters at the caller.  */
9642
9643   nparams = 0;
9644   for (child_die = die->child; child_die && child_die->tag;
9645        child_die = sibling_die (child_die))
9646     {
9647       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9648         {
9649           complaint (&symfile_complaints,
9650                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9651                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9652                      child_die->tag, child_die->offset.sect_off, objfile->name);
9653           continue;
9654         }
9655
9656       nparams++;
9657     }
9658
9659   call_site = obstack_alloc (&objfile->objfile_obstack,
9660                              (sizeof (*call_site)
9661                               + (sizeof (*call_site->parameter)
9662                                  * (nparams - 1))));
9663   *slot = call_site;
9664   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9665   call_site->pc = pc;
9666
9667   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9668     {
9669       struct die_info *func_die;
9670
9671       /* Skip also over DW_TAG_inlined_subroutine.  */
9672       for (func_die = die->parent;
9673            func_die && func_die->tag != DW_TAG_subprogram
9674            && func_die->tag != DW_TAG_subroutine_type;
9675            func_die = func_die->parent);
9676
9677       /* DW_AT_GNU_all_call_sites is a superset
9678          of DW_AT_GNU_all_tail_call_sites.  */
9679       if (func_die
9680           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9681           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9682         {
9683           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9684              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9685              both the initial caller containing the real return address PC and
9686              the final callee containing the current PC of a chain of tail
9687              calls do not need to have the tail call list complete.  But any
9688              function candidate for a virtual tail call frame searched via
9689              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9690              determined unambiguously.  */
9691         }
9692       else
9693         {
9694           struct type *func_type = NULL;
9695
9696           if (func_die)
9697             func_type = get_die_type (func_die, cu);
9698           if (func_type != NULL)
9699             {
9700               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9701
9702               /* Enlist this call site to the function.  */
9703               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9704               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9705             }
9706           else
9707             complaint (&symfile_complaints,
9708                        _("Cannot find function owning DW_TAG_GNU_call_site "
9709                          "DIE 0x%x [in module %s]"),
9710                        die->offset.sect_off, objfile->name);
9711         }
9712     }
9713
9714   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9715   if (attr == NULL)
9716     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9717   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9718   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9719     /* Keep NULL DWARF_BLOCK.  */;
9720   else if (attr_form_is_block (attr))
9721     {
9722       struct dwarf2_locexpr_baton *dlbaton;
9723
9724       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9725       dlbaton->data = DW_BLOCK (attr)->data;
9726       dlbaton->size = DW_BLOCK (attr)->size;
9727       dlbaton->per_cu = cu->per_cu;
9728
9729       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9730     }
9731   else if (is_ref_attr (attr))
9732     {
9733       struct dwarf2_cu *target_cu = cu;
9734       struct die_info *target_die;
9735
9736       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9737       gdb_assert (target_cu->objfile == objfile);
9738       if (die_is_declaration (target_die, target_cu))
9739         {
9740           const char *target_physname;
9741
9742           target_physname = dwarf2_physname (NULL, target_die, target_cu);
9743           if (target_physname == NULL)
9744             complaint (&symfile_complaints,
9745                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9746                          "physname, for referencing DIE 0x%x [in module %s]"),
9747                        die->offset.sect_off, objfile->name);
9748           else
9749             SET_FIELD_PHYSNAME (call_site->target, (char *) target_physname);
9750         }
9751       else
9752         {
9753           CORE_ADDR lowpc;
9754
9755           /* DW_AT_entry_pc should be preferred.  */
9756           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9757             complaint (&symfile_complaints,
9758                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9759                          "low pc, for referencing DIE 0x%x [in module %s]"),
9760                        die->offset.sect_off, objfile->name);
9761           else
9762             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9763         }
9764     }
9765   else
9766     complaint (&symfile_complaints,
9767                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9768                  "block nor reference, for DIE 0x%x [in module %s]"),
9769                die->offset.sect_off, objfile->name);
9770
9771   call_site->per_cu = cu->per_cu;
9772
9773   for (child_die = die->child;
9774        child_die && child_die->tag;
9775        child_die = sibling_die (child_die))
9776     {
9777       struct call_site_parameter *parameter;
9778       struct attribute *loc, *origin;
9779
9780       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9781         {
9782           /* Already printed the complaint above.  */
9783           continue;
9784         }
9785
9786       gdb_assert (call_site->parameter_count < nparams);
9787       parameter = &call_site->parameter[call_site->parameter_count];
9788
9789       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
9790          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
9791          register is contained in DW_AT_GNU_call_site_value.  */
9792
9793       loc = dwarf2_attr (child_die, DW_AT_location, cu);
9794       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
9795       if (loc == NULL && origin != NULL && is_ref_attr (origin))
9796         {
9797           sect_offset offset;
9798
9799           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
9800           offset = dwarf2_get_ref_die_offset (origin);
9801           if (!offset_in_cu_p (&cu->header, offset))
9802             {
9803               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
9804                  binding can be done only inside one CU.  Such referenced DIE
9805                  therefore cannot be even moved to DW_TAG_partial_unit.  */
9806               complaint (&symfile_complaints,
9807                          _("DW_AT_abstract_origin offset is not in CU for "
9808                            "DW_TAG_GNU_call_site child DIE 0x%x "
9809                            "[in module %s]"),
9810                          child_die->offset.sect_off, objfile->name);
9811               continue;
9812             }
9813           parameter->u.param_offset.cu_off = (offset.sect_off
9814                                               - cu->header.offset.sect_off);
9815         }
9816       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
9817         {
9818           complaint (&symfile_complaints,
9819                      _("No DW_FORM_block* DW_AT_location for "
9820                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9821                      child_die->offset.sect_off, objfile->name);
9822           continue;
9823         }
9824       else
9825         {
9826           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
9827             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
9828           if (parameter->u.dwarf_reg != -1)
9829             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
9830           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
9831                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
9832                                              &parameter->u.fb_offset))
9833             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
9834           else
9835             {
9836               complaint (&symfile_complaints,
9837                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
9838                            "for DW_FORM_block* DW_AT_location is supported for "
9839                            "DW_TAG_GNU_call_site child DIE 0x%x "
9840                            "[in module %s]"),
9841                          child_die->offset.sect_off, objfile->name);
9842               continue;
9843             }
9844         }
9845
9846       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
9847       if (!attr_form_is_block (attr))
9848         {
9849           complaint (&symfile_complaints,
9850                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
9851                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9852                      child_die->offset.sect_off, objfile->name);
9853           continue;
9854         }
9855       parameter->value = DW_BLOCK (attr)->data;
9856       parameter->value_size = DW_BLOCK (attr)->size;
9857
9858       /* Parameters are not pre-cleared by memset above.  */
9859       parameter->data_value = NULL;
9860       parameter->data_value_size = 0;
9861       call_site->parameter_count++;
9862
9863       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
9864       if (attr)
9865         {
9866           if (!attr_form_is_block (attr))
9867             complaint (&symfile_complaints,
9868                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
9869                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9870                        child_die->offset.sect_off, objfile->name);
9871           else
9872             {
9873               parameter->data_value = DW_BLOCK (attr)->data;
9874               parameter->data_value_size = DW_BLOCK (attr)->size;
9875             }
9876         }
9877     }
9878 }
9879
9880 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
9881    Return 1 if the attributes are present and valid, otherwise, return 0.
9882    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
9883
9884 static int
9885 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
9886                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
9887                     struct partial_symtab *ranges_pst)
9888 {
9889   struct objfile *objfile = cu->objfile;
9890   struct comp_unit_head *cu_header = &cu->header;
9891   bfd *obfd = objfile->obfd;
9892   unsigned int addr_size = cu_header->addr_size;
9893   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9894   /* Base address selection entry.  */
9895   CORE_ADDR base;
9896   int found_base;
9897   unsigned int dummy;
9898   gdb_byte *buffer;
9899   CORE_ADDR marker;
9900   int low_set;
9901   CORE_ADDR low = 0;
9902   CORE_ADDR high = 0;
9903   CORE_ADDR baseaddr;
9904
9905   found_base = cu->base_known;
9906   base = cu->base_address;
9907
9908   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
9909   if (offset >= dwarf2_per_objfile->ranges.size)
9910     {
9911       complaint (&symfile_complaints,
9912                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
9913                  offset);
9914       return 0;
9915     }
9916   buffer = dwarf2_per_objfile->ranges.buffer + offset;
9917
9918   /* Read in the largest possible address.  */
9919   marker = read_address (obfd, buffer, cu, &dummy);
9920   if ((marker & mask) == mask)
9921     {
9922       /* If we found the largest possible address, then
9923          read the base address.  */
9924       base = read_address (obfd, buffer + addr_size, cu, &dummy);
9925       buffer += 2 * addr_size;
9926       offset += 2 * addr_size;
9927       found_base = 1;
9928     }
9929
9930   low_set = 0;
9931
9932   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9933
9934   while (1)
9935     {
9936       CORE_ADDR range_beginning, range_end;
9937
9938       range_beginning = read_address (obfd, buffer, cu, &dummy);
9939       buffer += addr_size;
9940       range_end = read_address (obfd, buffer, cu, &dummy);
9941       buffer += addr_size;
9942       offset += 2 * addr_size;
9943
9944       /* An end of list marker is a pair of zero addresses.  */
9945       if (range_beginning == 0 && range_end == 0)
9946         /* Found the end of list entry.  */
9947         break;
9948
9949       /* Each base address selection entry is a pair of 2 values.
9950          The first is the largest possible address, the second is
9951          the base address.  Check for a base address here.  */
9952       if ((range_beginning & mask) == mask)
9953         {
9954           /* If we found the largest possible address, then
9955              read the base address.  */
9956           base = read_address (obfd, buffer + addr_size, cu, &dummy);
9957           found_base = 1;
9958           continue;
9959         }
9960
9961       if (!found_base)
9962         {
9963           /* We have no valid base address for the ranges
9964              data.  */
9965           complaint (&symfile_complaints,
9966                      _("Invalid .debug_ranges data (no base address)"));
9967           return 0;
9968         }
9969
9970       if (range_beginning > range_end)
9971         {
9972           /* Inverted range entries are invalid.  */
9973           complaint (&symfile_complaints,
9974                      _("Invalid .debug_ranges data (inverted range)"));
9975           return 0;
9976         }
9977
9978       /* Empty range entries have no effect.  */
9979       if (range_beginning == range_end)
9980         continue;
9981
9982       range_beginning += base;
9983       range_end += base;
9984
9985       /* A not-uncommon case of bad debug info.
9986          Don't pollute the addrmap with bad data.  */
9987       if (range_beginning + baseaddr == 0
9988           && !dwarf2_per_objfile->has_section_at_zero)
9989         {
9990           complaint (&symfile_complaints,
9991                      _(".debug_ranges entry has start address of zero"
9992                        " [in module %s]"), objfile->name);
9993           continue;
9994         }
9995
9996       if (ranges_pst != NULL)
9997         addrmap_set_empty (objfile->psymtabs_addrmap,
9998                            range_beginning + baseaddr,
9999                            range_end - 1 + baseaddr,
10000                            ranges_pst);
10001
10002       /* FIXME: This is recording everything as a low-high
10003          segment of consecutive addresses.  We should have a
10004          data structure for discontiguous block ranges
10005          instead.  */
10006       if (! low_set)
10007         {
10008           low = range_beginning;
10009           high = range_end;
10010           low_set = 1;
10011         }
10012       else
10013         {
10014           if (range_beginning < low)
10015             low = range_beginning;
10016           if (range_end > high)
10017             high = range_end;
10018         }
10019     }
10020
10021   if (! low_set)
10022     /* If the first entry is an end-of-list marker, the range
10023        describes an empty scope, i.e. no instructions.  */
10024     return 0;
10025
10026   if (low_return)
10027     *low_return = low;
10028   if (high_return)
10029     *high_return = high;
10030   return 1;
10031 }
10032
10033 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10034    are present and valid, otherwise, return 0.  Return -1 if the range is
10035    discontinuous, i.e. derived from DW_AT_ranges information.  */
10036
10037 static int
10038 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10039                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10040                       struct partial_symtab *pst)
10041 {
10042   struct attribute *attr;
10043   struct attribute *attr_high;
10044   CORE_ADDR low = 0;
10045   CORE_ADDR high = 0;
10046   int ret = 0;
10047
10048   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10049   if (attr_high)
10050     {
10051       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10052       if (attr)
10053         {
10054           low = DW_ADDR (attr);
10055           if (attr_high->form == DW_FORM_addr
10056               || attr_high->form == DW_FORM_GNU_addr_index)
10057             high = DW_ADDR (attr_high);
10058           else
10059             high = low + DW_UNSND (attr_high);
10060         }
10061       else
10062         /* Found high w/o low attribute.  */
10063         return 0;
10064
10065       /* Found consecutive range of addresses.  */
10066       ret = 1;
10067     }
10068   else
10069     {
10070       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10071       if (attr != NULL)
10072         {
10073           unsigned int ranges_offset = DW_UNSND (attr) + cu->ranges_base;
10074
10075           /* Value of the DW_AT_ranges attribute is the offset in the
10076              .debug_ranges section.  */
10077           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10078             return 0;
10079           /* Found discontinuous range of addresses.  */
10080           ret = -1;
10081         }
10082     }
10083
10084   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10085   if (high <= low)
10086     return 0;
10087
10088   /* When using the GNU linker, .gnu.linkonce. sections are used to
10089      eliminate duplicate copies of functions and vtables and such.
10090      The linker will arbitrarily choose one and discard the others.
10091      The AT_*_pc values for such functions refer to local labels in
10092      these sections.  If the section from that file was discarded, the
10093      labels are not in the output, so the relocs get a value of 0.
10094      If this is a discarded function, mark the pc bounds as invalid,
10095      so that GDB will ignore it.  */
10096   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10097     return 0;
10098
10099   *lowpc = low;
10100   if (highpc)
10101     *highpc = high;
10102   return ret;
10103 }
10104
10105 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10106    its low and high PC addresses.  Do nothing if these addresses could not
10107    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10108    and HIGHPC to the high address if greater than HIGHPC.  */
10109
10110 static void
10111 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10112                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10113                                  struct dwarf2_cu *cu)
10114 {
10115   CORE_ADDR low, high;
10116   struct die_info *child = die->child;
10117
10118   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10119     {
10120       *lowpc = min (*lowpc, low);
10121       *highpc = max (*highpc, high);
10122     }
10123
10124   /* If the language does not allow nested subprograms (either inside
10125      subprograms or lexical blocks), we're done.  */
10126   if (cu->language != language_ada)
10127     return;
10128
10129   /* Check all the children of the given DIE.  If it contains nested
10130      subprograms, then check their pc bounds.  Likewise, we need to
10131      check lexical blocks as well, as they may also contain subprogram
10132      definitions.  */
10133   while (child && child->tag)
10134     {
10135       if (child->tag == DW_TAG_subprogram
10136           || child->tag == DW_TAG_lexical_block)
10137         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10138       child = sibling_die (child);
10139     }
10140 }
10141
10142 /* Get the low and high pc's represented by the scope DIE, and store
10143    them in *LOWPC and *HIGHPC.  If the correct values can't be
10144    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10145
10146 static void
10147 get_scope_pc_bounds (struct die_info *die,
10148                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10149                      struct dwarf2_cu *cu)
10150 {
10151   CORE_ADDR best_low = (CORE_ADDR) -1;
10152   CORE_ADDR best_high = (CORE_ADDR) 0;
10153   CORE_ADDR current_low, current_high;
10154
10155   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10156     {
10157       best_low = current_low;
10158       best_high = current_high;
10159     }
10160   else
10161     {
10162       struct die_info *child = die->child;
10163
10164       while (child && child->tag)
10165         {
10166           switch (child->tag) {
10167           case DW_TAG_subprogram:
10168             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10169             break;
10170           case DW_TAG_namespace:
10171           case DW_TAG_module:
10172             /* FIXME: carlton/2004-01-16: Should we do this for
10173                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10174                that current GCC's always emit the DIEs corresponding
10175                to definitions of methods of classes as children of a
10176                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10177                the DIEs giving the declarations, which could be
10178                anywhere).  But I don't see any reason why the
10179                standards says that they have to be there.  */
10180             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10181
10182             if (current_low != ((CORE_ADDR) -1))
10183               {
10184                 best_low = min (best_low, current_low);
10185                 best_high = max (best_high, current_high);
10186               }
10187             break;
10188           default:
10189             /* Ignore.  */
10190             break;
10191           }
10192
10193           child = sibling_die (child);
10194         }
10195     }
10196
10197   *lowpc = best_low;
10198   *highpc = best_high;
10199 }
10200
10201 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10202    in DIE.  */
10203
10204 static void
10205 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10206                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10207 {
10208   struct objfile *objfile = cu->objfile;
10209   struct attribute *attr;
10210   struct attribute *attr_high;
10211
10212   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10213   if (attr_high)
10214     {
10215       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10216       if (attr)
10217         {
10218           CORE_ADDR low = DW_ADDR (attr);
10219           CORE_ADDR high;
10220           if (attr_high->form == DW_FORM_addr
10221               || attr_high->form == DW_FORM_GNU_addr_index)
10222             high = DW_ADDR (attr_high);
10223           else
10224             high = low + DW_UNSND (attr_high);
10225
10226           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10227         }
10228     }
10229
10230   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10231   if (attr)
10232     {
10233       bfd *obfd = objfile->obfd;
10234
10235       /* The value of the DW_AT_ranges attribute is the offset of the
10236          address range list in the .debug_ranges section.  */
10237       unsigned long offset = DW_UNSND (attr) + cu->ranges_base;
10238       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10239
10240       /* For some target architectures, but not others, the
10241          read_address function sign-extends the addresses it returns.
10242          To recognize base address selection entries, we need a
10243          mask.  */
10244       unsigned int addr_size = cu->header.addr_size;
10245       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10246
10247       /* The base address, to which the next pair is relative.  Note
10248          that this 'base' is a DWARF concept: most entries in a range
10249          list are relative, to reduce the number of relocs against the
10250          debugging information.  This is separate from this function's
10251          'baseaddr' argument, which GDB uses to relocate debugging
10252          information from a shared library based on the address at
10253          which the library was loaded.  */
10254       CORE_ADDR base = cu->base_address;
10255       int base_known = cu->base_known;
10256
10257       gdb_assert (dwarf2_per_objfile->ranges.readin);
10258       if (offset >= dwarf2_per_objfile->ranges.size)
10259         {
10260           complaint (&symfile_complaints,
10261                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10262                      offset);
10263           return;
10264         }
10265
10266       for (;;)
10267         {
10268           unsigned int bytes_read;
10269           CORE_ADDR start, end;
10270
10271           start = read_address (obfd, buffer, cu, &bytes_read);
10272           buffer += bytes_read;
10273           end = read_address (obfd, buffer, cu, &bytes_read);
10274           buffer += bytes_read;
10275
10276           /* Did we find the end of the range list?  */
10277           if (start == 0 && end == 0)
10278             break;
10279
10280           /* Did we find a base address selection entry?  */
10281           else if ((start & base_select_mask) == base_select_mask)
10282             {
10283               base = end;
10284               base_known = 1;
10285             }
10286
10287           /* We found an ordinary address range.  */
10288           else
10289             {
10290               if (!base_known)
10291                 {
10292                   complaint (&symfile_complaints,
10293                              _("Invalid .debug_ranges data "
10294                                "(no base address)"));
10295                   return;
10296                 }
10297
10298               if (start > end)
10299                 {
10300                   /* Inverted range entries are invalid.  */
10301                   complaint (&symfile_complaints,
10302                              _("Invalid .debug_ranges data "
10303                                "(inverted range)"));
10304                   return;
10305                 }
10306
10307               /* Empty range entries have no effect.  */
10308               if (start == end)
10309                 continue;
10310
10311               start += base + baseaddr;
10312               end += base + baseaddr;
10313
10314               /* A not-uncommon case of bad debug info.
10315                  Don't pollute the addrmap with bad data.  */
10316               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10317                 {
10318                   complaint (&symfile_complaints,
10319                              _(".debug_ranges entry has start address of zero"
10320                                " [in module %s]"), objfile->name);
10321                   continue;
10322                 }
10323
10324               record_block_range (block, start, end - 1);
10325             }
10326         }
10327     }
10328 }
10329
10330 /* Check whether the producer field indicates either of GCC < 4.6, or the
10331    Intel C/C++ compiler, and cache the result in CU.  */
10332
10333 static void
10334 check_producer (struct dwarf2_cu *cu)
10335 {
10336   const char *cs;
10337   int major, minor, release;
10338
10339   if (cu->producer == NULL)
10340     {
10341       /* For unknown compilers expect their behavior is DWARF version
10342          compliant.
10343
10344          GCC started to support .debug_types sections by -gdwarf-4 since
10345          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10346          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10347          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10348          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10349     }
10350   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10351     {
10352       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10353
10354       cs = &cu->producer[strlen ("GNU ")];
10355       while (*cs && !isdigit (*cs))
10356         cs++;
10357       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10358         {
10359           /* Not recognized as GCC.  */
10360         }
10361       else
10362         cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10363     }
10364   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10365     cu->producer_is_icc = 1;
10366   else
10367     {
10368       /* For other non-GCC compilers, expect their behavior is DWARF version
10369          compliant.  */
10370     }
10371
10372   cu->checked_producer = 1;
10373 }
10374
10375 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10376    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10377    during 4.6.0 experimental.  */
10378
10379 static int
10380 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10381 {
10382   if (!cu->checked_producer)
10383     check_producer (cu);
10384
10385   return cu->producer_is_gxx_lt_4_6;
10386 }
10387
10388 /* Return the default accessibility type if it is not overriden by
10389    DW_AT_accessibility.  */
10390
10391 static enum dwarf_access_attribute
10392 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10393 {
10394   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10395     {
10396       /* The default DWARF 2 accessibility for members is public, the default
10397          accessibility for inheritance is private.  */
10398
10399       if (die->tag != DW_TAG_inheritance)
10400         return DW_ACCESS_public;
10401       else
10402         return DW_ACCESS_private;
10403     }
10404   else
10405     {
10406       /* DWARF 3+ defines the default accessibility a different way.  The same
10407          rules apply now for DW_TAG_inheritance as for the members and it only
10408          depends on the container kind.  */
10409
10410       if (die->parent->tag == DW_TAG_class_type)
10411         return DW_ACCESS_private;
10412       else
10413         return DW_ACCESS_public;
10414     }
10415 }
10416
10417 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10418    offset.  If the attribute was not found return 0, otherwise return
10419    1.  If it was found but could not properly be handled, set *OFFSET
10420    to 0.  */
10421
10422 static int
10423 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10424                              LONGEST *offset)
10425 {
10426   struct attribute *attr;
10427
10428   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10429   if (attr != NULL)
10430     {
10431       *offset = 0;
10432
10433       /* Note that we do not check for a section offset first here.
10434          This is because DW_AT_data_member_location is new in DWARF 4,
10435          so if we see it, we can assume that a constant form is really
10436          a constant and not a section offset.  */
10437       if (attr_form_is_constant (attr))
10438         *offset = dwarf2_get_attr_constant_value (attr, 0);
10439       else if (attr_form_is_section_offset (attr))
10440         dwarf2_complex_location_expr_complaint ();
10441       else if (attr_form_is_block (attr))
10442         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10443       else
10444         dwarf2_complex_location_expr_complaint ();
10445
10446       return 1;
10447     }
10448
10449   return 0;
10450 }
10451
10452 /* Add an aggregate field to the field list.  */
10453
10454 static void
10455 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10456                   struct dwarf2_cu *cu)
10457 {
10458   struct objfile *objfile = cu->objfile;
10459   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10460   struct nextfield *new_field;
10461   struct attribute *attr;
10462   struct field *fp;
10463   char *fieldname = "";
10464
10465   /* Allocate a new field list entry and link it in.  */
10466   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10467   make_cleanup (xfree, new_field);
10468   memset (new_field, 0, sizeof (struct nextfield));
10469
10470   if (die->tag == DW_TAG_inheritance)
10471     {
10472       new_field->next = fip->baseclasses;
10473       fip->baseclasses = new_field;
10474     }
10475   else
10476     {
10477       new_field->next = fip->fields;
10478       fip->fields = new_field;
10479     }
10480   fip->nfields++;
10481
10482   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10483   if (attr)
10484     new_field->accessibility = DW_UNSND (attr);
10485   else
10486     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10487   if (new_field->accessibility != DW_ACCESS_public)
10488     fip->non_public_fields = 1;
10489
10490   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10491   if (attr)
10492     new_field->virtuality = DW_UNSND (attr);
10493   else
10494     new_field->virtuality = DW_VIRTUALITY_none;
10495
10496   fp = &new_field->field;
10497
10498   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10499     {
10500       LONGEST offset;
10501
10502       /* Data member other than a C++ static data member.  */
10503
10504       /* Get type of field.  */
10505       fp->type = die_type (die, cu);
10506
10507       SET_FIELD_BITPOS (*fp, 0);
10508
10509       /* Get bit size of field (zero if none).  */
10510       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10511       if (attr)
10512         {
10513           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10514         }
10515       else
10516         {
10517           FIELD_BITSIZE (*fp) = 0;
10518         }
10519
10520       /* Get bit offset of field.  */
10521       if (handle_data_member_location (die, cu, &offset))
10522         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10523       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10524       if (attr)
10525         {
10526           if (gdbarch_bits_big_endian (gdbarch))
10527             {
10528               /* For big endian bits, the DW_AT_bit_offset gives the
10529                  additional bit offset from the MSB of the containing
10530                  anonymous object to the MSB of the field.  We don't
10531                  have to do anything special since we don't need to
10532                  know the size of the anonymous object.  */
10533               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10534             }
10535           else
10536             {
10537               /* For little endian bits, compute the bit offset to the
10538                  MSB of the anonymous object, subtract off the number of
10539                  bits from the MSB of the field to the MSB of the
10540                  object, and then subtract off the number of bits of
10541                  the field itself.  The result is the bit offset of
10542                  the LSB of the field.  */
10543               int anonymous_size;
10544               int bit_offset = DW_UNSND (attr);
10545
10546               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10547               if (attr)
10548                 {
10549                   /* The size of the anonymous object containing
10550                      the bit field is explicit, so use the
10551                      indicated size (in bytes).  */
10552                   anonymous_size = DW_UNSND (attr);
10553                 }
10554               else
10555                 {
10556                   /* The size of the anonymous object containing
10557                      the bit field must be inferred from the type
10558                      attribute of the data member containing the
10559                      bit field.  */
10560                   anonymous_size = TYPE_LENGTH (fp->type);
10561                 }
10562               SET_FIELD_BITPOS (*fp,
10563                                 (FIELD_BITPOS (*fp)
10564                                  + anonymous_size * bits_per_byte
10565                                  - bit_offset - FIELD_BITSIZE (*fp)));
10566             }
10567         }
10568
10569       /* Get name of field.  */
10570       fieldname = dwarf2_name (die, cu);
10571       if (fieldname == NULL)
10572         fieldname = "";
10573
10574       /* The name is already allocated along with this objfile, so we don't
10575          need to duplicate it for the type.  */
10576       fp->name = fieldname;
10577
10578       /* Change accessibility for artificial fields (e.g. virtual table
10579          pointer or virtual base class pointer) to private.  */
10580       if (dwarf2_attr (die, DW_AT_artificial, cu))
10581         {
10582           FIELD_ARTIFICIAL (*fp) = 1;
10583           new_field->accessibility = DW_ACCESS_private;
10584           fip->non_public_fields = 1;
10585         }
10586     }
10587   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10588     {
10589       /* C++ static member.  */
10590
10591       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10592          is a declaration, but all versions of G++ as of this writing
10593          (so through at least 3.2.1) incorrectly generate
10594          DW_TAG_variable tags.  */
10595
10596       const char *physname;
10597
10598       /* Get name of field.  */
10599       fieldname = dwarf2_name (die, cu);
10600       if (fieldname == NULL)
10601         return;
10602
10603       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10604       if (attr
10605           /* Only create a symbol if this is an external value.
10606              new_symbol checks this and puts the value in the global symbol
10607              table, which we want.  If it is not external, new_symbol
10608              will try to put the value in cu->list_in_scope which is wrong.  */
10609           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10610         {
10611           /* A static const member, not much different than an enum as far as
10612              we're concerned, except that we can support more types.  */
10613           new_symbol (die, NULL, cu);
10614         }
10615
10616       /* Get physical name.  */
10617       physname = dwarf2_physname (fieldname, die, cu);
10618
10619       /* The name is already allocated along with this objfile, so we don't
10620          need to duplicate it for the type.  */
10621       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10622       FIELD_TYPE (*fp) = die_type (die, cu);
10623       FIELD_NAME (*fp) = fieldname;
10624     }
10625   else if (die->tag == DW_TAG_inheritance)
10626     {
10627       LONGEST offset;
10628
10629       /* C++ base class field.  */
10630       if (handle_data_member_location (die, cu, &offset))
10631         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10632       FIELD_BITSIZE (*fp) = 0;
10633       FIELD_TYPE (*fp) = die_type (die, cu);
10634       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10635       fip->nbaseclasses++;
10636     }
10637 }
10638
10639 /* Add a typedef defined in the scope of the FIP's class.  */
10640
10641 static void
10642 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10643                     struct dwarf2_cu *cu)
10644 {
10645   struct objfile *objfile = cu->objfile;
10646   struct typedef_field_list *new_field;
10647   struct attribute *attr;
10648   struct typedef_field *fp;
10649   char *fieldname = "";
10650
10651   /* Allocate a new field list entry and link it in.  */
10652   new_field = xzalloc (sizeof (*new_field));
10653   make_cleanup (xfree, new_field);
10654
10655   gdb_assert (die->tag == DW_TAG_typedef);
10656
10657   fp = &new_field->field;
10658
10659   /* Get name of field.  */
10660   fp->name = dwarf2_name (die, cu);
10661   if (fp->name == NULL)
10662     return;
10663
10664   fp->type = read_type_die (die, cu);
10665
10666   new_field->next = fip->typedef_field_list;
10667   fip->typedef_field_list = new_field;
10668   fip->typedef_field_list_count++;
10669 }
10670
10671 /* Create the vector of fields, and attach it to the type.  */
10672
10673 static void
10674 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10675                               struct dwarf2_cu *cu)
10676 {
10677   int nfields = fip->nfields;
10678
10679   /* Record the field count, allocate space for the array of fields,
10680      and create blank accessibility bitfields if necessary.  */
10681   TYPE_NFIELDS (type) = nfields;
10682   TYPE_FIELDS (type) = (struct field *)
10683     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10684   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10685
10686   if (fip->non_public_fields && cu->language != language_ada)
10687     {
10688       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10689
10690       TYPE_FIELD_PRIVATE_BITS (type) =
10691         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10692       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10693
10694       TYPE_FIELD_PROTECTED_BITS (type) =
10695         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10696       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10697
10698       TYPE_FIELD_IGNORE_BITS (type) =
10699         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10700       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10701     }
10702
10703   /* If the type has baseclasses, allocate and clear a bit vector for
10704      TYPE_FIELD_VIRTUAL_BITS.  */
10705   if (fip->nbaseclasses && cu->language != language_ada)
10706     {
10707       int num_bytes = B_BYTES (fip->nbaseclasses);
10708       unsigned char *pointer;
10709
10710       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10711       pointer = TYPE_ALLOC (type, num_bytes);
10712       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10713       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10714       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10715     }
10716
10717   /* Copy the saved-up fields into the field vector.  Start from the head of
10718      the list, adding to the tail of the field array, so that they end up in
10719      the same order in the array in which they were added to the list.  */
10720   while (nfields-- > 0)
10721     {
10722       struct nextfield *fieldp;
10723
10724       if (fip->fields)
10725         {
10726           fieldp = fip->fields;
10727           fip->fields = fieldp->next;
10728         }
10729       else
10730         {
10731           fieldp = fip->baseclasses;
10732           fip->baseclasses = fieldp->next;
10733         }
10734
10735       TYPE_FIELD (type, nfields) = fieldp->field;
10736       switch (fieldp->accessibility)
10737         {
10738         case DW_ACCESS_private:
10739           if (cu->language != language_ada)
10740             SET_TYPE_FIELD_PRIVATE (type, nfields);
10741           break;
10742
10743         case DW_ACCESS_protected:
10744           if (cu->language != language_ada)
10745             SET_TYPE_FIELD_PROTECTED (type, nfields);
10746           break;
10747
10748         case DW_ACCESS_public:
10749           break;
10750
10751         default:
10752           /* Unknown accessibility.  Complain and treat it as public.  */
10753           {
10754             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10755                        fieldp->accessibility);
10756           }
10757           break;
10758         }
10759       if (nfields < fip->nbaseclasses)
10760         {
10761           switch (fieldp->virtuality)
10762             {
10763             case DW_VIRTUALITY_virtual:
10764             case DW_VIRTUALITY_pure_virtual:
10765               if (cu->language == language_ada)
10766                 error (_("unexpected virtuality in component of Ada type"));
10767               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10768               break;
10769             }
10770         }
10771     }
10772 }
10773
10774 /* Add a member function to the proper fieldlist.  */
10775
10776 static void
10777 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
10778                       struct type *type, struct dwarf2_cu *cu)
10779 {
10780   struct objfile *objfile = cu->objfile;
10781   struct attribute *attr;
10782   struct fnfieldlist *flp;
10783   int i;
10784   struct fn_field *fnp;
10785   char *fieldname;
10786   struct nextfnfield *new_fnfield;
10787   struct type *this_type;
10788   enum dwarf_access_attribute accessibility;
10789
10790   if (cu->language == language_ada)
10791     error (_("unexpected member function in Ada type"));
10792
10793   /* Get name of member function.  */
10794   fieldname = dwarf2_name (die, cu);
10795   if (fieldname == NULL)
10796     return;
10797
10798   /* Look up member function name in fieldlist.  */
10799   for (i = 0; i < fip->nfnfields; i++)
10800     {
10801       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
10802         break;
10803     }
10804
10805   /* Create new list element if necessary.  */
10806   if (i < fip->nfnfields)
10807     flp = &fip->fnfieldlists[i];
10808   else
10809     {
10810       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
10811         {
10812           fip->fnfieldlists = (struct fnfieldlist *)
10813             xrealloc (fip->fnfieldlists,
10814                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
10815                       * sizeof (struct fnfieldlist));
10816           if (fip->nfnfields == 0)
10817             make_cleanup (free_current_contents, &fip->fnfieldlists);
10818         }
10819       flp = &fip->fnfieldlists[fip->nfnfields];
10820       flp->name = fieldname;
10821       flp->length = 0;
10822       flp->head = NULL;
10823       i = fip->nfnfields++;
10824     }
10825
10826   /* Create a new member function field and chain it to the field list
10827      entry.  */
10828   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
10829   make_cleanup (xfree, new_fnfield);
10830   memset (new_fnfield, 0, sizeof (struct nextfnfield));
10831   new_fnfield->next = flp->head;
10832   flp->head = new_fnfield;
10833   flp->length++;
10834
10835   /* Fill in the member function field info.  */
10836   fnp = &new_fnfield->fnfield;
10837
10838   /* Delay processing of the physname until later.  */
10839   if (cu->language == language_cplus || cu->language == language_java)
10840     {
10841       add_to_method_list (type, i, flp->length - 1, fieldname,
10842                           die, cu);
10843     }
10844   else
10845     {
10846       const char *physname = dwarf2_physname (fieldname, die, cu);
10847       fnp->physname = physname ? physname : "";
10848     }
10849
10850   fnp->type = alloc_type (objfile);
10851   this_type = read_type_die (die, cu);
10852   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
10853     {
10854       int nparams = TYPE_NFIELDS (this_type);
10855
10856       /* TYPE is the domain of this method, and THIS_TYPE is the type
10857            of the method itself (TYPE_CODE_METHOD).  */
10858       smash_to_method_type (fnp->type, type,
10859                             TYPE_TARGET_TYPE (this_type),
10860                             TYPE_FIELDS (this_type),
10861                             TYPE_NFIELDS (this_type),
10862                             TYPE_VARARGS (this_type));
10863
10864       /* Handle static member functions.
10865          Dwarf2 has no clean way to discern C++ static and non-static
10866          member functions.  G++ helps GDB by marking the first
10867          parameter for non-static member functions (which is the this
10868          pointer) as artificial.  We obtain this information from
10869          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
10870       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
10871         fnp->voffset = VOFFSET_STATIC;
10872     }
10873   else
10874     complaint (&symfile_complaints, _("member function type missing for '%s'"),
10875                dwarf2_full_name (fieldname, die, cu));
10876
10877   /* Get fcontext from DW_AT_containing_type if present.  */
10878   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10879     fnp->fcontext = die_containing_type (die, cu);
10880
10881   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
10882      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
10883
10884   /* Get accessibility.  */
10885   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10886   if (attr)
10887     accessibility = DW_UNSND (attr);
10888   else
10889     accessibility = dwarf2_default_access_attribute (die, cu);
10890   switch (accessibility)
10891     {
10892     case DW_ACCESS_private:
10893       fnp->is_private = 1;
10894       break;
10895     case DW_ACCESS_protected:
10896       fnp->is_protected = 1;
10897       break;
10898     }
10899
10900   /* Check for artificial methods.  */
10901   attr = dwarf2_attr (die, DW_AT_artificial, cu);
10902   if (attr && DW_UNSND (attr) != 0)
10903     fnp->is_artificial = 1;
10904
10905   /* Get index in virtual function table if it is a virtual member
10906      function.  For older versions of GCC, this is an offset in the
10907      appropriate virtual table, as specified by DW_AT_containing_type.
10908      For everyone else, it is an expression to be evaluated relative
10909      to the object address.  */
10910
10911   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
10912   if (attr)
10913     {
10914       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
10915         {
10916           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
10917             {
10918               /* Old-style GCC.  */
10919               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
10920             }
10921           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
10922                    || (DW_BLOCK (attr)->size > 1
10923                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
10924                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
10925             {
10926               struct dwarf_block blk;
10927               int offset;
10928
10929               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
10930                         ? 1 : 2);
10931               blk.size = DW_BLOCK (attr)->size - offset;
10932               blk.data = DW_BLOCK (attr)->data + offset;
10933               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
10934               if ((fnp->voffset % cu->header.addr_size) != 0)
10935                 dwarf2_complex_location_expr_complaint ();
10936               else
10937                 fnp->voffset /= cu->header.addr_size;
10938               fnp->voffset += 2;
10939             }
10940           else
10941             dwarf2_complex_location_expr_complaint ();
10942
10943           if (!fnp->fcontext)
10944             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
10945         }
10946       else if (attr_form_is_section_offset (attr))
10947         {
10948           dwarf2_complex_location_expr_complaint ();
10949         }
10950       else
10951         {
10952           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
10953                                                  fieldname);
10954         }
10955     }
10956   else
10957     {
10958       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10959       if (attr && DW_UNSND (attr))
10960         {
10961           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
10962           complaint (&symfile_complaints,
10963                      _("Member function \"%s\" (offset %d) is virtual "
10964                        "but the vtable offset is not specified"),
10965                      fieldname, die->offset.sect_off);
10966           ALLOCATE_CPLUS_STRUCT_TYPE (type);
10967           TYPE_CPLUS_DYNAMIC (type) = 1;
10968         }
10969     }
10970 }
10971
10972 /* Create the vector of member function fields, and attach it to the type.  */
10973
10974 static void
10975 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
10976                                  struct dwarf2_cu *cu)
10977 {
10978   struct fnfieldlist *flp;
10979   int i;
10980
10981   if (cu->language == language_ada)
10982     error (_("unexpected member functions in Ada type"));
10983
10984   ALLOCATE_CPLUS_STRUCT_TYPE (type);
10985   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
10986     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
10987
10988   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
10989     {
10990       struct nextfnfield *nfp = flp->head;
10991       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
10992       int k;
10993
10994       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
10995       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
10996       fn_flp->fn_fields = (struct fn_field *)
10997         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
10998       for (k = flp->length; (k--, nfp); nfp = nfp->next)
10999         fn_flp->fn_fields[k] = nfp->fnfield;
11000     }
11001
11002   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11003 }
11004
11005 /* Returns non-zero if NAME is the name of a vtable member in CU's
11006    language, zero otherwise.  */
11007 static int
11008 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11009 {
11010   static const char vptr[] = "_vptr";
11011   static const char vtable[] = "vtable";
11012
11013   /* Look for the C++ and Java forms of the vtable.  */
11014   if ((cu->language == language_java
11015        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11016        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11017        && is_cplus_marker (name[sizeof (vptr) - 1])))
11018     return 1;
11019
11020   return 0;
11021 }
11022
11023 /* GCC outputs unnamed structures that are really pointers to member
11024    functions, with the ABI-specified layout.  If TYPE describes
11025    such a structure, smash it into a member function type.
11026
11027    GCC shouldn't do this; it should just output pointer to member DIEs.
11028    This is GCC PR debug/28767.  */
11029
11030 static void
11031 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11032 {
11033   struct type *pfn_type, *domain_type, *new_type;
11034
11035   /* Check for a structure with no name and two children.  */
11036   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11037     return;
11038
11039   /* Check for __pfn and __delta members.  */
11040   if (TYPE_FIELD_NAME (type, 0) == NULL
11041       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11042       || TYPE_FIELD_NAME (type, 1) == NULL
11043       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11044     return;
11045
11046   /* Find the type of the method.  */
11047   pfn_type = TYPE_FIELD_TYPE (type, 0);
11048   if (pfn_type == NULL
11049       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11050       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11051     return;
11052
11053   /* Look for the "this" argument.  */
11054   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11055   if (TYPE_NFIELDS (pfn_type) == 0
11056       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11057       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11058     return;
11059
11060   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11061   new_type = alloc_type (objfile);
11062   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11063                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11064                         TYPE_VARARGS (pfn_type));
11065   smash_to_methodptr_type (type, new_type);
11066 }
11067
11068 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11069    (icc).  */
11070
11071 static int
11072 producer_is_icc (struct dwarf2_cu *cu)
11073 {
11074   if (!cu->checked_producer)
11075     check_producer (cu);
11076
11077   return cu->producer_is_icc;
11078 }
11079
11080 /* Called when we find the DIE that starts a structure or union scope
11081    (definition) to create a type for the structure or union.  Fill in
11082    the type's name and general properties; the members will not be
11083    processed until process_structure_type.
11084
11085    NOTE: we need to call these functions regardless of whether or not the
11086    DIE has a DW_AT_name attribute, since it might be an anonymous
11087    structure or union.  This gets the type entered into our set of
11088    user defined types.
11089
11090    However, if the structure is incomplete (an opaque struct/union)
11091    then suppress creating a symbol table entry for it since gdb only
11092    wants to find the one with the complete definition.  Note that if
11093    it is complete, we just call new_symbol, which does it's own
11094    checking about whether the struct/union is anonymous or not (and
11095    suppresses creating a symbol table entry itself).  */
11096
11097 static struct type *
11098 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11099 {
11100   struct objfile *objfile = cu->objfile;
11101   struct type *type;
11102   struct attribute *attr;
11103   char *name;
11104
11105   /* If the definition of this type lives in .debug_types, read that type.
11106      Don't follow DW_AT_specification though, that will take us back up
11107      the chain and we want to go down.  */
11108   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11109   if (attr)
11110     {
11111       struct dwarf2_cu *type_cu = cu;
11112       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11113
11114       /* We could just recurse on read_structure_type, but we need to call
11115          get_die_type to ensure only one type for this DIE is created.
11116          This is important, for example, because for c++ classes we need
11117          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11118       type = read_type_die (type_die, type_cu);
11119
11120       /* TYPE_CU may not be the same as CU.
11121          Ensure TYPE is recorded in CU's type_hash table.  */
11122       return set_die_type (die, type, cu);
11123     }
11124
11125   type = alloc_type (objfile);
11126   INIT_CPLUS_SPECIFIC (type);
11127
11128   name = dwarf2_name (die, cu);
11129   if (name != NULL)
11130     {
11131       if (cu->language == language_cplus
11132           || cu->language == language_java)
11133         {
11134           char *full_name = (char *) dwarf2_full_name (name, die, cu);
11135
11136           /* dwarf2_full_name might have already finished building the DIE's
11137              type.  If so, there is no need to continue.  */
11138           if (get_die_type (die, cu) != NULL)
11139             return get_die_type (die, cu);
11140
11141           TYPE_TAG_NAME (type) = full_name;
11142           if (die->tag == DW_TAG_structure_type
11143               || die->tag == DW_TAG_class_type)
11144             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11145         }
11146       else
11147         {
11148           /* The name is already allocated along with this objfile, so
11149              we don't need to duplicate it for the type.  */
11150           TYPE_TAG_NAME (type) = (char *) name;
11151           if (die->tag == DW_TAG_class_type)
11152             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11153         }
11154     }
11155
11156   if (die->tag == DW_TAG_structure_type)
11157     {
11158       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11159     }
11160   else if (die->tag == DW_TAG_union_type)
11161     {
11162       TYPE_CODE (type) = TYPE_CODE_UNION;
11163     }
11164   else
11165     {
11166       TYPE_CODE (type) = TYPE_CODE_CLASS;
11167     }
11168
11169   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11170     TYPE_DECLARED_CLASS (type) = 1;
11171
11172   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11173   if (attr)
11174     {
11175       TYPE_LENGTH (type) = DW_UNSND (attr);
11176     }
11177   else
11178     {
11179       TYPE_LENGTH (type) = 0;
11180     }
11181
11182   if (producer_is_icc (cu))
11183     {
11184       /* ICC does not output the required DW_AT_declaration
11185          on incomplete types, but gives them a size of zero.  */
11186     }
11187   else
11188     TYPE_STUB_SUPPORTED (type) = 1;
11189
11190   if (die_is_declaration (die, cu))
11191     TYPE_STUB (type) = 1;
11192   else if (attr == NULL && die->child == NULL
11193            && producer_is_realview (cu->producer))
11194     /* RealView does not output the required DW_AT_declaration
11195        on incomplete types.  */
11196     TYPE_STUB (type) = 1;
11197
11198   /* We need to add the type field to the die immediately so we don't
11199      infinitely recurse when dealing with pointers to the structure
11200      type within the structure itself.  */
11201   set_die_type (die, type, cu);
11202
11203   /* set_die_type should be already done.  */
11204   set_descriptive_type (type, die, cu);
11205
11206   return type;
11207 }
11208
11209 /* Finish creating a structure or union type, including filling in
11210    its members and creating a symbol for it.  */
11211
11212 static void
11213 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11214 {
11215   struct objfile *objfile = cu->objfile;
11216   struct die_info *child_die = die->child;
11217   struct type *type;
11218
11219   type = get_die_type (die, cu);
11220   if (type == NULL)
11221     type = read_structure_type (die, cu);
11222
11223   if (die->child != NULL && ! die_is_declaration (die, cu))
11224     {
11225       struct field_info fi;
11226       struct die_info *child_die;
11227       VEC (symbolp) *template_args = NULL;
11228       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11229
11230       memset (&fi, 0, sizeof (struct field_info));
11231
11232       child_die = die->child;
11233
11234       while (child_die && child_die->tag)
11235         {
11236           if (child_die->tag == DW_TAG_member
11237               || child_die->tag == DW_TAG_variable)
11238             {
11239               /* NOTE: carlton/2002-11-05: A C++ static data member
11240                  should be a DW_TAG_member that is a declaration, but
11241                  all versions of G++ as of this writing (so through at
11242                  least 3.2.1) incorrectly generate DW_TAG_variable
11243                  tags for them instead.  */
11244               dwarf2_add_field (&fi, child_die, cu);
11245             }
11246           else if (child_die->tag == DW_TAG_subprogram)
11247             {
11248               /* C++ member function.  */
11249               dwarf2_add_member_fn (&fi, child_die, type, cu);
11250             }
11251           else if (child_die->tag == DW_TAG_inheritance)
11252             {
11253               /* C++ base class field.  */
11254               dwarf2_add_field (&fi, child_die, cu);
11255             }
11256           else if (child_die->tag == DW_TAG_typedef)
11257             dwarf2_add_typedef (&fi, child_die, cu);
11258           else if (child_die->tag == DW_TAG_template_type_param
11259                    || child_die->tag == DW_TAG_template_value_param)
11260             {
11261               struct symbol *arg = new_symbol (child_die, NULL, cu);
11262
11263               if (arg != NULL)
11264                 VEC_safe_push (symbolp, template_args, arg);
11265             }
11266
11267           child_die = sibling_die (child_die);
11268         }
11269
11270       /* Attach template arguments to type.  */
11271       if (! VEC_empty (symbolp, template_args))
11272         {
11273           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11274           TYPE_N_TEMPLATE_ARGUMENTS (type)
11275             = VEC_length (symbolp, template_args);
11276           TYPE_TEMPLATE_ARGUMENTS (type)
11277             = obstack_alloc (&objfile->objfile_obstack,
11278                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11279                               * sizeof (struct symbol *)));
11280           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11281                   VEC_address (symbolp, template_args),
11282                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11283                    * sizeof (struct symbol *)));
11284           VEC_free (symbolp, template_args);
11285         }
11286
11287       /* Attach fields and member functions to the type.  */
11288       if (fi.nfields)
11289         dwarf2_attach_fields_to_type (&fi, type, cu);
11290       if (fi.nfnfields)
11291         {
11292           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11293
11294           /* Get the type which refers to the base class (possibly this
11295              class itself) which contains the vtable pointer for the current
11296              class from the DW_AT_containing_type attribute.  This use of
11297              DW_AT_containing_type is a GNU extension.  */
11298
11299           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11300             {
11301               struct type *t = die_containing_type (die, cu);
11302
11303               TYPE_VPTR_BASETYPE (type) = t;
11304               if (type == t)
11305                 {
11306                   int i;
11307
11308                   /* Our own class provides vtbl ptr.  */
11309                   for (i = TYPE_NFIELDS (t) - 1;
11310                        i >= TYPE_N_BASECLASSES (t);
11311                        --i)
11312                     {
11313                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11314
11315                       if (is_vtable_name (fieldname, cu))
11316                         {
11317                           TYPE_VPTR_FIELDNO (type) = i;
11318                           break;
11319                         }
11320                     }
11321
11322                   /* Complain if virtual function table field not found.  */
11323                   if (i < TYPE_N_BASECLASSES (t))
11324                     complaint (&symfile_complaints,
11325                                _("virtual function table pointer "
11326                                  "not found when defining class '%s'"),
11327                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11328                                "");
11329                 }
11330               else
11331                 {
11332                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11333                 }
11334             }
11335           else if (cu->producer
11336                    && strncmp (cu->producer,
11337                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11338             {
11339               /* The IBM XLC compiler does not provide direct indication
11340                  of the containing type, but the vtable pointer is
11341                  always named __vfp.  */
11342
11343               int i;
11344
11345               for (i = TYPE_NFIELDS (type) - 1;
11346                    i >= TYPE_N_BASECLASSES (type);
11347                    --i)
11348                 {
11349                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11350                     {
11351                       TYPE_VPTR_FIELDNO (type) = i;
11352                       TYPE_VPTR_BASETYPE (type) = type;
11353                       break;
11354                     }
11355                 }
11356             }
11357         }
11358
11359       /* Copy fi.typedef_field_list linked list elements content into the
11360          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11361       if (fi.typedef_field_list)
11362         {
11363           int i = fi.typedef_field_list_count;
11364
11365           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11366           TYPE_TYPEDEF_FIELD_ARRAY (type)
11367             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11368           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11369
11370           /* Reverse the list order to keep the debug info elements order.  */
11371           while (--i >= 0)
11372             {
11373               struct typedef_field *dest, *src;
11374
11375               dest = &TYPE_TYPEDEF_FIELD (type, i);
11376               src = &fi.typedef_field_list->field;
11377               fi.typedef_field_list = fi.typedef_field_list->next;
11378               *dest = *src;
11379             }
11380         }
11381
11382       do_cleanups (back_to);
11383
11384       if (HAVE_CPLUS_STRUCT (type))
11385         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11386     }
11387
11388   quirk_gcc_member_function_pointer (type, objfile);
11389
11390   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11391      snapshots) has been known to create a die giving a declaration
11392      for a class that has, as a child, a die giving a definition for a
11393      nested class.  So we have to process our children even if the
11394      current die is a declaration.  Normally, of course, a declaration
11395      won't have any children at all.  */
11396
11397   while (child_die != NULL && child_die->tag)
11398     {
11399       if (child_die->tag == DW_TAG_member
11400           || child_die->tag == DW_TAG_variable
11401           || child_die->tag == DW_TAG_inheritance
11402           || child_die->tag == DW_TAG_template_value_param
11403           || child_die->tag == DW_TAG_template_type_param)
11404         {
11405           /* Do nothing.  */
11406         }
11407       else
11408         process_die (child_die, cu);
11409
11410       child_die = sibling_die (child_die);
11411     }
11412
11413   /* Do not consider external references.  According to the DWARF standard,
11414      these DIEs are identified by the fact that they have no byte_size
11415      attribute, and a declaration attribute.  */
11416   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11417       || !die_is_declaration (die, cu))
11418     new_symbol (die, type, cu);
11419 }
11420
11421 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11422    complete the type's fields yet, or create any symbols.  */
11423
11424 static struct type *
11425 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11426 {
11427   struct objfile *objfile = cu->objfile;
11428   struct type *type;
11429   struct attribute *attr;
11430   const char *name;
11431
11432   /* If the definition of this type lives in .debug_types, read that type.
11433      Don't follow DW_AT_specification though, that will take us back up
11434      the chain and we want to go down.  */
11435   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11436   if (attr)
11437     {
11438       struct dwarf2_cu *type_cu = cu;
11439       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11440
11441       type = read_type_die (type_die, type_cu);
11442
11443       /* TYPE_CU may not be the same as CU.
11444          Ensure TYPE is recorded in CU's type_hash table.  */
11445       return set_die_type (die, type, cu);
11446     }
11447
11448   type = alloc_type (objfile);
11449
11450   TYPE_CODE (type) = TYPE_CODE_ENUM;
11451   name = dwarf2_full_name (NULL, die, cu);
11452   if (name != NULL)
11453     TYPE_TAG_NAME (type) = (char *) name;
11454
11455   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11456   if (attr)
11457     {
11458       TYPE_LENGTH (type) = DW_UNSND (attr);
11459     }
11460   else
11461     {
11462       TYPE_LENGTH (type) = 0;
11463     }
11464
11465   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11466      declared as private in the package spec, and then defined only
11467      inside the package body.  Such types are known as Taft Amendment
11468      Types.  When another package uses such a type, an incomplete DIE
11469      may be generated by the compiler.  */
11470   if (die_is_declaration (die, cu))
11471     TYPE_STUB (type) = 1;
11472
11473   return set_die_type (die, type, cu);
11474 }
11475
11476 /* Given a pointer to a die which begins an enumeration, process all
11477    the dies that define the members of the enumeration, and create the
11478    symbol for the enumeration type.
11479
11480    NOTE: We reverse the order of the element list.  */
11481
11482 static void
11483 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11484 {
11485   struct type *this_type;
11486
11487   this_type = get_die_type (die, cu);
11488   if (this_type == NULL)
11489     this_type = read_enumeration_type (die, cu);
11490
11491   if (die->child != NULL)
11492     {
11493       struct die_info *child_die;
11494       struct symbol *sym;
11495       struct field *fields = NULL;
11496       int num_fields = 0;
11497       int unsigned_enum = 1;
11498       char *name;
11499       int flag_enum = 1;
11500       ULONGEST mask = 0;
11501
11502       child_die = die->child;
11503       while (child_die && child_die->tag)
11504         {
11505           if (child_die->tag != DW_TAG_enumerator)
11506             {
11507               process_die (child_die, cu);
11508             }
11509           else
11510             {
11511               name = dwarf2_name (child_die, cu);
11512               if (name)
11513                 {
11514                   sym = new_symbol (child_die, this_type, cu);
11515                   if (SYMBOL_VALUE (sym) < 0)
11516                     {
11517                       unsigned_enum = 0;
11518                       flag_enum = 0;
11519                     }
11520                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11521                     flag_enum = 0;
11522                   else
11523                     mask |= SYMBOL_VALUE (sym);
11524
11525                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11526                     {
11527                       fields = (struct field *)
11528                         xrealloc (fields,
11529                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11530                                   * sizeof (struct field));
11531                     }
11532
11533                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11534                   FIELD_TYPE (fields[num_fields]) = NULL;
11535                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11536                   FIELD_BITSIZE (fields[num_fields]) = 0;
11537
11538                   num_fields++;
11539                 }
11540             }
11541
11542           child_die = sibling_die (child_die);
11543         }
11544
11545       if (num_fields)
11546         {
11547           TYPE_NFIELDS (this_type) = num_fields;
11548           TYPE_FIELDS (this_type) = (struct field *)
11549             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11550           memcpy (TYPE_FIELDS (this_type), fields,
11551                   sizeof (struct field) * num_fields);
11552           xfree (fields);
11553         }
11554       if (unsigned_enum)
11555         TYPE_UNSIGNED (this_type) = 1;
11556       if (flag_enum)
11557         TYPE_FLAG_ENUM (this_type) = 1;
11558     }
11559
11560   /* If we are reading an enum from a .debug_types unit, and the enum
11561      is a declaration, and the enum is not the signatured type in the
11562      unit, then we do not want to add a symbol for it.  Adding a
11563      symbol would in some cases obscure the true definition of the
11564      enum, giving users an incomplete type when the definition is
11565      actually available.  Note that we do not want to do this for all
11566      enums which are just declarations, because C++0x allows forward
11567      enum declarations.  */
11568   if (cu->per_cu->is_debug_types
11569       && die_is_declaration (die, cu))
11570     {
11571       struct signatured_type *sig_type;
11572
11573       sig_type
11574         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
11575                                             cu->per_cu->info_or_types_section,
11576                                             cu->per_cu->offset);
11577       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11578       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11579         return;
11580     }
11581
11582   new_symbol (die, this_type, cu);
11583 }
11584
11585 /* Extract all information from a DW_TAG_array_type DIE and put it in
11586    the DIE's type field.  For now, this only handles one dimensional
11587    arrays.  */
11588
11589 static struct type *
11590 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11591 {
11592   struct objfile *objfile = cu->objfile;
11593   struct die_info *child_die;
11594   struct type *type;
11595   struct type *element_type, *range_type, *index_type;
11596   struct type **range_types = NULL;
11597   struct attribute *attr;
11598   int ndim = 0;
11599   struct cleanup *back_to;
11600   char *name;
11601
11602   element_type = die_type (die, cu);
11603
11604   /* The die_type call above may have already set the type for this DIE.  */
11605   type = get_die_type (die, cu);
11606   if (type)
11607     return type;
11608
11609   /* Irix 6.2 native cc creates array types without children for
11610      arrays with unspecified length.  */
11611   if (die->child == NULL)
11612     {
11613       index_type = objfile_type (objfile)->builtin_int;
11614       range_type = create_range_type (NULL, index_type, 0, -1);
11615       type = create_array_type (NULL, element_type, range_type);
11616       return set_die_type (die, type, cu);
11617     }
11618
11619   back_to = make_cleanup (null_cleanup, NULL);
11620   child_die = die->child;
11621   while (child_die && child_die->tag)
11622     {
11623       if (child_die->tag == DW_TAG_subrange_type)
11624         {
11625           struct type *child_type = read_type_die (child_die, cu);
11626
11627           if (child_type != NULL)
11628             {
11629               /* The range type was succesfully read.  Save it for the
11630                  array type creation.  */
11631               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11632                 {
11633                   range_types = (struct type **)
11634                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11635                               * sizeof (struct type *));
11636                   if (ndim == 0)
11637                     make_cleanup (free_current_contents, &range_types);
11638                 }
11639               range_types[ndim++] = child_type;
11640             }
11641         }
11642       child_die = sibling_die (child_die);
11643     }
11644
11645   /* Dwarf2 dimensions are output from left to right, create the
11646      necessary array types in backwards order.  */
11647
11648   type = element_type;
11649
11650   if (read_array_order (die, cu) == DW_ORD_col_major)
11651     {
11652       int i = 0;
11653
11654       while (i < ndim)
11655         type = create_array_type (NULL, type, range_types[i++]);
11656     }
11657   else
11658     {
11659       while (ndim-- > 0)
11660         type = create_array_type (NULL, type, range_types[ndim]);
11661     }
11662
11663   /* Understand Dwarf2 support for vector types (like they occur on
11664      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11665      array type.  This is not part of the Dwarf2/3 standard yet, but a
11666      custom vendor extension.  The main difference between a regular
11667      array and the vector variant is that vectors are passed by value
11668      to functions.  */
11669   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11670   if (attr)
11671     make_vector_type (type);
11672
11673   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11674      implementation may choose to implement triple vectors using this
11675      attribute.  */
11676   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11677   if (attr)
11678     {
11679       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11680         TYPE_LENGTH (type) = DW_UNSND (attr);
11681       else
11682         complaint (&symfile_complaints,
11683                    _("DW_AT_byte_size for array type smaller "
11684                      "than the total size of elements"));
11685     }
11686
11687   name = dwarf2_name (die, cu);
11688   if (name)
11689     TYPE_NAME (type) = name;
11690
11691   /* Install the type in the die.  */
11692   set_die_type (die, type, cu);
11693
11694   /* set_die_type should be already done.  */
11695   set_descriptive_type (type, die, cu);
11696
11697   do_cleanups (back_to);
11698
11699   return type;
11700 }
11701
11702 static enum dwarf_array_dim_ordering
11703 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11704 {
11705   struct attribute *attr;
11706
11707   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11708
11709   if (attr) return DW_SND (attr);
11710
11711   /* GNU F77 is a special case, as at 08/2004 array type info is the
11712      opposite order to the dwarf2 specification, but data is still
11713      laid out as per normal fortran.
11714
11715      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11716      version checking.  */
11717
11718   if (cu->language == language_fortran
11719       && cu->producer && strstr (cu->producer, "GNU F77"))
11720     {
11721       return DW_ORD_row_major;
11722     }
11723
11724   switch (cu->language_defn->la_array_ordering)
11725     {
11726     case array_column_major:
11727       return DW_ORD_col_major;
11728     case array_row_major:
11729     default:
11730       return DW_ORD_row_major;
11731     };
11732 }
11733
11734 /* Extract all information from a DW_TAG_set_type DIE and put it in
11735    the DIE's type field.  */
11736
11737 static struct type *
11738 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11739 {
11740   struct type *domain_type, *set_type;
11741   struct attribute *attr;
11742
11743   domain_type = die_type (die, cu);
11744
11745   /* The die_type call above may have already set the type for this DIE.  */
11746   set_type = get_die_type (die, cu);
11747   if (set_type)
11748     return set_type;
11749
11750   set_type = create_set_type (NULL, domain_type);
11751
11752   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11753   if (attr)
11754     TYPE_LENGTH (set_type) = DW_UNSND (attr);
11755
11756   return set_die_type (die, set_type, cu);
11757 }
11758
11759 /* A helper for read_common_block that creates a locexpr baton.
11760    SYM is the symbol which we are marking as computed.
11761    COMMON_DIE is the DIE for the common block.
11762    COMMON_LOC is the location expression attribute for the common
11763    block itself.
11764    MEMBER_LOC is the location expression attribute for the particular
11765    member of the common block that we are processing.
11766    CU is the CU from which the above come.  */
11767
11768 static void
11769 mark_common_block_symbol_computed (struct symbol *sym,
11770                                    struct die_info *common_die,
11771                                    struct attribute *common_loc,
11772                                    struct attribute *member_loc,
11773                                    struct dwarf2_cu *cu)
11774 {
11775   struct objfile *objfile = dwarf2_per_objfile->objfile;
11776   struct dwarf2_locexpr_baton *baton;
11777   gdb_byte *ptr;
11778   unsigned int cu_off;
11779   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
11780   LONGEST offset = 0;
11781
11782   gdb_assert (common_loc && member_loc);
11783   gdb_assert (attr_form_is_block (common_loc));
11784   gdb_assert (attr_form_is_block (member_loc)
11785               || attr_form_is_constant (member_loc));
11786
11787   baton = obstack_alloc (&objfile->objfile_obstack,
11788                          sizeof (struct dwarf2_locexpr_baton));
11789   baton->per_cu = cu->per_cu;
11790   gdb_assert (baton->per_cu);
11791
11792   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
11793
11794   if (attr_form_is_constant (member_loc))
11795     {
11796       offset = dwarf2_get_attr_constant_value (member_loc, 0);
11797       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
11798     }
11799   else
11800     baton->size += DW_BLOCK (member_loc)->size;
11801
11802   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
11803   baton->data = ptr;
11804
11805   *ptr++ = DW_OP_call4;
11806   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
11807   store_unsigned_integer (ptr, 4, byte_order, cu_off);
11808   ptr += 4;
11809
11810   if (attr_form_is_constant (member_loc))
11811     {
11812       *ptr++ = DW_OP_addr;
11813       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
11814       ptr += cu->header.addr_size;
11815     }
11816   else
11817     {
11818       /* We have to copy the data here, because DW_OP_call4 will only
11819          use a DW_AT_location attribute.  */
11820       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
11821       ptr += DW_BLOCK (member_loc)->size;
11822     }
11823
11824   *ptr++ = DW_OP_plus;
11825   gdb_assert (ptr - baton->data == baton->size);
11826
11827   SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
11828   SYMBOL_LOCATION_BATON (sym) = baton;
11829   SYMBOL_CLASS (sym) = LOC_COMPUTED;
11830 }
11831
11832 /* Create appropriate locally-scoped variables for all the
11833    DW_TAG_common_block entries.  Also create a struct common_block
11834    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
11835    is used to sepate the common blocks name namespace from regular
11836    variable names.  */
11837
11838 static void
11839 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
11840 {
11841   struct attribute *attr;
11842
11843   attr = dwarf2_attr (die, DW_AT_location, cu);
11844   if (attr)
11845     {
11846       /* Support the .debug_loc offsets.  */
11847       if (attr_form_is_block (attr))
11848         {
11849           /* Ok.  */
11850         }
11851       else if (attr_form_is_section_offset (attr))
11852         {
11853           dwarf2_complex_location_expr_complaint ();
11854           attr = NULL;
11855         }
11856       else
11857         {
11858           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11859                                                  "common block member");
11860           attr = NULL;
11861         }
11862     }
11863
11864   if (die->child != NULL)
11865     {
11866       struct objfile *objfile = cu->objfile;
11867       struct die_info *child_die;
11868       size_t n_entries = 0, size;
11869       struct common_block *common_block;
11870       struct symbol *sym;
11871
11872       for (child_die = die->child;
11873            child_die && child_die->tag;
11874            child_die = sibling_die (child_die))
11875         ++n_entries;
11876
11877       size = (sizeof (struct common_block)
11878               + (n_entries - 1) * sizeof (struct symbol *));
11879       common_block = obstack_alloc (&objfile->objfile_obstack, size);
11880       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
11881       common_block->n_entries = 0;
11882
11883       for (child_die = die->child;
11884            child_die && child_die->tag;
11885            child_die = sibling_die (child_die))
11886         {
11887           /* Create the symbol in the DW_TAG_common_block block in the current
11888              symbol scope.  */
11889           sym = new_symbol (child_die, NULL, cu);
11890           if (sym != NULL)
11891             {
11892               struct attribute *member_loc;
11893
11894               common_block->contents[common_block->n_entries++] = sym;
11895
11896               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
11897                                         cu);
11898               if (member_loc)
11899                 {
11900                   /* GDB has handled this for a long time, but it is
11901                      not specified by DWARF.  It seems to have been
11902                      emitted by gfortran at least as recently as:
11903                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
11904                   complaint (&symfile_complaints,
11905                              _("Variable in common block has "
11906                                "DW_AT_data_member_location "
11907                                "- DIE at 0x%x [in module %s]"),
11908                              child_die->offset.sect_off, cu->objfile->name);
11909
11910                   if (attr_form_is_section_offset (member_loc))
11911                     dwarf2_complex_location_expr_complaint ();
11912                   else if (attr_form_is_constant (member_loc)
11913                            || attr_form_is_block (member_loc))
11914                     {
11915                       if (attr)
11916                         mark_common_block_symbol_computed (sym, die, attr,
11917                                                            member_loc, cu);
11918                     }
11919                   else
11920                     dwarf2_complex_location_expr_complaint ();
11921                 }
11922             }
11923         }
11924
11925       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
11926       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
11927     }
11928 }
11929
11930 /* Create a type for a C++ namespace.  */
11931
11932 static struct type *
11933 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
11934 {
11935   struct objfile *objfile = cu->objfile;
11936   const char *previous_prefix, *name;
11937   int is_anonymous;
11938   struct type *type;
11939
11940   /* For extensions, reuse the type of the original namespace.  */
11941   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
11942     {
11943       struct die_info *ext_die;
11944       struct dwarf2_cu *ext_cu = cu;
11945
11946       ext_die = dwarf2_extension (die, &ext_cu);
11947       type = read_type_die (ext_die, ext_cu);
11948
11949       /* EXT_CU may not be the same as CU.
11950          Ensure TYPE is recorded in CU's type_hash table.  */
11951       return set_die_type (die, type, cu);
11952     }
11953
11954   name = namespace_name (die, &is_anonymous, cu);
11955
11956   /* Now build the name of the current namespace.  */
11957
11958   previous_prefix = determine_prefix (die, cu);
11959   if (previous_prefix[0] != '\0')
11960     name = typename_concat (&objfile->objfile_obstack,
11961                             previous_prefix, name, 0, cu);
11962
11963   /* Create the type.  */
11964   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
11965                     objfile);
11966   TYPE_NAME (type) = (char *) name;
11967   TYPE_TAG_NAME (type) = TYPE_NAME (type);
11968
11969   return set_die_type (die, type, cu);
11970 }
11971
11972 /* Read a C++ namespace.  */
11973
11974 static void
11975 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
11976 {
11977   struct objfile *objfile = cu->objfile;
11978   int is_anonymous;
11979
11980   /* Add a symbol associated to this if we haven't seen the namespace
11981      before.  Also, add a using directive if it's an anonymous
11982      namespace.  */
11983
11984   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
11985     {
11986       struct type *type;
11987
11988       type = read_type_die (die, cu);
11989       new_symbol (die, type, cu);
11990
11991       namespace_name (die, &is_anonymous, cu);
11992       if (is_anonymous)
11993         {
11994           const char *previous_prefix = determine_prefix (die, cu);
11995
11996           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
11997                                   NULL, NULL, &objfile->objfile_obstack);
11998         }
11999     }
12000
12001   if (die->child != NULL)
12002     {
12003       struct die_info *child_die = die->child;
12004
12005       while (child_die && child_die->tag)
12006         {
12007           process_die (child_die, cu);
12008           child_die = sibling_die (child_die);
12009         }
12010     }
12011 }
12012
12013 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12014    imported module.  Still we need that type as local Fortran "use ... only"
12015    declaration imports depend on the created type in determine_prefix.  */
12016
12017 static struct type *
12018 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12019 {
12020   struct objfile *objfile = cu->objfile;
12021   char *module_name;
12022   struct type *type;
12023
12024   module_name = dwarf2_name (die, cu);
12025   if (!module_name)
12026     complaint (&symfile_complaints,
12027                _("DW_TAG_module has no name, offset 0x%x"),
12028                die->offset.sect_off);
12029   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12030
12031   /* determine_prefix uses TYPE_TAG_NAME.  */
12032   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12033
12034   return set_die_type (die, type, cu);
12035 }
12036
12037 /* Read a Fortran module.  */
12038
12039 static void
12040 read_module (struct die_info *die, struct dwarf2_cu *cu)
12041 {
12042   struct die_info *child_die = die->child;
12043
12044   while (child_die && child_die->tag)
12045     {
12046       process_die (child_die, cu);
12047       child_die = sibling_die (child_die);
12048     }
12049 }
12050
12051 /* Return the name of the namespace represented by DIE.  Set
12052    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12053    namespace.  */
12054
12055 static const char *
12056 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12057 {
12058   struct die_info *current_die;
12059   const char *name = NULL;
12060
12061   /* Loop through the extensions until we find a name.  */
12062
12063   for (current_die = die;
12064        current_die != NULL;
12065        current_die = dwarf2_extension (die, &cu))
12066     {
12067       name = dwarf2_name (current_die, cu);
12068       if (name != NULL)
12069         break;
12070     }
12071
12072   /* Is it an anonymous namespace?  */
12073
12074   *is_anonymous = (name == NULL);
12075   if (*is_anonymous)
12076     name = CP_ANONYMOUS_NAMESPACE_STR;
12077
12078   return name;
12079 }
12080
12081 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12082    the user defined type vector.  */
12083
12084 static struct type *
12085 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12086 {
12087   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12088   struct comp_unit_head *cu_header = &cu->header;
12089   struct type *type;
12090   struct attribute *attr_byte_size;
12091   struct attribute *attr_address_class;
12092   int byte_size, addr_class;
12093   struct type *target_type;
12094
12095   target_type = die_type (die, cu);
12096
12097   /* The die_type call above may have already set the type for this DIE.  */
12098   type = get_die_type (die, cu);
12099   if (type)
12100     return type;
12101
12102   type = lookup_pointer_type (target_type);
12103
12104   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12105   if (attr_byte_size)
12106     byte_size = DW_UNSND (attr_byte_size);
12107   else
12108     byte_size = cu_header->addr_size;
12109
12110   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12111   if (attr_address_class)
12112     addr_class = DW_UNSND (attr_address_class);
12113   else
12114     addr_class = DW_ADDR_none;
12115
12116   /* If the pointer size or address class is different than the
12117      default, create a type variant marked as such and set the
12118      length accordingly.  */
12119   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12120     {
12121       if (gdbarch_address_class_type_flags_p (gdbarch))
12122         {
12123           int type_flags;
12124
12125           type_flags = gdbarch_address_class_type_flags
12126                          (gdbarch, byte_size, addr_class);
12127           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12128                       == 0);
12129           type = make_type_with_address_space (type, type_flags);
12130         }
12131       else if (TYPE_LENGTH (type) != byte_size)
12132         {
12133           complaint (&symfile_complaints,
12134                      _("invalid pointer size %d"), byte_size);
12135         }
12136       else
12137         {
12138           /* Should we also complain about unhandled address classes?  */
12139         }
12140     }
12141
12142   TYPE_LENGTH (type) = byte_size;
12143   return set_die_type (die, type, cu);
12144 }
12145
12146 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12147    the user defined type vector.  */
12148
12149 static struct type *
12150 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12151 {
12152   struct type *type;
12153   struct type *to_type;
12154   struct type *domain;
12155
12156   to_type = die_type (die, cu);
12157   domain = die_containing_type (die, cu);
12158
12159   /* The calls above may have already set the type for this DIE.  */
12160   type = get_die_type (die, cu);
12161   if (type)
12162     return type;
12163
12164   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12165     type = lookup_methodptr_type (to_type);
12166   else
12167     type = lookup_memberptr_type (to_type, domain);
12168
12169   return set_die_type (die, type, cu);
12170 }
12171
12172 /* Extract all information from a DW_TAG_reference_type DIE and add to
12173    the user defined type vector.  */
12174
12175 static struct type *
12176 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12177 {
12178   struct comp_unit_head *cu_header = &cu->header;
12179   struct type *type, *target_type;
12180   struct attribute *attr;
12181
12182   target_type = die_type (die, cu);
12183
12184   /* The die_type call above may have already set the type for this DIE.  */
12185   type = get_die_type (die, cu);
12186   if (type)
12187     return type;
12188
12189   type = lookup_reference_type (target_type);
12190   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12191   if (attr)
12192     {
12193       TYPE_LENGTH (type) = DW_UNSND (attr);
12194     }
12195   else
12196     {
12197       TYPE_LENGTH (type) = cu_header->addr_size;
12198     }
12199   return set_die_type (die, type, cu);
12200 }
12201
12202 static struct type *
12203 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12204 {
12205   struct type *base_type, *cv_type;
12206
12207   base_type = die_type (die, cu);
12208
12209   /* The die_type call above may have already set the type for this DIE.  */
12210   cv_type = get_die_type (die, cu);
12211   if (cv_type)
12212     return cv_type;
12213
12214   /* In case the const qualifier is applied to an array type, the element type
12215      is so qualified, not the array type (section 6.7.3 of C99).  */
12216   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12217     {
12218       struct type *el_type, *inner_array;
12219
12220       base_type = copy_type (base_type);
12221       inner_array = base_type;
12222
12223       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12224         {
12225           TYPE_TARGET_TYPE (inner_array) =
12226             copy_type (TYPE_TARGET_TYPE (inner_array));
12227           inner_array = TYPE_TARGET_TYPE (inner_array);
12228         }
12229
12230       el_type = TYPE_TARGET_TYPE (inner_array);
12231       TYPE_TARGET_TYPE (inner_array) =
12232         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12233
12234       return set_die_type (die, base_type, cu);
12235     }
12236
12237   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12238   return set_die_type (die, cv_type, cu);
12239 }
12240
12241 static struct type *
12242 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12243 {
12244   struct type *base_type, *cv_type;
12245
12246   base_type = die_type (die, cu);
12247
12248   /* The die_type call above may have already set the type for this DIE.  */
12249   cv_type = get_die_type (die, cu);
12250   if (cv_type)
12251     return cv_type;
12252
12253   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12254   return set_die_type (die, cv_type, cu);
12255 }
12256
12257 /* Extract all information from a DW_TAG_string_type DIE and add to
12258    the user defined type vector.  It isn't really a user defined type,
12259    but it behaves like one, with other DIE's using an AT_user_def_type
12260    attribute to reference it.  */
12261
12262 static struct type *
12263 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12264 {
12265   struct objfile *objfile = cu->objfile;
12266   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12267   struct type *type, *range_type, *index_type, *char_type;
12268   struct attribute *attr;
12269   unsigned int length;
12270
12271   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12272   if (attr)
12273     {
12274       length = DW_UNSND (attr);
12275     }
12276   else
12277     {
12278       /* Check for the DW_AT_byte_size attribute.  */
12279       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12280       if (attr)
12281         {
12282           length = DW_UNSND (attr);
12283         }
12284       else
12285         {
12286           length = 1;
12287         }
12288     }
12289
12290   index_type = objfile_type (objfile)->builtin_int;
12291   range_type = create_range_type (NULL, index_type, 1, length);
12292   char_type = language_string_char_type (cu->language_defn, gdbarch);
12293   type = create_string_type (NULL, char_type, range_type);
12294
12295   return set_die_type (die, type, cu);
12296 }
12297
12298 /* Handle DIES due to C code like:
12299
12300    struct foo
12301    {
12302    int (*funcp)(int a, long l);
12303    int b;
12304    };
12305
12306    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12307
12308 static struct type *
12309 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12310 {
12311   struct objfile *objfile = cu->objfile;
12312   struct type *type;            /* Type that this function returns.  */
12313   struct type *ftype;           /* Function that returns above type.  */
12314   struct attribute *attr;
12315
12316   type = die_type (die, cu);
12317
12318   /* The die_type call above may have already set the type for this DIE.  */
12319   ftype = get_die_type (die, cu);
12320   if (ftype)
12321     return ftype;
12322
12323   ftype = lookup_function_type (type);
12324
12325   /* All functions in C++, Pascal and Java have prototypes.  */
12326   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12327   if ((attr && (DW_UNSND (attr) != 0))
12328       || cu->language == language_cplus
12329       || cu->language == language_java
12330       || cu->language == language_pascal)
12331     TYPE_PROTOTYPED (ftype) = 1;
12332   else if (producer_is_realview (cu->producer))
12333     /* RealView does not emit DW_AT_prototyped.  We can not
12334        distinguish prototyped and unprototyped functions; default to
12335        prototyped, since that is more common in modern code (and
12336        RealView warns about unprototyped functions).  */
12337     TYPE_PROTOTYPED (ftype) = 1;
12338
12339   /* Store the calling convention in the type if it's available in
12340      the subroutine die.  Otherwise set the calling convention to
12341      the default value DW_CC_normal.  */
12342   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12343   if (attr)
12344     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12345   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12346     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12347   else
12348     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12349
12350   /* We need to add the subroutine type to the die immediately so
12351      we don't infinitely recurse when dealing with parameters
12352      declared as the same subroutine type.  */
12353   set_die_type (die, ftype, cu);
12354
12355   if (die->child != NULL)
12356     {
12357       struct type *void_type = objfile_type (objfile)->builtin_void;
12358       struct die_info *child_die;
12359       int nparams, iparams;
12360
12361       /* Count the number of parameters.
12362          FIXME: GDB currently ignores vararg functions, but knows about
12363          vararg member functions.  */
12364       nparams = 0;
12365       child_die = die->child;
12366       while (child_die && child_die->tag)
12367         {
12368           if (child_die->tag == DW_TAG_formal_parameter)
12369             nparams++;
12370           else if (child_die->tag == DW_TAG_unspecified_parameters)
12371             TYPE_VARARGS (ftype) = 1;
12372           child_die = sibling_die (child_die);
12373         }
12374
12375       /* Allocate storage for parameters and fill them in.  */
12376       TYPE_NFIELDS (ftype) = nparams;
12377       TYPE_FIELDS (ftype) = (struct field *)
12378         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12379
12380       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12381          even if we error out during the parameters reading below.  */
12382       for (iparams = 0; iparams < nparams; iparams++)
12383         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12384
12385       iparams = 0;
12386       child_die = die->child;
12387       while (child_die && child_die->tag)
12388         {
12389           if (child_die->tag == DW_TAG_formal_parameter)
12390             {
12391               struct type *arg_type;
12392
12393               /* DWARF version 2 has no clean way to discern C++
12394                  static and non-static member functions.  G++ helps
12395                  GDB by marking the first parameter for non-static
12396                  member functions (which is the this pointer) as
12397                  artificial.  We pass this information to
12398                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12399
12400                  DWARF version 3 added DW_AT_object_pointer, which GCC
12401                  4.5 does not yet generate.  */
12402               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12403               if (attr)
12404                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12405               else
12406                 {
12407                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12408
12409                   /* GCC/43521: In java, the formal parameter
12410                      "this" is sometimes not marked with DW_AT_artificial.  */
12411                   if (cu->language == language_java)
12412                     {
12413                       const char *name = dwarf2_name (child_die, cu);
12414
12415                       if (name && !strcmp (name, "this"))
12416                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12417                     }
12418                 }
12419               arg_type = die_type (child_die, cu);
12420
12421               /* RealView does not mark THIS as const, which the testsuite
12422                  expects.  GCC marks THIS as const in method definitions,
12423                  but not in the class specifications (GCC PR 43053).  */
12424               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12425                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12426                 {
12427                   int is_this = 0;
12428                   struct dwarf2_cu *arg_cu = cu;
12429                   const char *name = dwarf2_name (child_die, cu);
12430
12431                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12432                   if (attr)
12433                     {
12434                       /* If the compiler emits this, use it.  */
12435                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12436                         is_this = 1;
12437                     }
12438                   else if (name && strcmp (name, "this") == 0)
12439                     /* Function definitions will have the argument names.  */
12440                     is_this = 1;
12441                   else if (name == NULL && iparams == 0)
12442                     /* Declarations may not have the names, so like
12443                        elsewhere in GDB, assume an artificial first
12444                        argument is "this".  */
12445                     is_this = 1;
12446
12447                   if (is_this)
12448                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12449                                              arg_type, 0);
12450                 }
12451
12452               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12453               iparams++;
12454             }
12455           child_die = sibling_die (child_die);
12456         }
12457     }
12458
12459   return ftype;
12460 }
12461
12462 static struct type *
12463 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12464 {
12465   struct objfile *objfile = cu->objfile;
12466   const char *name = NULL;
12467   struct type *this_type, *target_type;
12468
12469   name = dwarf2_full_name (NULL, die, cu);
12470   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12471                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12472   TYPE_NAME (this_type) = (char *) name;
12473   set_die_type (die, this_type, cu);
12474   target_type = die_type (die, cu);
12475   if (target_type != this_type)
12476     TYPE_TARGET_TYPE (this_type) = target_type;
12477   else
12478     {
12479       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12480          spec and cause infinite loops in GDB.  */
12481       complaint (&symfile_complaints,
12482                  _("Self-referential DW_TAG_typedef "
12483                    "- DIE at 0x%x [in module %s]"),
12484                  die->offset.sect_off, objfile->name);
12485       TYPE_TARGET_TYPE (this_type) = NULL;
12486     }
12487   return this_type;
12488 }
12489
12490 /* Find a representation of a given base type and install
12491    it in the TYPE field of the die.  */
12492
12493 static struct type *
12494 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12495 {
12496   struct objfile *objfile = cu->objfile;
12497   struct type *type;
12498   struct attribute *attr;
12499   int encoding = 0, size = 0;
12500   char *name;
12501   enum type_code code = TYPE_CODE_INT;
12502   int type_flags = 0;
12503   struct type *target_type = NULL;
12504
12505   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12506   if (attr)
12507     {
12508       encoding = DW_UNSND (attr);
12509     }
12510   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12511   if (attr)
12512     {
12513       size = DW_UNSND (attr);
12514     }
12515   name = dwarf2_name (die, cu);
12516   if (!name)
12517     {
12518       complaint (&symfile_complaints,
12519                  _("DW_AT_name missing from DW_TAG_base_type"));
12520     }
12521
12522   switch (encoding)
12523     {
12524       case DW_ATE_address:
12525         /* Turn DW_ATE_address into a void * pointer.  */
12526         code = TYPE_CODE_PTR;
12527         type_flags |= TYPE_FLAG_UNSIGNED;
12528         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12529         break;
12530       case DW_ATE_boolean:
12531         code = TYPE_CODE_BOOL;
12532         type_flags |= TYPE_FLAG_UNSIGNED;
12533         break;
12534       case DW_ATE_complex_float:
12535         code = TYPE_CODE_COMPLEX;
12536         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12537         break;
12538       case DW_ATE_decimal_float:
12539         code = TYPE_CODE_DECFLOAT;
12540         break;
12541       case DW_ATE_float:
12542         code = TYPE_CODE_FLT;
12543         break;
12544       case DW_ATE_signed:
12545         break;
12546       case DW_ATE_unsigned:
12547         type_flags |= TYPE_FLAG_UNSIGNED;
12548         if (cu->language == language_fortran
12549             && name
12550             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12551           code = TYPE_CODE_CHAR;
12552         break;
12553       case DW_ATE_signed_char:
12554         if (cu->language == language_ada || cu->language == language_m2
12555             || cu->language == language_pascal
12556             || cu->language == language_fortran)
12557           code = TYPE_CODE_CHAR;
12558         break;
12559       case DW_ATE_unsigned_char:
12560         if (cu->language == language_ada || cu->language == language_m2
12561             || cu->language == language_pascal
12562             || cu->language == language_fortran)
12563           code = TYPE_CODE_CHAR;
12564         type_flags |= TYPE_FLAG_UNSIGNED;
12565         break;
12566       case DW_ATE_UTF:
12567         /* We just treat this as an integer and then recognize the
12568            type by name elsewhere.  */
12569         break;
12570
12571       default:
12572         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12573                    dwarf_type_encoding_name (encoding));
12574         break;
12575     }
12576
12577   type = init_type (code, size, type_flags, NULL, objfile);
12578   TYPE_NAME (type) = name;
12579   TYPE_TARGET_TYPE (type) = target_type;
12580
12581   if (name && strcmp (name, "char") == 0)
12582     TYPE_NOSIGN (type) = 1;
12583
12584   return set_die_type (die, type, cu);
12585 }
12586
12587 /* Read the given DW_AT_subrange DIE.  */
12588
12589 static struct type *
12590 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12591 {
12592   struct type *base_type;
12593   struct type *range_type;
12594   struct attribute *attr;
12595   LONGEST low, high;
12596   int low_default_is_valid;
12597   char *name;
12598   LONGEST negative_mask;
12599
12600   base_type = die_type (die, cu);
12601   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
12602   check_typedef (base_type);
12603
12604   /* The die_type call above may have already set the type for this DIE.  */
12605   range_type = get_die_type (die, cu);
12606   if (range_type)
12607     return range_type;
12608
12609   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12610      omitting DW_AT_lower_bound.  */
12611   switch (cu->language)
12612     {
12613     case language_c:
12614     case language_cplus:
12615       low = 0;
12616       low_default_is_valid = 1;
12617       break;
12618     case language_fortran:
12619       low = 1;
12620       low_default_is_valid = 1;
12621       break;
12622     case language_d:
12623     case language_java:
12624     case language_objc:
12625       low = 0;
12626       low_default_is_valid = (cu->header.version >= 4);
12627       break;
12628     case language_ada:
12629     case language_m2:
12630     case language_pascal:
12631       low = 1;
12632       low_default_is_valid = (cu->header.version >= 4);
12633       break;
12634     default:
12635       low = 0;
12636       low_default_is_valid = 0;
12637       break;
12638     }
12639
12640   /* FIXME: For variable sized arrays either of these could be
12641      a variable rather than a constant value.  We'll allow it,
12642      but we don't know how to handle it.  */
12643   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12644   if (attr)
12645     low = dwarf2_get_attr_constant_value (attr, low);
12646   else if (!low_default_is_valid)
12647     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12648                                       "- DIE at 0x%x [in module %s]"),
12649                die->offset.sect_off, cu->objfile->name);
12650
12651   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12652   if (attr)
12653     {
12654       if (attr_form_is_block (attr) || is_ref_attr (attr))
12655         {
12656           /* GCC encodes arrays with unspecified or dynamic length
12657              with a DW_FORM_block1 attribute or a reference attribute.
12658              FIXME: GDB does not yet know how to handle dynamic
12659              arrays properly, treat them as arrays with unspecified
12660              length for now.
12661
12662              FIXME: jimb/2003-09-22: GDB does not really know
12663              how to handle arrays of unspecified length
12664              either; we just represent them as zero-length
12665              arrays.  Choose an appropriate upper bound given
12666              the lower bound we've computed above.  */
12667           high = low - 1;
12668         }
12669       else
12670         high = dwarf2_get_attr_constant_value (attr, 1);
12671     }
12672   else
12673     {
12674       attr = dwarf2_attr (die, DW_AT_count, cu);
12675       if (attr)
12676         {
12677           int count = dwarf2_get_attr_constant_value (attr, 1);
12678           high = low + count - 1;
12679         }
12680       else
12681         {
12682           /* Unspecified array length.  */
12683           high = low - 1;
12684         }
12685     }
12686
12687   /* Dwarf-2 specifications explicitly allows to create subrange types
12688      without specifying a base type.
12689      In that case, the base type must be set to the type of
12690      the lower bound, upper bound or count, in that order, if any of these
12691      three attributes references an object that has a type.
12692      If no base type is found, the Dwarf-2 specifications say that
12693      a signed integer type of size equal to the size of an address should
12694      be used.
12695      For the following C code: `extern char gdb_int [];'
12696      GCC produces an empty range DIE.
12697      FIXME: muller/2010-05-28: Possible references to object for low bound,
12698      high bound or count are not yet handled by this code.  */
12699   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12700     {
12701       struct objfile *objfile = cu->objfile;
12702       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12703       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12704       struct type *int_type = objfile_type (objfile)->builtin_int;
12705
12706       /* Test "int", "long int", and "long long int" objfile types,
12707          and select the first one having a size above or equal to the
12708          architecture address size.  */
12709       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12710         base_type = int_type;
12711       else
12712         {
12713           int_type = objfile_type (objfile)->builtin_long;
12714           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12715             base_type = int_type;
12716           else
12717             {
12718               int_type = objfile_type (objfile)->builtin_long_long;
12719               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12720                 base_type = int_type;
12721             }
12722         }
12723     }
12724
12725   negative_mask =
12726     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
12727   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
12728     low |= negative_mask;
12729   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
12730     high |= negative_mask;
12731
12732   range_type = create_range_type (NULL, base_type, low, high);
12733
12734   /* Mark arrays with dynamic length at least as an array of unspecified
12735      length.  GDB could check the boundary but before it gets implemented at
12736      least allow accessing the array elements.  */
12737   if (attr && attr_form_is_block (attr))
12738     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12739
12740   /* Ada expects an empty array on no boundary attributes.  */
12741   if (attr == NULL && cu->language != language_ada)
12742     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12743
12744   name = dwarf2_name (die, cu);
12745   if (name)
12746     TYPE_NAME (range_type) = name;
12747
12748   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12749   if (attr)
12750     TYPE_LENGTH (range_type) = DW_UNSND (attr);
12751
12752   set_die_type (die, range_type, cu);
12753
12754   /* set_die_type should be already done.  */
12755   set_descriptive_type (range_type, die, cu);
12756
12757   return range_type;
12758 }
12759
12760 static struct type *
12761 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
12762 {
12763   struct type *type;
12764
12765   /* For now, we only support the C meaning of an unspecified type: void.  */
12766
12767   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
12768   TYPE_NAME (type) = dwarf2_name (die, cu);
12769
12770   return set_die_type (die, type, cu);
12771 }
12772
12773 /* Read a single die and all its descendents.  Set the die's sibling
12774    field to NULL; set other fields in the die correctly, and set all
12775    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
12776    location of the info_ptr after reading all of those dies.  PARENT
12777    is the parent of the die in question.  */
12778
12779 static struct die_info *
12780 read_die_and_children (const struct die_reader_specs *reader,
12781                        gdb_byte *info_ptr,
12782                        gdb_byte **new_info_ptr,
12783                        struct die_info *parent)
12784 {
12785   struct die_info *die;
12786   gdb_byte *cur_ptr;
12787   int has_children;
12788
12789   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
12790   if (die == NULL)
12791     {
12792       *new_info_ptr = cur_ptr;
12793       return NULL;
12794     }
12795   store_in_ref_table (die, reader->cu);
12796
12797   if (has_children)
12798     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
12799   else
12800     {
12801       die->child = NULL;
12802       *new_info_ptr = cur_ptr;
12803     }
12804
12805   die->sibling = NULL;
12806   die->parent = parent;
12807   return die;
12808 }
12809
12810 /* Read a die, all of its descendents, and all of its siblings; set
12811    all of the fields of all of the dies correctly.  Arguments are as
12812    in read_die_and_children.  */
12813
12814 static struct die_info *
12815 read_die_and_siblings (const struct die_reader_specs *reader,
12816                        gdb_byte *info_ptr,
12817                        gdb_byte **new_info_ptr,
12818                        struct die_info *parent)
12819 {
12820   struct die_info *first_die, *last_sibling;
12821   gdb_byte *cur_ptr;
12822
12823   cur_ptr = info_ptr;
12824   first_die = last_sibling = NULL;
12825
12826   while (1)
12827     {
12828       struct die_info *die
12829         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
12830
12831       if (die == NULL)
12832         {
12833           *new_info_ptr = cur_ptr;
12834           return first_die;
12835         }
12836
12837       if (!first_die)
12838         first_die = die;
12839       else
12840         last_sibling->sibling = die;
12841
12842       last_sibling = die;
12843     }
12844 }
12845
12846 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
12847    attributes.
12848    The caller is responsible for filling in the extra attributes
12849    and updating (*DIEP)->num_attrs.
12850    Set DIEP to point to a newly allocated die with its information,
12851    except for its child, sibling, and parent fields.
12852    Set HAS_CHILDREN to tell whether the die has children or not.  */
12853
12854 static gdb_byte *
12855 read_full_die_1 (const struct die_reader_specs *reader,
12856                  struct die_info **diep, gdb_byte *info_ptr,
12857                  int *has_children, int num_extra_attrs)
12858 {
12859   unsigned int abbrev_number, bytes_read, i;
12860   sect_offset offset;
12861   struct abbrev_info *abbrev;
12862   struct die_info *die;
12863   struct dwarf2_cu *cu = reader->cu;
12864   bfd *abfd = reader->abfd;
12865
12866   offset.sect_off = info_ptr - reader->buffer;
12867   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12868   info_ptr += bytes_read;
12869   if (!abbrev_number)
12870     {
12871       *diep = NULL;
12872       *has_children = 0;
12873       return info_ptr;
12874     }
12875
12876   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
12877   if (!abbrev)
12878     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
12879            abbrev_number,
12880            bfd_get_filename (abfd));
12881
12882   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
12883   die->offset = offset;
12884   die->tag = abbrev->tag;
12885   die->abbrev = abbrev_number;
12886
12887   /* Make the result usable.
12888      The caller needs to update num_attrs after adding the extra
12889      attributes.  */
12890   die->num_attrs = abbrev->num_attrs;
12891
12892   for (i = 0; i < abbrev->num_attrs; ++i)
12893     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
12894                                info_ptr);
12895
12896   *diep = die;
12897   *has_children = abbrev->has_children;
12898   return info_ptr;
12899 }
12900
12901 /* Read a die and all its attributes.
12902    Set DIEP to point to a newly allocated die with its information,
12903    except for its child, sibling, and parent fields.
12904    Set HAS_CHILDREN to tell whether the die has children or not.  */
12905
12906 static gdb_byte *
12907 read_full_die (const struct die_reader_specs *reader,
12908                struct die_info **diep, gdb_byte *info_ptr,
12909                int *has_children)
12910 {
12911   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
12912 }
12913 \f
12914 /* Abbreviation tables.
12915
12916    In DWARF version 2, the description of the debugging information is
12917    stored in a separate .debug_abbrev section.  Before we read any
12918    dies from a section we read in all abbreviations and install them
12919    in a hash table.  */
12920
12921 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
12922
12923 static struct abbrev_info *
12924 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
12925 {
12926   struct abbrev_info *abbrev;
12927
12928   abbrev = (struct abbrev_info *)
12929     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
12930   memset (abbrev, 0, sizeof (struct abbrev_info));
12931   return abbrev;
12932 }
12933
12934 /* Add an abbreviation to the table.  */
12935
12936 static void
12937 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
12938                          unsigned int abbrev_number,
12939                          struct abbrev_info *abbrev)
12940 {
12941   unsigned int hash_number;
12942
12943   hash_number = abbrev_number % ABBREV_HASH_SIZE;
12944   abbrev->next = abbrev_table->abbrevs[hash_number];
12945   abbrev_table->abbrevs[hash_number] = abbrev;
12946 }
12947
12948 /* Look up an abbrev in the table.
12949    Returns NULL if the abbrev is not found.  */
12950
12951 static struct abbrev_info *
12952 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
12953                             unsigned int abbrev_number)
12954 {
12955   unsigned int hash_number;
12956   struct abbrev_info *abbrev;
12957
12958   hash_number = abbrev_number % ABBREV_HASH_SIZE;
12959   abbrev = abbrev_table->abbrevs[hash_number];
12960
12961   while (abbrev)
12962     {
12963       if (abbrev->number == abbrev_number)
12964         return abbrev;
12965       abbrev = abbrev->next;
12966     }
12967   return NULL;
12968 }
12969
12970 /* Read in an abbrev table.  */
12971
12972 static struct abbrev_table *
12973 abbrev_table_read_table (struct dwarf2_section_info *section,
12974                          sect_offset offset)
12975 {
12976   struct objfile *objfile = dwarf2_per_objfile->objfile;
12977   bfd *abfd = section->asection->owner;
12978   struct abbrev_table *abbrev_table;
12979   gdb_byte *abbrev_ptr;
12980   struct abbrev_info *cur_abbrev;
12981   unsigned int abbrev_number, bytes_read, abbrev_name;
12982   unsigned int abbrev_form;
12983   struct attr_abbrev *cur_attrs;
12984   unsigned int allocated_attrs;
12985
12986   abbrev_table = XMALLOC (struct abbrev_table);
12987   abbrev_table->offset = offset;
12988   obstack_init (&abbrev_table->abbrev_obstack);
12989   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
12990                                          (ABBREV_HASH_SIZE
12991                                           * sizeof (struct abbrev_info *)));
12992   memset (abbrev_table->abbrevs, 0,
12993           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
12994
12995   dwarf2_read_section (objfile, section);
12996   abbrev_ptr = section->buffer + offset.sect_off;
12997   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
12998   abbrev_ptr += bytes_read;
12999
13000   allocated_attrs = ATTR_ALLOC_CHUNK;
13001   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13002
13003   /* Loop until we reach an abbrev number of 0.  */
13004   while (abbrev_number)
13005     {
13006       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13007
13008       /* read in abbrev header */
13009       cur_abbrev->number = abbrev_number;
13010       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13011       abbrev_ptr += bytes_read;
13012       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13013       abbrev_ptr += 1;
13014
13015       /* now read in declarations */
13016       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13017       abbrev_ptr += bytes_read;
13018       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13019       abbrev_ptr += bytes_read;
13020       while (abbrev_name)
13021         {
13022           if (cur_abbrev->num_attrs == allocated_attrs)
13023             {
13024               allocated_attrs += ATTR_ALLOC_CHUNK;
13025               cur_attrs
13026                 = xrealloc (cur_attrs, (allocated_attrs
13027                                         * sizeof (struct attr_abbrev)));
13028             }
13029
13030           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13031           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13032           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13033           abbrev_ptr += bytes_read;
13034           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13035           abbrev_ptr += bytes_read;
13036         }
13037
13038       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13039                                          (cur_abbrev->num_attrs
13040                                           * sizeof (struct attr_abbrev)));
13041       memcpy (cur_abbrev->attrs, cur_attrs,
13042               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13043
13044       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13045
13046       /* Get next abbreviation.
13047          Under Irix6 the abbreviations for a compilation unit are not
13048          always properly terminated with an abbrev number of 0.
13049          Exit loop if we encounter an abbreviation which we have
13050          already read (which means we are about to read the abbreviations
13051          for the next compile unit) or if the end of the abbreviation
13052          table is reached.  */
13053       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13054         break;
13055       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13056       abbrev_ptr += bytes_read;
13057       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13058         break;
13059     }
13060
13061   xfree (cur_attrs);
13062   return abbrev_table;
13063 }
13064
13065 /* Free the resources held by ABBREV_TABLE.  */
13066
13067 static void
13068 abbrev_table_free (struct abbrev_table *abbrev_table)
13069 {
13070   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13071   xfree (abbrev_table);
13072 }
13073
13074 /* Same as abbrev_table_free but as a cleanup.
13075    We pass in a pointer to the pointer to the table so that we can
13076    set the pointer to NULL when we're done.  It also simplifies
13077    build_type_unit_groups.  */
13078
13079 static void
13080 abbrev_table_free_cleanup (void *table_ptr)
13081 {
13082   struct abbrev_table **abbrev_table_ptr = table_ptr;
13083
13084   if (*abbrev_table_ptr != NULL)
13085     abbrev_table_free (*abbrev_table_ptr);
13086   *abbrev_table_ptr = NULL;
13087 }
13088
13089 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13090
13091 static void
13092 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13093                      struct dwarf2_section_info *abbrev_section)
13094 {
13095   cu->abbrev_table =
13096     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13097 }
13098
13099 /* Release the memory used by the abbrev table for a compilation unit.  */
13100
13101 static void
13102 dwarf2_free_abbrev_table (void *ptr_to_cu)
13103 {
13104   struct dwarf2_cu *cu = ptr_to_cu;
13105
13106   abbrev_table_free (cu->abbrev_table);
13107   /* Set this to NULL so that we SEGV if we try to read it later,
13108      and also because free_comp_unit verifies this is NULL.  */
13109   cu->abbrev_table = NULL;
13110 }
13111 \f
13112 /* Returns nonzero if TAG represents a type that we might generate a partial
13113    symbol for.  */
13114
13115 static int
13116 is_type_tag_for_partial (int tag)
13117 {
13118   switch (tag)
13119     {
13120 #if 0
13121     /* Some types that would be reasonable to generate partial symbols for,
13122        that we don't at present.  */
13123     case DW_TAG_array_type:
13124     case DW_TAG_file_type:
13125     case DW_TAG_ptr_to_member_type:
13126     case DW_TAG_set_type:
13127     case DW_TAG_string_type:
13128     case DW_TAG_subroutine_type:
13129 #endif
13130     case DW_TAG_base_type:
13131     case DW_TAG_class_type:
13132     case DW_TAG_interface_type:
13133     case DW_TAG_enumeration_type:
13134     case DW_TAG_structure_type:
13135     case DW_TAG_subrange_type:
13136     case DW_TAG_typedef:
13137     case DW_TAG_union_type:
13138       return 1;
13139     default:
13140       return 0;
13141     }
13142 }
13143
13144 /* Load all DIEs that are interesting for partial symbols into memory.  */
13145
13146 static struct partial_die_info *
13147 load_partial_dies (const struct die_reader_specs *reader,
13148                    gdb_byte *info_ptr, int building_psymtab)
13149 {
13150   struct dwarf2_cu *cu = reader->cu;
13151   struct objfile *objfile = cu->objfile;
13152   struct partial_die_info *part_die;
13153   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13154   struct abbrev_info *abbrev;
13155   unsigned int bytes_read;
13156   unsigned int load_all = 0;
13157   int nesting_level = 1;
13158
13159   parent_die = NULL;
13160   last_die = NULL;
13161
13162   gdb_assert (cu->per_cu != NULL);
13163   if (cu->per_cu->load_all_dies)
13164     load_all = 1;
13165
13166   cu->partial_dies
13167     = htab_create_alloc_ex (cu->header.length / 12,
13168                             partial_die_hash,
13169                             partial_die_eq,
13170                             NULL,
13171                             &cu->comp_unit_obstack,
13172                             hashtab_obstack_allocate,
13173                             dummy_obstack_deallocate);
13174
13175   part_die = obstack_alloc (&cu->comp_unit_obstack,
13176                             sizeof (struct partial_die_info));
13177
13178   while (1)
13179     {
13180       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13181
13182       /* A NULL abbrev means the end of a series of children.  */
13183       if (abbrev == NULL)
13184         {
13185           if (--nesting_level == 0)
13186             {
13187               /* PART_DIE was probably the last thing allocated on the
13188                  comp_unit_obstack, so we could call obstack_free
13189                  here.  We don't do that because the waste is small,
13190                  and will be cleaned up when we're done with this
13191                  compilation unit.  This way, we're also more robust
13192                  against other users of the comp_unit_obstack.  */
13193               return first_die;
13194             }
13195           info_ptr += bytes_read;
13196           last_die = parent_die;
13197           parent_die = parent_die->die_parent;
13198           continue;
13199         }
13200
13201       /* Check for template arguments.  We never save these; if
13202          they're seen, we just mark the parent, and go on our way.  */
13203       if (parent_die != NULL
13204           && cu->language == language_cplus
13205           && (abbrev->tag == DW_TAG_template_type_param
13206               || abbrev->tag == DW_TAG_template_value_param))
13207         {
13208           parent_die->has_template_arguments = 1;
13209
13210           if (!load_all)
13211             {
13212               /* We don't need a partial DIE for the template argument.  */
13213               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13214               continue;
13215             }
13216         }
13217
13218       /* We only recurse into c++ subprograms looking for template arguments.
13219          Skip their other children.  */
13220       if (!load_all
13221           && cu->language == language_cplus
13222           && parent_die != NULL
13223           && parent_die->tag == DW_TAG_subprogram)
13224         {
13225           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13226           continue;
13227         }
13228
13229       /* Check whether this DIE is interesting enough to save.  Normally
13230          we would not be interested in members here, but there may be
13231          later variables referencing them via DW_AT_specification (for
13232          static members).  */
13233       if (!load_all
13234           && !is_type_tag_for_partial (abbrev->tag)
13235           && abbrev->tag != DW_TAG_constant
13236           && abbrev->tag != DW_TAG_enumerator
13237           && abbrev->tag != DW_TAG_subprogram
13238           && abbrev->tag != DW_TAG_lexical_block
13239           && abbrev->tag != DW_TAG_variable
13240           && abbrev->tag != DW_TAG_namespace
13241           && abbrev->tag != DW_TAG_module
13242           && abbrev->tag != DW_TAG_member
13243           && abbrev->tag != DW_TAG_imported_unit)
13244         {
13245           /* Otherwise we skip to the next sibling, if any.  */
13246           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13247           continue;
13248         }
13249
13250       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13251                                    info_ptr);
13252
13253       /* This two-pass algorithm for processing partial symbols has a
13254          high cost in cache pressure.  Thus, handle some simple cases
13255          here which cover the majority of C partial symbols.  DIEs
13256          which neither have specification tags in them, nor could have
13257          specification tags elsewhere pointing at them, can simply be
13258          processed and discarded.
13259
13260          This segment is also optional; scan_partial_symbols and
13261          add_partial_symbol will handle these DIEs if we chain
13262          them in normally.  When compilers which do not emit large
13263          quantities of duplicate debug information are more common,
13264          this code can probably be removed.  */
13265
13266       /* Any complete simple types at the top level (pretty much all
13267          of them, for a language without namespaces), can be processed
13268          directly.  */
13269       if (parent_die == NULL
13270           && part_die->has_specification == 0
13271           && part_die->is_declaration == 0
13272           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13273               || part_die->tag == DW_TAG_base_type
13274               || part_die->tag == DW_TAG_subrange_type))
13275         {
13276           if (building_psymtab && part_die->name != NULL)
13277             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13278                                  VAR_DOMAIN, LOC_TYPEDEF,
13279                                  &objfile->static_psymbols,
13280                                  0, (CORE_ADDR) 0, cu->language, objfile);
13281           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13282           continue;
13283         }
13284
13285       /* The exception for DW_TAG_typedef with has_children above is
13286          a workaround of GCC PR debug/47510.  In the case of this complaint
13287          type_name_no_tag_or_error will error on such types later.
13288
13289          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13290          it could not find the child DIEs referenced later, this is checked
13291          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13292
13293       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13294         complaint (&symfile_complaints,
13295                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13296                      "- DIE at 0x%x [in module %s]"),
13297                    part_die->offset.sect_off, objfile->name);
13298
13299       /* If we're at the second level, and we're an enumerator, and
13300          our parent has no specification (meaning possibly lives in a
13301          namespace elsewhere), then we can add the partial symbol now
13302          instead of queueing it.  */
13303       if (part_die->tag == DW_TAG_enumerator
13304           && parent_die != NULL
13305           && parent_die->die_parent == NULL
13306           && parent_die->tag == DW_TAG_enumeration_type
13307           && parent_die->has_specification == 0)
13308         {
13309           if (part_die->name == NULL)
13310             complaint (&symfile_complaints,
13311                        _("malformed enumerator DIE ignored"));
13312           else if (building_psymtab)
13313             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13314                                  VAR_DOMAIN, LOC_CONST,
13315                                  (cu->language == language_cplus
13316                                   || cu->language == language_java)
13317                                  ? &objfile->global_psymbols
13318                                  : &objfile->static_psymbols,
13319                                  0, (CORE_ADDR) 0, cu->language, objfile);
13320
13321           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13322           continue;
13323         }
13324
13325       /* We'll save this DIE so link it in.  */
13326       part_die->die_parent = parent_die;
13327       part_die->die_sibling = NULL;
13328       part_die->die_child = NULL;
13329
13330       if (last_die && last_die == parent_die)
13331         last_die->die_child = part_die;
13332       else if (last_die)
13333         last_die->die_sibling = part_die;
13334
13335       last_die = part_die;
13336
13337       if (first_die == NULL)
13338         first_die = part_die;
13339
13340       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13341          find interesting need to be in the hash table, because we
13342          also have the parent/sibling/child chains; only those that we
13343          might refer to by offset later during partial symbol reading.
13344
13345          For now this means things that might have be the target of a
13346          DW_AT_specification, DW_AT_abstract_origin, or
13347          DW_AT_extension.  DW_AT_extension will refer only to
13348          namespaces; DW_AT_abstract_origin refers to functions (and
13349          many things under the function DIE, but we do not recurse
13350          into function DIEs during partial symbol reading) and
13351          possibly variables as well; DW_AT_specification refers to
13352          declarations.  Declarations ought to have the DW_AT_declaration
13353          flag.  It happens that GCC forgets to put it in sometimes, but
13354          only for functions, not for types.
13355
13356          Adding more things than necessary to the hash table is harmless
13357          except for the performance cost.  Adding too few will result in
13358          wasted time in find_partial_die, when we reread the compilation
13359          unit with load_all_dies set.  */
13360
13361       if (load_all
13362           || abbrev->tag == DW_TAG_constant
13363           || abbrev->tag == DW_TAG_subprogram
13364           || abbrev->tag == DW_TAG_variable
13365           || abbrev->tag == DW_TAG_namespace
13366           || part_die->is_declaration)
13367         {
13368           void **slot;
13369
13370           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13371                                            part_die->offset.sect_off, INSERT);
13372           *slot = part_die;
13373         }
13374
13375       part_die = obstack_alloc (&cu->comp_unit_obstack,
13376                                 sizeof (struct partial_die_info));
13377
13378       /* For some DIEs we want to follow their children (if any).  For C
13379          we have no reason to follow the children of structures; for other
13380          languages we have to, so that we can get at method physnames
13381          to infer fully qualified class names, for DW_AT_specification,
13382          and for C++ template arguments.  For C++, we also look one level
13383          inside functions to find template arguments (if the name of the
13384          function does not already contain the template arguments).
13385
13386          For Ada, we need to scan the children of subprograms and lexical
13387          blocks as well because Ada allows the definition of nested
13388          entities that could be interesting for the debugger, such as
13389          nested subprograms for instance.  */
13390       if (last_die->has_children
13391           && (load_all
13392               || last_die->tag == DW_TAG_namespace
13393               || last_die->tag == DW_TAG_module
13394               || last_die->tag == DW_TAG_enumeration_type
13395               || (cu->language == language_cplus
13396                   && last_die->tag == DW_TAG_subprogram
13397                   && (last_die->name == NULL
13398                       || strchr (last_die->name, '<') == NULL))
13399               || (cu->language != language_c
13400                   && (last_die->tag == DW_TAG_class_type
13401                       || last_die->tag == DW_TAG_interface_type
13402                       || last_die->tag == DW_TAG_structure_type
13403                       || last_die->tag == DW_TAG_union_type))
13404               || (cu->language == language_ada
13405                   && (last_die->tag == DW_TAG_subprogram
13406                       || last_die->tag == DW_TAG_lexical_block))))
13407         {
13408           nesting_level++;
13409           parent_die = last_die;
13410           continue;
13411         }
13412
13413       /* Otherwise we skip to the next sibling, if any.  */
13414       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13415
13416       /* Back to the top, do it again.  */
13417     }
13418 }
13419
13420 /* Read a minimal amount of information into the minimal die structure.  */
13421
13422 static gdb_byte *
13423 read_partial_die (const struct die_reader_specs *reader,
13424                   struct partial_die_info *part_die,
13425                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13426                   gdb_byte *info_ptr)
13427 {
13428   struct dwarf2_cu *cu = reader->cu;
13429   struct objfile *objfile = cu->objfile;
13430   gdb_byte *buffer = reader->buffer;
13431   unsigned int i;
13432   struct attribute attr;
13433   int has_low_pc_attr = 0;
13434   int has_high_pc_attr = 0;
13435   int high_pc_relative = 0;
13436
13437   memset (part_die, 0, sizeof (struct partial_die_info));
13438
13439   part_die->offset.sect_off = info_ptr - buffer;
13440
13441   info_ptr += abbrev_len;
13442
13443   if (abbrev == NULL)
13444     return info_ptr;
13445
13446   part_die->tag = abbrev->tag;
13447   part_die->has_children = abbrev->has_children;
13448
13449   for (i = 0; i < abbrev->num_attrs; ++i)
13450     {
13451       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13452
13453       /* Store the data if it is of an attribute we want to keep in a
13454          partial symbol table.  */
13455       switch (attr.name)
13456         {
13457         case DW_AT_name:
13458           switch (part_die->tag)
13459             {
13460             case DW_TAG_compile_unit:
13461             case DW_TAG_partial_unit:
13462             case DW_TAG_type_unit:
13463               /* Compilation units have a DW_AT_name that is a filename, not
13464                  a source language identifier.  */
13465             case DW_TAG_enumeration_type:
13466             case DW_TAG_enumerator:
13467               /* These tags always have simple identifiers already; no need
13468                  to canonicalize them.  */
13469               part_die->name = DW_STRING (&attr);
13470               break;
13471             default:
13472               part_die->name
13473                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13474                                             &objfile->objfile_obstack);
13475               break;
13476             }
13477           break;
13478         case DW_AT_linkage_name:
13479         case DW_AT_MIPS_linkage_name:
13480           /* Note that both forms of linkage name might appear.  We
13481              assume they will be the same, and we only store the last
13482              one we see.  */
13483           if (cu->language == language_ada)
13484             part_die->name = DW_STRING (&attr);
13485           part_die->linkage_name = DW_STRING (&attr);
13486           break;
13487         case DW_AT_low_pc:
13488           has_low_pc_attr = 1;
13489           part_die->lowpc = DW_ADDR (&attr);
13490           break;
13491         case DW_AT_high_pc:
13492           has_high_pc_attr = 1;
13493           if (attr.form == DW_FORM_addr
13494               || attr.form == DW_FORM_GNU_addr_index)
13495             part_die->highpc = DW_ADDR (&attr);
13496           else
13497             {
13498               high_pc_relative = 1;
13499               part_die->highpc = DW_UNSND (&attr);
13500             }
13501           break;
13502         case DW_AT_location:
13503           /* Support the .debug_loc offsets.  */
13504           if (attr_form_is_block (&attr))
13505             {
13506                part_die->d.locdesc = DW_BLOCK (&attr);
13507             }
13508           else if (attr_form_is_section_offset (&attr))
13509             {
13510               dwarf2_complex_location_expr_complaint ();
13511             }
13512           else
13513             {
13514               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13515                                                      "partial symbol information");
13516             }
13517           break;
13518         case DW_AT_external:
13519           part_die->is_external = DW_UNSND (&attr);
13520           break;
13521         case DW_AT_declaration:
13522           part_die->is_declaration = DW_UNSND (&attr);
13523           break;
13524         case DW_AT_type:
13525           part_die->has_type = 1;
13526           break;
13527         case DW_AT_abstract_origin:
13528         case DW_AT_specification:
13529         case DW_AT_extension:
13530           part_die->has_specification = 1;
13531           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13532           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13533                                    || cu->per_cu->is_dwz);
13534           break;
13535         case DW_AT_sibling:
13536           /* Ignore absolute siblings, they might point outside of
13537              the current compile unit.  */
13538           if (attr.form == DW_FORM_ref_addr)
13539             complaint (&symfile_complaints,
13540                        _("ignoring absolute DW_AT_sibling"));
13541           else
13542             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13543           break;
13544         case DW_AT_byte_size:
13545           part_die->has_byte_size = 1;
13546           break;
13547         case DW_AT_calling_convention:
13548           /* DWARF doesn't provide a way to identify a program's source-level
13549              entry point.  DW_AT_calling_convention attributes are only meant
13550              to describe functions' calling conventions.
13551
13552              However, because it's a necessary piece of information in
13553              Fortran, and because DW_CC_program is the only piece of debugging
13554              information whose definition refers to a 'main program' at all,
13555              several compilers have begun marking Fortran main programs with
13556              DW_CC_program --- even when those functions use the standard
13557              calling conventions.
13558
13559              So until DWARF specifies a way to provide this information and
13560              compilers pick up the new representation, we'll support this
13561              practice.  */
13562           if (DW_UNSND (&attr) == DW_CC_program
13563               && cu->language == language_fortran)
13564             {
13565               set_main_name (part_die->name);
13566
13567               /* As this DIE has a static linkage the name would be difficult
13568                  to look up later.  */
13569               language_of_main = language_fortran;
13570             }
13571           break;
13572         case DW_AT_inline:
13573           if (DW_UNSND (&attr) == DW_INL_inlined
13574               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13575             part_die->may_be_inlined = 1;
13576           break;
13577
13578         case DW_AT_import:
13579           if (part_die->tag == DW_TAG_imported_unit)
13580             {
13581               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13582               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13583                                   || cu->per_cu->is_dwz);
13584             }
13585           break;
13586
13587         default:
13588           break;
13589         }
13590     }
13591
13592   if (high_pc_relative)
13593     part_die->highpc += part_die->lowpc;
13594
13595   if (has_low_pc_attr && has_high_pc_attr)
13596     {
13597       /* When using the GNU linker, .gnu.linkonce. sections are used to
13598          eliminate duplicate copies of functions and vtables and such.
13599          The linker will arbitrarily choose one and discard the others.
13600          The AT_*_pc values for such functions refer to local labels in
13601          these sections.  If the section from that file was discarded, the
13602          labels are not in the output, so the relocs get a value of 0.
13603          If this is a discarded function, mark the pc bounds as invalid,
13604          so that GDB will ignore it.  */
13605       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13606         {
13607           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13608
13609           complaint (&symfile_complaints,
13610                      _("DW_AT_low_pc %s is zero "
13611                        "for DIE at 0x%x [in module %s]"),
13612                      paddress (gdbarch, part_die->lowpc),
13613                      part_die->offset.sect_off, objfile->name);
13614         }
13615       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13616       else if (part_die->lowpc >= part_die->highpc)
13617         {
13618           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13619
13620           complaint (&symfile_complaints,
13621                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13622                        "for DIE at 0x%x [in module %s]"),
13623                      paddress (gdbarch, part_die->lowpc),
13624                      paddress (gdbarch, part_die->highpc),
13625                      part_die->offset.sect_off, objfile->name);
13626         }
13627       else
13628         part_die->has_pc_info = 1;
13629     }
13630
13631   return info_ptr;
13632 }
13633
13634 /* Find a cached partial DIE at OFFSET in CU.  */
13635
13636 static struct partial_die_info *
13637 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13638 {
13639   struct partial_die_info *lookup_die = NULL;
13640   struct partial_die_info part_die;
13641
13642   part_die.offset = offset;
13643   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13644                                     offset.sect_off);
13645
13646   return lookup_die;
13647 }
13648
13649 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13650    except in the case of .debug_types DIEs which do not reference
13651    outside their CU (they do however referencing other types via
13652    DW_FORM_ref_sig8).  */
13653
13654 static struct partial_die_info *
13655 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13656 {
13657   struct objfile *objfile = cu->objfile;
13658   struct dwarf2_per_cu_data *per_cu = NULL;
13659   struct partial_die_info *pd = NULL;
13660
13661   if (offset_in_dwz == cu->per_cu->is_dwz
13662       && offset_in_cu_p (&cu->header, offset))
13663     {
13664       pd = find_partial_die_in_comp_unit (offset, cu);
13665       if (pd != NULL)
13666         return pd;
13667       /* We missed recording what we needed.
13668          Load all dies and try again.  */
13669       per_cu = cu->per_cu;
13670     }
13671   else
13672     {
13673       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13674       if (cu->per_cu->is_debug_types)
13675         {
13676           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13677                    " external reference to offset 0x%lx [in module %s].\n"),
13678                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
13679                  bfd_get_filename (objfile->obfd));
13680         }
13681       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
13682                                                  objfile);
13683
13684       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
13685         load_partial_comp_unit (per_cu);
13686
13687       per_cu->cu->last_used = 0;
13688       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13689     }
13690
13691   /* If we didn't find it, and not all dies have been loaded,
13692      load them all and try again.  */
13693
13694   if (pd == NULL && per_cu->load_all_dies == 0)
13695     {
13696       per_cu->load_all_dies = 1;
13697
13698       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
13699          THIS_CU->cu may already be in use.  So we can't just free it and
13700          replace its DIEs with the ones we read in.  Instead, we leave those
13701          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
13702          and clobber THIS_CU->cu->partial_dies with the hash table for the new
13703          set.  */
13704       load_partial_comp_unit (per_cu);
13705
13706       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13707     }
13708
13709   if (pd == NULL)
13710     internal_error (__FILE__, __LINE__,
13711                     _("could not find partial DIE 0x%x "
13712                       "in cache [from module %s]\n"),
13713                     offset.sect_off, bfd_get_filename (objfile->obfd));
13714   return pd;
13715 }
13716
13717 /* See if we can figure out if the class lives in a namespace.  We do
13718    this by looking for a member function; its demangled name will
13719    contain namespace info, if there is any.  */
13720
13721 static void
13722 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
13723                                   struct dwarf2_cu *cu)
13724 {
13725   /* NOTE: carlton/2003-10-07: Getting the info this way changes
13726      what template types look like, because the demangler
13727      frequently doesn't give the same name as the debug info.  We
13728      could fix this by only using the demangled name to get the
13729      prefix (but see comment in read_structure_type).  */
13730
13731   struct partial_die_info *real_pdi;
13732   struct partial_die_info *child_pdi;
13733
13734   /* If this DIE (this DIE's specification, if any) has a parent, then
13735      we should not do this.  We'll prepend the parent's fully qualified
13736      name when we create the partial symbol.  */
13737
13738   real_pdi = struct_pdi;
13739   while (real_pdi->has_specification)
13740     real_pdi = find_partial_die (real_pdi->spec_offset,
13741                                  real_pdi->spec_is_dwz, cu);
13742
13743   if (real_pdi->die_parent != NULL)
13744     return;
13745
13746   for (child_pdi = struct_pdi->die_child;
13747        child_pdi != NULL;
13748        child_pdi = child_pdi->die_sibling)
13749     {
13750       if (child_pdi->tag == DW_TAG_subprogram
13751           && child_pdi->linkage_name != NULL)
13752         {
13753           char *actual_class_name
13754             = language_class_name_from_physname (cu->language_defn,
13755                                                  child_pdi->linkage_name);
13756           if (actual_class_name != NULL)
13757             {
13758               struct_pdi->name
13759                 = obsavestring (actual_class_name,
13760                                 strlen (actual_class_name),
13761                                 &cu->objfile->objfile_obstack);
13762               xfree (actual_class_name);
13763             }
13764           break;
13765         }
13766     }
13767 }
13768
13769 /* Adjust PART_DIE before generating a symbol for it.  This function
13770    may set the is_external flag or change the DIE's name.  */
13771
13772 static void
13773 fixup_partial_die (struct partial_die_info *part_die,
13774                    struct dwarf2_cu *cu)
13775 {
13776   /* Once we've fixed up a die, there's no point in doing so again.
13777      This also avoids a memory leak if we were to call
13778      guess_partial_die_structure_name multiple times.  */
13779   if (part_die->fixup_called)
13780     return;
13781
13782   /* If we found a reference attribute and the DIE has no name, try
13783      to find a name in the referred to DIE.  */
13784
13785   if (part_die->name == NULL && part_die->has_specification)
13786     {
13787       struct partial_die_info *spec_die;
13788
13789       spec_die = find_partial_die (part_die->spec_offset,
13790                                    part_die->spec_is_dwz, cu);
13791
13792       fixup_partial_die (spec_die, cu);
13793
13794       if (spec_die->name)
13795         {
13796           part_die->name = spec_die->name;
13797
13798           /* Copy DW_AT_external attribute if it is set.  */
13799           if (spec_die->is_external)
13800             part_die->is_external = spec_die->is_external;
13801         }
13802     }
13803
13804   /* Set default names for some unnamed DIEs.  */
13805
13806   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
13807     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
13808
13809   /* If there is no parent die to provide a namespace, and there are
13810      children, see if we can determine the namespace from their linkage
13811      name.  */
13812   if (cu->language == language_cplus
13813       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
13814       && part_die->die_parent == NULL
13815       && part_die->has_children
13816       && (part_die->tag == DW_TAG_class_type
13817           || part_die->tag == DW_TAG_structure_type
13818           || part_die->tag == DW_TAG_union_type))
13819     guess_partial_die_structure_name (part_die, cu);
13820
13821   /* GCC might emit a nameless struct or union that has a linkage
13822      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
13823   if (part_die->name == NULL
13824       && (part_die->tag == DW_TAG_class_type
13825           || part_die->tag == DW_TAG_interface_type
13826           || part_die->tag == DW_TAG_structure_type
13827           || part_die->tag == DW_TAG_union_type)
13828       && part_die->linkage_name != NULL)
13829     {
13830       char *demangled;
13831
13832       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
13833       if (demangled)
13834         {
13835           const char *base;
13836
13837           /* Strip any leading namespaces/classes, keep only the base name.
13838              DW_AT_name for named DIEs does not contain the prefixes.  */
13839           base = strrchr (demangled, ':');
13840           if (base && base > demangled && base[-1] == ':')
13841             base++;
13842           else
13843             base = demangled;
13844
13845           part_die->name = obsavestring (base, strlen (base),
13846                                          &cu->objfile->objfile_obstack);
13847           xfree (demangled);
13848         }
13849     }
13850
13851   part_die->fixup_called = 1;
13852 }
13853
13854 /* Read an attribute value described by an attribute form.  */
13855
13856 static gdb_byte *
13857 read_attribute_value (const struct die_reader_specs *reader,
13858                       struct attribute *attr, unsigned form,
13859                       gdb_byte *info_ptr)
13860 {
13861   struct dwarf2_cu *cu = reader->cu;
13862   bfd *abfd = reader->abfd;
13863   struct comp_unit_head *cu_header = &cu->header;
13864   unsigned int bytes_read;
13865   struct dwarf_block *blk;
13866
13867   attr->form = form;
13868   switch (form)
13869     {
13870     case DW_FORM_ref_addr:
13871       if (cu->header.version == 2)
13872         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
13873       else
13874         DW_UNSND (attr) = read_offset (abfd, info_ptr,
13875                                        &cu->header, &bytes_read);
13876       info_ptr += bytes_read;
13877       break;
13878     case DW_FORM_GNU_ref_alt:
13879       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
13880       info_ptr += bytes_read;
13881       break;
13882     case DW_FORM_addr:
13883       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
13884       info_ptr += bytes_read;
13885       break;
13886     case DW_FORM_block2:
13887       blk = dwarf_alloc_block (cu);
13888       blk->size = read_2_bytes (abfd, info_ptr);
13889       info_ptr += 2;
13890       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
13891       info_ptr += blk->size;
13892       DW_BLOCK (attr) = blk;
13893       break;
13894     case DW_FORM_block4:
13895       blk = dwarf_alloc_block (cu);
13896       blk->size = read_4_bytes (abfd, info_ptr);
13897       info_ptr += 4;
13898       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
13899       info_ptr += blk->size;
13900       DW_BLOCK (attr) = blk;
13901       break;
13902     case DW_FORM_data2:
13903       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
13904       info_ptr += 2;
13905       break;
13906     case DW_FORM_data4:
13907       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
13908       info_ptr += 4;
13909       break;
13910     case DW_FORM_data8:
13911       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
13912       info_ptr += 8;
13913       break;
13914     case DW_FORM_sec_offset:
13915       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
13916       info_ptr += bytes_read;
13917       break;
13918     case DW_FORM_string:
13919       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
13920       DW_STRING_IS_CANONICAL (attr) = 0;
13921       info_ptr += bytes_read;
13922       break;
13923     case DW_FORM_strp:
13924       if (!cu->per_cu->is_dwz)
13925         {
13926           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
13927                                                    &bytes_read);
13928           DW_STRING_IS_CANONICAL (attr) = 0;
13929           info_ptr += bytes_read;
13930           break;
13931         }
13932       /* FALLTHROUGH */
13933     case DW_FORM_GNU_strp_alt:
13934       {
13935         struct dwz_file *dwz = dwarf2_get_dwz_file ();
13936         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
13937                                           &bytes_read);
13938
13939         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
13940         DW_STRING_IS_CANONICAL (attr) = 0;
13941         info_ptr += bytes_read;
13942       }
13943       break;
13944     case DW_FORM_exprloc:
13945     case DW_FORM_block:
13946       blk = dwarf_alloc_block (cu);
13947       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13948       info_ptr += bytes_read;
13949       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
13950       info_ptr += blk->size;
13951       DW_BLOCK (attr) = blk;
13952       break;
13953     case DW_FORM_block1:
13954       blk = dwarf_alloc_block (cu);
13955       blk->size = read_1_byte (abfd, info_ptr);
13956       info_ptr += 1;
13957       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
13958       info_ptr += blk->size;
13959       DW_BLOCK (attr) = blk;
13960       break;
13961     case DW_FORM_data1:
13962       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
13963       info_ptr += 1;
13964       break;
13965     case DW_FORM_flag:
13966       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
13967       info_ptr += 1;
13968       break;
13969     case DW_FORM_flag_present:
13970       DW_UNSND (attr) = 1;
13971       break;
13972     case DW_FORM_sdata:
13973       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
13974       info_ptr += bytes_read;
13975       break;
13976     case DW_FORM_udata:
13977       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13978       info_ptr += bytes_read;
13979       break;
13980     case DW_FORM_ref1:
13981       DW_UNSND (attr) = (cu->header.offset.sect_off
13982                          + read_1_byte (abfd, info_ptr));
13983       info_ptr += 1;
13984       break;
13985     case DW_FORM_ref2:
13986       DW_UNSND (attr) = (cu->header.offset.sect_off
13987                          + read_2_bytes (abfd, info_ptr));
13988       info_ptr += 2;
13989       break;
13990     case DW_FORM_ref4:
13991       DW_UNSND (attr) = (cu->header.offset.sect_off
13992                          + read_4_bytes (abfd, info_ptr));
13993       info_ptr += 4;
13994       break;
13995     case DW_FORM_ref8:
13996       DW_UNSND (attr) = (cu->header.offset.sect_off
13997                          + read_8_bytes (abfd, info_ptr));
13998       info_ptr += 8;
13999       break;
14000     case DW_FORM_ref_sig8:
14001       /* Convert the signature to something we can record in DW_UNSND
14002          for later lookup.
14003          NOTE: This is NULL if the type wasn't found.  */
14004       DW_SIGNATURED_TYPE (attr) =
14005         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14006       info_ptr += 8;
14007       break;
14008     case DW_FORM_ref_udata:
14009       DW_UNSND (attr) = (cu->header.offset.sect_off
14010                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14011       info_ptr += bytes_read;
14012       break;
14013     case DW_FORM_indirect:
14014       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14015       info_ptr += bytes_read;
14016       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14017       break;
14018     case DW_FORM_GNU_addr_index:
14019       if (reader->dwo_file == NULL)
14020         {
14021           /* For now flag a hard error.
14022              Later we can turn this into a complaint.  */
14023           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14024                  dwarf_form_name (form),
14025                  bfd_get_filename (abfd));
14026         }
14027       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14028       info_ptr += bytes_read;
14029       break;
14030     case DW_FORM_GNU_str_index:
14031       if (reader->dwo_file == NULL)
14032         {
14033           /* For now flag a hard error.
14034              Later we can turn this into a complaint if warranted.  */
14035           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14036                  dwarf_form_name (form),
14037                  bfd_get_filename (abfd));
14038         }
14039       {
14040         ULONGEST str_index =
14041           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14042
14043         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14044         DW_STRING_IS_CANONICAL (attr) = 0;
14045         info_ptr += bytes_read;
14046       }
14047       break;
14048     default:
14049       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14050              dwarf_form_name (form),
14051              bfd_get_filename (abfd));
14052     }
14053
14054   /* Super hack.  */
14055   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14056     attr->form = DW_FORM_GNU_ref_alt;
14057
14058   /* We have seen instances where the compiler tried to emit a byte
14059      size attribute of -1 which ended up being encoded as an unsigned
14060      0xffffffff.  Although 0xffffffff is technically a valid size value,
14061      an object of this size seems pretty unlikely so we can relatively
14062      safely treat these cases as if the size attribute was invalid and
14063      treat them as zero by default.  */
14064   if (attr->name == DW_AT_byte_size
14065       && form == DW_FORM_data4
14066       && DW_UNSND (attr) >= 0xffffffff)
14067     {
14068       complaint
14069         (&symfile_complaints,
14070          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14071          hex_string (DW_UNSND (attr)));
14072       DW_UNSND (attr) = 0;
14073     }
14074
14075   return info_ptr;
14076 }
14077
14078 /* Read an attribute described by an abbreviated attribute.  */
14079
14080 static gdb_byte *
14081 read_attribute (const struct die_reader_specs *reader,
14082                 struct attribute *attr, struct attr_abbrev *abbrev,
14083                 gdb_byte *info_ptr)
14084 {
14085   attr->name = abbrev->name;
14086   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14087 }
14088
14089 /* Read dwarf information from a buffer.  */
14090
14091 static unsigned int
14092 read_1_byte (bfd *abfd, const gdb_byte *buf)
14093 {
14094   return bfd_get_8 (abfd, buf);
14095 }
14096
14097 static int
14098 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14099 {
14100   return bfd_get_signed_8 (abfd, buf);
14101 }
14102
14103 static unsigned int
14104 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14105 {
14106   return bfd_get_16 (abfd, buf);
14107 }
14108
14109 static int
14110 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14111 {
14112   return bfd_get_signed_16 (abfd, buf);
14113 }
14114
14115 static unsigned int
14116 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14117 {
14118   return bfd_get_32 (abfd, buf);
14119 }
14120
14121 static int
14122 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14123 {
14124   return bfd_get_signed_32 (abfd, buf);
14125 }
14126
14127 static ULONGEST
14128 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14129 {
14130   return bfd_get_64 (abfd, buf);
14131 }
14132
14133 static CORE_ADDR
14134 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
14135               unsigned int *bytes_read)
14136 {
14137   struct comp_unit_head *cu_header = &cu->header;
14138   CORE_ADDR retval = 0;
14139
14140   if (cu_header->signed_addr_p)
14141     {
14142       switch (cu_header->addr_size)
14143         {
14144         case 2:
14145           retval = bfd_get_signed_16 (abfd, buf);
14146           break;
14147         case 4:
14148           retval = bfd_get_signed_32 (abfd, buf);
14149           break;
14150         case 8:
14151           retval = bfd_get_signed_64 (abfd, buf);
14152           break;
14153         default:
14154           internal_error (__FILE__, __LINE__,
14155                           _("read_address: bad switch, signed [in module %s]"),
14156                           bfd_get_filename (abfd));
14157         }
14158     }
14159   else
14160     {
14161       switch (cu_header->addr_size)
14162         {
14163         case 2:
14164           retval = bfd_get_16 (abfd, buf);
14165           break;
14166         case 4:
14167           retval = bfd_get_32 (abfd, buf);
14168           break;
14169         case 8:
14170           retval = bfd_get_64 (abfd, buf);
14171           break;
14172         default:
14173           internal_error (__FILE__, __LINE__,
14174                           _("read_address: bad switch, "
14175                             "unsigned [in module %s]"),
14176                           bfd_get_filename (abfd));
14177         }
14178     }
14179
14180   *bytes_read = cu_header->addr_size;
14181   return retval;
14182 }
14183
14184 /* Read the initial length from a section.  The (draft) DWARF 3
14185    specification allows the initial length to take up either 4 bytes
14186    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14187    bytes describe the length and all offsets will be 8 bytes in length
14188    instead of 4.
14189
14190    An older, non-standard 64-bit format is also handled by this
14191    function.  The older format in question stores the initial length
14192    as an 8-byte quantity without an escape value.  Lengths greater
14193    than 2^32 aren't very common which means that the initial 4 bytes
14194    is almost always zero.  Since a length value of zero doesn't make
14195    sense for the 32-bit format, this initial zero can be considered to
14196    be an escape value which indicates the presence of the older 64-bit
14197    format.  As written, the code can't detect (old format) lengths
14198    greater than 4GB.  If it becomes necessary to handle lengths
14199    somewhat larger than 4GB, we could allow other small values (such
14200    as the non-sensical values of 1, 2, and 3) to also be used as
14201    escape values indicating the presence of the old format.
14202
14203    The value returned via bytes_read should be used to increment the
14204    relevant pointer after calling read_initial_length().
14205
14206    [ Note:  read_initial_length() and read_offset() are based on the
14207      document entitled "DWARF Debugging Information Format", revision
14208      3, draft 8, dated November 19, 2001.  This document was obtained
14209      from:
14210
14211         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14212
14213      This document is only a draft and is subject to change.  (So beware.)
14214
14215      Details regarding the older, non-standard 64-bit format were
14216      determined empirically by examining 64-bit ELF files produced by
14217      the SGI toolchain on an IRIX 6.5 machine.
14218
14219      - Kevin, July 16, 2002
14220    ] */
14221
14222 static LONGEST
14223 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
14224 {
14225   LONGEST length = bfd_get_32 (abfd, buf);
14226
14227   if (length == 0xffffffff)
14228     {
14229       length = bfd_get_64 (abfd, buf + 4);
14230       *bytes_read = 12;
14231     }
14232   else if (length == 0)
14233     {
14234       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14235       length = bfd_get_64 (abfd, buf);
14236       *bytes_read = 8;
14237     }
14238   else
14239     {
14240       *bytes_read = 4;
14241     }
14242
14243   return length;
14244 }
14245
14246 /* Cover function for read_initial_length.
14247    Returns the length of the object at BUF, and stores the size of the
14248    initial length in *BYTES_READ and stores the size that offsets will be in
14249    *OFFSET_SIZE.
14250    If the initial length size is not equivalent to that specified in
14251    CU_HEADER then issue a complaint.
14252    This is useful when reading non-comp-unit headers.  */
14253
14254 static LONGEST
14255 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
14256                                         const struct comp_unit_head *cu_header,
14257                                         unsigned int *bytes_read,
14258                                         unsigned int *offset_size)
14259 {
14260   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14261
14262   gdb_assert (cu_header->initial_length_size == 4
14263               || cu_header->initial_length_size == 8
14264               || cu_header->initial_length_size == 12);
14265
14266   if (cu_header->initial_length_size != *bytes_read)
14267     complaint (&symfile_complaints,
14268                _("intermixed 32-bit and 64-bit DWARF sections"));
14269
14270   *offset_size = (*bytes_read == 4) ? 4 : 8;
14271   return length;
14272 }
14273
14274 /* Read an offset from the data stream.  The size of the offset is
14275    given by cu_header->offset_size.  */
14276
14277 static LONGEST
14278 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
14279              unsigned int *bytes_read)
14280 {
14281   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14282
14283   *bytes_read = cu_header->offset_size;
14284   return offset;
14285 }
14286
14287 /* Read an offset from the data stream.  */
14288
14289 static LONGEST
14290 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
14291 {
14292   LONGEST retval = 0;
14293
14294   switch (offset_size)
14295     {
14296     case 4:
14297       retval = bfd_get_32 (abfd, buf);
14298       break;
14299     case 8:
14300       retval = bfd_get_64 (abfd, buf);
14301       break;
14302     default:
14303       internal_error (__FILE__, __LINE__,
14304                       _("read_offset_1: bad switch [in module %s]"),
14305                       bfd_get_filename (abfd));
14306     }
14307
14308   return retval;
14309 }
14310
14311 static gdb_byte *
14312 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
14313 {
14314   /* If the size of a host char is 8 bits, we can return a pointer
14315      to the buffer, otherwise we have to copy the data to a buffer
14316      allocated on the temporary obstack.  */
14317   gdb_assert (HOST_CHAR_BIT == 8);
14318   return buf;
14319 }
14320
14321 static char *
14322 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14323 {
14324   /* If the size of a host char is 8 bits, we can return a pointer
14325      to the string, otherwise we have to copy the string to a buffer
14326      allocated on the temporary obstack.  */
14327   gdb_assert (HOST_CHAR_BIT == 8);
14328   if (*buf == '\0')
14329     {
14330       *bytes_read_ptr = 1;
14331       return NULL;
14332     }
14333   *bytes_read_ptr = strlen ((char *) buf) + 1;
14334   return (char *) buf;
14335 }
14336
14337 static char *
14338 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14339 {
14340   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14341   if (dwarf2_per_objfile->str.buffer == NULL)
14342     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14343            bfd_get_filename (abfd));
14344   if (str_offset >= dwarf2_per_objfile->str.size)
14345     error (_("DW_FORM_strp pointing outside of "
14346              ".debug_str section [in module %s]"),
14347            bfd_get_filename (abfd));
14348   gdb_assert (HOST_CHAR_BIT == 8);
14349   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14350     return NULL;
14351   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
14352 }
14353
14354 /* Read a string at offset STR_OFFSET in the .debug_str section from
14355    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14356    the string consists of a single NUL byte, return NULL; otherwise
14357    return a pointer to the string.  */
14358
14359 static char *
14360 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14361 {
14362   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14363
14364   if (dwz->str.buffer == NULL)
14365     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14366              "section [in module %s]"),
14367            bfd_get_filename (dwz->dwz_bfd));
14368   if (str_offset >= dwz->str.size)
14369     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14370              ".debug_str section [in module %s]"),
14371            bfd_get_filename (dwz->dwz_bfd));
14372   gdb_assert (HOST_CHAR_BIT == 8);
14373   if (dwz->str.buffer[str_offset] == '\0')
14374     return NULL;
14375   return (char *) (dwz->str.buffer + str_offset);
14376 }
14377
14378 static char *
14379 read_indirect_string (bfd *abfd, gdb_byte *buf,
14380                       const struct comp_unit_head *cu_header,
14381                       unsigned int *bytes_read_ptr)
14382 {
14383   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14384
14385   return read_indirect_string_at_offset (abfd, str_offset);
14386 }
14387
14388 static ULONGEST
14389 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14390 {
14391   ULONGEST result;
14392   unsigned int num_read;
14393   int i, shift;
14394   unsigned char byte;
14395
14396   result = 0;
14397   shift = 0;
14398   num_read = 0;
14399   i = 0;
14400   while (1)
14401     {
14402       byte = bfd_get_8 (abfd, buf);
14403       buf++;
14404       num_read++;
14405       result |= ((ULONGEST) (byte & 127) << shift);
14406       if ((byte & 128) == 0)
14407         {
14408           break;
14409         }
14410       shift += 7;
14411     }
14412   *bytes_read_ptr = num_read;
14413   return result;
14414 }
14415
14416 static LONGEST
14417 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14418 {
14419   LONGEST result;
14420   int i, shift, num_read;
14421   unsigned char byte;
14422
14423   result = 0;
14424   shift = 0;
14425   num_read = 0;
14426   i = 0;
14427   while (1)
14428     {
14429       byte = bfd_get_8 (abfd, buf);
14430       buf++;
14431       num_read++;
14432       result |= ((LONGEST) (byte & 127) << shift);
14433       shift += 7;
14434       if ((byte & 128) == 0)
14435         {
14436           break;
14437         }
14438     }
14439   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14440     result |= -(((LONGEST) 1) << shift);
14441   *bytes_read_ptr = num_read;
14442   return result;
14443 }
14444
14445 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14446    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14447    ADDR_SIZE is the size of addresses from the CU header.  */
14448
14449 static CORE_ADDR
14450 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14451 {
14452   struct objfile *objfile = dwarf2_per_objfile->objfile;
14453   bfd *abfd = objfile->obfd;
14454   const gdb_byte *info_ptr;
14455
14456   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14457   if (dwarf2_per_objfile->addr.buffer == NULL)
14458     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14459            objfile->name);
14460   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14461     error (_("DW_FORM_addr_index pointing outside of "
14462              ".debug_addr section [in module %s]"),
14463            objfile->name);
14464   info_ptr = (dwarf2_per_objfile->addr.buffer
14465               + addr_base + addr_index * addr_size);
14466   if (addr_size == 4)
14467     return bfd_get_32 (abfd, info_ptr);
14468   else
14469     return bfd_get_64 (abfd, info_ptr);
14470 }
14471
14472 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14473
14474 static CORE_ADDR
14475 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14476 {
14477   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14478 }
14479
14480 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14481
14482 static CORE_ADDR
14483 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
14484                              unsigned int *bytes_read)
14485 {
14486   bfd *abfd = cu->objfile->obfd;
14487   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14488
14489   return read_addr_index (cu, addr_index);
14490 }
14491
14492 /* Data structure to pass results from dwarf2_read_addr_index_reader
14493    back to dwarf2_read_addr_index.  */
14494
14495 struct dwarf2_read_addr_index_data
14496 {
14497   ULONGEST addr_base;
14498   int addr_size;
14499 };
14500
14501 /* die_reader_func for dwarf2_read_addr_index.  */
14502
14503 static void
14504 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14505                                gdb_byte *info_ptr,
14506                                struct die_info *comp_unit_die,
14507                                int has_children,
14508                                void *data)
14509 {
14510   struct dwarf2_cu *cu = reader->cu;
14511   struct dwarf2_read_addr_index_data *aidata =
14512     (struct dwarf2_read_addr_index_data *) data;
14513
14514   aidata->addr_base = cu->addr_base;
14515   aidata->addr_size = cu->header.addr_size;
14516 }
14517
14518 /* Given an index in .debug_addr, fetch the value.
14519    NOTE: This can be called during dwarf expression evaluation,
14520    long after the debug information has been read, and thus per_cu->cu
14521    may no longer exist.  */
14522
14523 CORE_ADDR
14524 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14525                         unsigned int addr_index)
14526 {
14527   struct objfile *objfile = per_cu->objfile;
14528   struct dwarf2_cu *cu = per_cu->cu;
14529   ULONGEST addr_base;
14530   int addr_size;
14531
14532   /* This is intended to be called from outside this file.  */
14533   dw2_setup (objfile);
14534
14535   /* We need addr_base and addr_size.
14536      If we don't have PER_CU->cu, we have to get it.
14537      Nasty, but the alternative is storing the needed info in PER_CU,
14538      which at this point doesn't seem justified: it's not clear how frequently
14539      it would get used and it would increase the size of every PER_CU.
14540      Entry points like dwarf2_per_cu_addr_size do a similar thing
14541      so we're not in uncharted territory here.
14542      Alas we need to be a bit more complicated as addr_base is contained
14543      in the DIE.
14544
14545      We don't need to read the entire CU(/TU).
14546      We just need the header and top level die.
14547
14548      IWBN to use the aging mechanism to let us lazily later discard the CU.
14549      For now we skip this optimization.  */
14550
14551   if (cu != NULL)
14552     {
14553       addr_base = cu->addr_base;
14554       addr_size = cu->header.addr_size;
14555     }
14556   else
14557     {
14558       struct dwarf2_read_addr_index_data aidata;
14559
14560       /* Note: We can't use init_cutu_and_read_dies_simple here,
14561          we need addr_base.  */
14562       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14563                                dwarf2_read_addr_index_reader, &aidata);
14564       addr_base = aidata.addr_base;
14565       addr_size = aidata.addr_size;
14566     }
14567
14568   return read_addr_index_1 (addr_index, addr_base, addr_size);
14569 }
14570
14571 /* Given a DW_AT_str_index, fetch the string.  */
14572
14573 static char *
14574 read_str_index (const struct die_reader_specs *reader,
14575                 struct dwarf2_cu *cu, ULONGEST str_index)
14576 {
14577   struct objfile *objfile = dwarf2_per_objfile->objfile;
14578   const char *dwo_name = objfile->name;
14579   bfd *abfd = objfile->obfd;
14580   struct dwo_sections *sections = &reader->dwo_file->sections;
14581   gdb_byte *info_ptr;
14582   ULONGEST str_offset;
14583
14584   dwarf2_read_section (objfile, &sections->str);
14585   dwarf2_read_section (objfile, &sections->str_offsets);
14586   if (sections->str.buffer == NULL)
14587     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14588              " in CU at offset 0x%lx [in module %s]"),
14589            (long) cu->header.offset.sect_off, dwo_name);
14590   if (sections->str_offsets.buffer == NULL)
14591     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14592              " in CU at offset 0x%lx [in module %s]"),
14593            (long) cu->header.offset.sect_off, dwo_name);
14594   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14595     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14596              " section in CU at offset 0x%lx [in module %s]"),
14597            (long) cu->header.offset.sect_off, dwo_name);
14598   info_ptr = (sections->str_offsets.buffer
14599               + str_index * cu->header.offset_size);
14600   if (cu->header.offset_size == 4)
14601     str_offset = bfd_get_32 (abfd, info_ptr);
14602   else
14603     str_offset = bfd_get_64 (abfd, info_ptr);
14604   if (str_offset >= sections->str.size)
14605     error (_("Offset from DW_FORM_str_index pointing outside of"
14606              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14607            (long) cu->header.offset.sect_off, dwo_name);
14608   return (char *) (sections->str.buffer + str_offset);
14609 }
14610
14611 /* Return the length of an LEB128 number in BUF.  */
14612
14613 static int
14614 leb128_size (const gdb_byte *buf)
14615 {
14616   const gdb_byte *begin = buf;
14617   gdb_byte byte;
14618
14619   while (1)
14620     {
14621       byte = *buf++;
14622       if ((byte & 128) == 0)
14623         return buf - begin;
14624     }
14625 }
14626
14627 static void
14628 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14629 {
14630   switch (lang)
14631     {
14632     case DW_LANG_C89:
14633     case DW_LANG_C99:
14634     case DW_LANG_C:
14635       cu->language = language_c;
14636       break;
14637     case DW_LANG_C_plus_plus:
14638       cu->language = language_cplus;
14639       break;
14640     case DW_LANG_D:
14641       cu->language = language_d;
14642       break;
14643     case DW_LANG_Fortran77:
14644     case DW_LANG_Fortran90:
14645     case DW_LANG_Fortran95:
14646       cu->language = language_fortran;
14647       break;
14648     case DW_LANG_Go:
14649       cu->language = language_go;
14650       break;
14651     case DW_LANG_Mips_Assembler:
14652       cu->language = language_asm;
14653       break;
14654     case DW_LANG_Java:
14655       cu->language = language_java;
14656       break;
14657     case DW_LANG_Ada83:
14658     case DW_LANG_Ada95:
14659       cu->language = language_ada;
14660       break;
14661     case DW_LANG_Modula2:
14662       cu->language = language_m2;
14663       break;
14664     case DW_LANG_Pascal83:
14665       cu->language = language_pascal;
14666       break;
14667     case DW_LANG_ObjC:
14668       cu->language = language_objc;
14669       break;
14670     case DW_LANG_Cobol74:
14671     case DW_LANG_Cobol85:
14672     default:
14673       cu->language = language_minimal;
14674       break;
14675     }
14676   cu->language_defn = language_def (cu->language);
14677 }
14678
14679 /* Return the named attribute or NULL if not there.  */
14680
14681 static struct attribute *
14682 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
14683 {
14684   for (;;)
14685     {
14686       unsigned int i;
14687       struct attribute *spec = NULL;
14688
14689       for (i = 0; i < die->num_attrs; ++i)
14690         {
14691           if (die->attrs[i].name == name)
14692             return &die->attrs[i];
14693           if (die->attrs[i].name == DW_AT_specification
14694               || die->attrs[i].name == DW_AT_abstract_origin)
14695             spec = &die->attrs[i];
14696         }
14697
14698       if (!spec)
14699         break;
14700
14701       die = follow_die_ref (die, spec, &cu);
14702     }
14703
14704   return NULL;
14705 }
14706
14707 /* Return the named attribute or NULL if not there,
14708    but do not follow DW_AT_specification, etc.
14709    This is for use in contexts where we're reading .debug_types dies.
14710    Following DW_AT_specification, DW_AT_abstract_origin will take us
14711    back up the chain, and we want to go down.  */
14712
14713 static struct attribute *
14714 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
14715 {
14716   unsigned int i;
14717
14718   for (i = 0; i < die->num_attrs; ++i)
14719     if (die->attrs[i].name == name)
14720       return &die->attrs[i];
14721
14722   return NULL;
14723 }
14724
14725 /* Return non-zero iff the attribute NAME is defined for the given DIE,
14726    and holds a non-zero value.  This function should only be used for
14727    DW_FORM_flag or DW_FORM_flag_present attributes.  */
14728
14729 static int
14730 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
14731 {
14732   struct attribute *attr = dwarf2_attr (die, name, cu);
14733
14734   return (attr && DW_UNSND (attr));
14735 }
14736
14737 static int
14738 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
14739 {
14740   /* A DIE is a declaration if it has a DW_AT_declaration attribute
14741      which value is non-zero.  However, we have to be careful with
14742      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
14743      (via dwarf2_flag_true_p) follows this attribute.  So we may
14744      end up accidently finding a declaration attribute that belongs
14745      to a different DIE referenced by the specification attribute,
14746      even though the given DIE does not have a declaration attribute.  */
14747   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
14748           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
14749 }
14750
14751 /* Return the die giving the specification for DIE, if there is
14752    one.  *SPEC_CU is the CU containing DIE on input, and the CU
14753    containing the return value on output.  If there is no
14754    specification, but there is an abstract origin, that is
14755    returned.  */
14756
14757 static struct die_info *
14758 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
14759 {
14760   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
14761                                              *spec_cu);
14762
14763   if (spec_attr == NULL)
14764     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
14765
14766   if (spec_attr == NULL)
14767     return NULL;
14768   else
14769     return follow_die_ref (die, spec_attr, spec_cu);
14770 }
14771
14772 /* Free the line_header structure *LH, and any arrays and strings it
14773    refers to.
14774    NOTE: This is also used as a "cleanup" function.  */
14775
14776 static void
14777 free_line_header (struct line_header *lh)
14778 {
14779   if (lh->standard_opcode_lengths)
14780     xfree (lh->standard_opcode_lengths);
14781
14782   /* Remember that all the lh->file_names[i].name pointers are
14783      pointers into debug_line_buffer, and don't need to be freed.  */
14784   if (lh->file_names)
14785     xfree (lh->file_names);
14786
14787   /* Similarly for the include directory names.  */
14788   if (lh->include_dirs)
14789     xfree (lh->include_dirs);
14790
14791   xfree (lh);
14792 }
14793
14794 /* Add an entry to LH's include directory table.  */
14795
14796 static void
14797 add_include_dir (struct line_header *lh, char *include_dir)
14798 {
14799   /* Grow the array if necessary.  */
14800   if (lh->include_dirs_size == 0)
14801     {
14802       lh->include_dirs_size = 1; /* for testing */
14803       lh->include_dirs = xmalloc (lh->include_dirs_size
14804                                   * sizeof (*lh->include_dirs));
14805     }
14806   else if (lh->num_include_dirs >= lh->include_dirs_size)
14807     {
14808       lh->include_dirs_size *= 2;
14809       lh->include_dirs = xrealloc (lh->include_dirs,
14810                                    (lh->include_dirs_size
14811                                     * sizeof (*lh->include_dirs)));
14812     }
14813
14814   lh->include_dirs[lh->num_include_dirs++] = include_dir;
14815 }
14816
14817 /* Add an entry to LH's file name table.  */
14818
14819 static void
14820 add_file_name (struct line_header *lh,
14821                char *name,
14822                unsigned int dir_index,
14823                unsigned int mod_time,
14824                unsigned int length)
14825 {
14826   struct file_entry *fe;
14827
14828   /* Grow the array if necessary.  */
14829   if (lh->file_names_size == 0)
14830     {
14831       lh->file_names_size = 1; /* for testing */
14832       lh->file_names = xmalloc (lh->file_names_size
14833                                 * sizeof (*lh->file_names));
14834     }
14835   else if (lh->num_file_names >= lh->file_names_size)
14836     {
14837       lh->file_names_size *= 2;
14838       lh->file_names = xrealloc (lh->file_names,
14839                                  (lh->file_names_size
14840                                   * sizeof (*lh->file_names)));
14841     }
14842
14843   fe = &lh->file_names[lh->num_file_names++];
14844   fe->name = name;
14845   fe->dir_index = dir_index;
14846   fe->mod_time = mod_time;
14847   fe->length = length;
14848   fe->included_p = 0;
14849   fe->symtab = NULL;
14850 }
14851
14852 /* A convenience function to find the proper .debug_line section for a
14853    CU.  */
14854
14855 static struct dwarf2_section_info *
14856 get_debug_line_section (struct dwarf2_cu *cu)
14857 {
14858   struct dwarf2_section_info *section;
14859
14860   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
14861      DWO file.  */
14862   if (cu->dwo_unit && cu->per_cu->is_debug_types)
14863     section = &cu->dwo_unit->dwo_file->sections.line;
14864   else if (cu->per_cu->is_dwz)
14865     {
14866       struct dwz_file *dwz = dwarf2_get_dwz_file ();
14867
14868       section = &dwz->line;
14869     }
14870   else
14871     section = &dwarf2_per_objfile->line;
14872
14873   return section;
14874 }
14875
14876 /* Read the statement program header starting at OFFSET in
14877    .debug_line, or .debug_line.dwo.  Return a pointer
14878    to a struct line_header, allocated using xmalloc.
14879
14880    NOTE: the strings in the include directory and file name tables of
14881    the returned object point into the dwarf line section buffer,
14882    and must not be freed.  */
14883
14884 static struct line_header *
14885 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
14886 {
14887   struct cleanup *back_to;
14888   struct line_header *lh;
14889   gdb_byte *line_ptr;
14890   unsigned int bytes_read, offset_size;
14891   int i;
14892   char *cur_dir, *cur_file;
14893   struct dwarf2_section_info *section;
14894   bfd *abfd;
14895
14896   section = get_debug_line_section (cu);
14897   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
14898   if (section->buffer == NULL)
14899     {
14900       if (cu->dwo_unit && cu->per_cu->is_debug_types)
14901         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
14902       else
14903         complaint (&symfile_complaints, _("missing .debug_line section"));
14904       return 0;
14905     }
14906
14907   /* We can't do this until we know the section is non-empty.
14908      Only then do we know we have such a section.  */
14909   abfd = section->asection->owner;
14910
14911   /* Make sure that at least there's room for the total_length field.
14912      That could be 12 bytes long, but we're just going to fudge that.  */
14913   if (offset + 4 >= section->size)
14914     {
14915       dwarf2_statement_list_fits_in_line_number_section_complaint ();
14916       return 0;
14917     }
14918
14919   lh = xmalloc (sizeof (*lh));
14920   memset (lh, 0, sizeof (*lh));
14921   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
14922                           (void *) lh);
14923
14924   line_ptr = section->buffer + offset;
14925
14926   /* Read in the header.  */
14927   lh->total_length =
14928     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
14929                                             &bytes_read, &offset_size);
14930   line_ptr += bytes_read;
14931   if (line_ptr + lh->total_length > (section->buffer + section->size))
14932     {
14933       dwarf2_statement_list_fits_in_line_number_section_complaint ();
14934       return 0;
14935     }
14936   lh->statement_program_end = line_ptr + lh->total_length;
14937   lh->version = read_2_bytes (abfd, line_ptr);
14938   line_ptr += 2;
14939   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
14940   line_ptr += offset_size;
14941   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
14942   line_ptr += 1;
14943   if (lh->version >= 4)
14944     {
14945       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
14946       line_ptr += 1;
14947     }
14948   else
14949     lh->maximum_ops_per_instruction = 1;
14950
14951   if (lh->maximum_ops_per_instruction == 0)
14952     {
14953       lh->maximum_ops_per_instruction = 1;
14954       complaint (&symfile_complaints,
14955                  _("invalid maximum_ops_per_instruction "
14956                    "in `.debug_line' section"));
14957     }
14958
14959   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
14960   line_ptr += 1;
14961   lh->line_base = read_1_signed_byte (abfd, line_ptr);
14962   line_ptr += 1;
14963   lh->line_range = read_1_byte (abfd, line_ptr);
14964   line_ptr += 1;
14965   lh->opcode_base = read_1_byte (abfd, line_ptr);
14966   line_ptr += 1;
14967   lh->standard_opcode_lengths
14968     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
14969
14970   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
14971   for (i = 1; i < lh->opcode_base; ++i)
14972     {
14973       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
14974       line_ptr += 1;
14975     }
14976
14977   /* Read directory table.  */
14978   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
14979     {
14980       line_ptr += bytes_read;
14981       add_include_dir (lh, cur_dir);
14982     }
14983   line_ptr += bytes_read;
14984
14985   /* Read file name table.  */
14986   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
14987     {
14988       unsigned int dir_index, mod_time, length;
14989
14990       line_ptr += bytes_read;
14991       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14992       line_ptr += bytes_read;
14993       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14994       line_ptr += bytes_read;
14995       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
14996       line_ptr += bytes_read;
14997
14998       add_file_name (lh, cur_file, dir_index, mod_time, length);
14999     }
15000   line_ptr += bytes_read;
15001   lh->statement_program_start = line_ptr;
15002
15003   if (line_ptr > (section->buffer + section->size))
15004     complaint (&symfile_complaints,
15005                _("line number info header doesn't "
15006                  "fit in `.debug_line' section"));
15007
15008   discard_cleanups (back_to);
15009   return lh;
15010 }
15011
15012 /* Subroutine of dwarf_decode_lines to simplify it.
15013    Return the file name of the psymtab for included file FILE_INDEX
15014    in line header LH of PST.
15015    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15016    If space for the result is malloc'd, it will be freed by a cleanup.
15017    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
15018
15019 static char *
15020 psymtab_include_file_name (const struct line_header *lh, int file_index,
15021                            const struct partial_symtab *pst,
15022                            const char *comp_dir)
15023 {
15024   const struct file_entry fe = lh->file_names [file_index];
15025   char *include_name = fe.name;
15026   char *include_name_to_compare = include_name;
15027   char *dir_name = NULL;
15028   const char *pst_filename;
15029   char *copied_name = NULL;
15030   int file_is_pst;
15031
15032   if (fe.dir_index)
15033     dir_name = lh->include_dirs[fe.dir_index - 1];
15034
15035   if (!IS_ABSOLUTE_PATH (include_name)
15036       && (dir_name != NULL || comp_dir != NULL))
15037     {
15038       /* Avoid creating a duplicate psymtab for PST.
15039          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15040          Before we do the comparison, however, we need to account
15041          for DIR_NAME and COMP_DIR.
15042          First prepend dir_name (if non-NULL).  If we still don't
15043          have an absolute path prepend comp_dir (if non-NULL).
15044          However, the directory we record in the include-file's
15045          psymtab does not contain COMP_DIR (to match the
15046          corresponding symtab(s)).
15047
15048          Example:
15049
15050          bash$ cd /tmp
15051          bash$ gcc -g ./hello.c
15052          include_name = "hello.c"
15053          dir_name = "."
15054          DW_AT_comp_dir = comp_dir = "/tmp"
15055          DW_AT_name = "./hello.c"  */
15056
15057       if (dir_name != NULL)
15058         {
15059           include_name = concat (dir_name, SLASH_STRING,
15060                                  include_name, (char *)NULL);
15061           include_name_to_compare = include_name;
15062           make_cleanup (xfree, include_name);
15063         }
15064       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15065         {
15066           include_name_to_compare = concat (comp_dir, SLASH_STRING,
15067                                             include_name, (char *)NULL);
15068         }
15069     }
15070
15071   pst_filename = pst->filename;
15072   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15073     {
15074       copied_name = concat (pst->dirname, SLASH_STRING,
15075                             pst_filename, (char *)NULL);
15076       pst_filename = copied_name;
15077     }
15078
15079   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15080
15081   if (include_name_to_compare != include_name)
15082     xfree (include_name_to_compare);
15083   if (copied_name != NULL)
15084     xfree (copied_name);
15085
15086   if (file_is_pst)
15087     return NULL;
15088   return include_name;
15089 }
15090
15091 /* Ignore this record_line request.  */
15092
15093 static void
15094 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15095 {
15096   return;
15097 }
15098
15099 /* Subroutine of dwarf_decode_lines to simplify it.
15100    Process the line number information in LH.  */
15101
15102 static void
15103 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15104                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15105 {
15106   gdb_byte *line_ptr, *extended_end;
15107   gdb_byte *line_end;
15108   unsigned int bytes_read, extended_len;
15109   unsigned char op_code, extended_op, adj_opcode;
15110   CORE_ADDR baseaddr;
15111   struct objfile *objfile = cu->objfile;
15112   bfd *abfd = objfile->obfd;
15113   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15114   const int decode_for_pst_p = (pst != NULL);
15115   struct subfile *last_subfile = NULL;
15116   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15117     = record_line;
15118
15119   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15120
15121   line_ptr = lh->statement_program_start;
15122   line_end = lh->statement_program_end;
15123
15124   /* Read the statement sequences until there's nothing left.  */
15125   while (line_ptr < line_end)
15126     {
15127       /* state machine registers  */
15128       CORE_ADDR address = 0;
15129       unsigned int file = 1;
15130       unsigned int line = 1;
15131       unsigned int column = 0;
15132       int is_stmt = lh->default_is_stmt;
15133       int basic_block = 0;
15134       int end_sequence = 0;
15135       CORE_ADDR addr;
15136       unsigned char op_index = 0;
15137
15138       if (!decode_for_pst_p && lh->num_file_names >= file)
15139         {
15140           /* Start a subfile for the current file of the state machine.  */
15141           /* lh->include_dirs and lh->file_names are 0-based, but the
15142              directory and file name numbers in the statement program
15143              are 1-based.  */
15144           struct file_entry *fe = &lh->file_names[file - 1];
15145           char *dir = NULL;
15146
15147           if (fe->dir_index)
15148             dir = lh->include_dirs[fe->dir_index - 1];
15149
15150           dwarf2_start_subfile (fe->name, dir, comp_dir);
15151         }
15152
15153       /* Decode the table.  */
15154       while (!end_sequence)
15155         {
15156           op_code = read_1_byte (abfd, line_ptr);
15157           line_ptr += 1;
15158           if (line_ptr > line_end)
15159             {
15160               dwarf2_debug_line_missing_end_sequence_complaint ();
15161               break;
15162             }
15163
15164           if (op_code >= lh->opcode_base)
15165             {
15166               /* Special operand.  */
15167               adj_opcode = op_code - lh->opcode_base;
15168               address += (((op_index + (adj_opcode / lh->line_range))
15169                            / lh->maximum_ops_per_instruction)
15170                           * lh->minimum_instruction_length);
15171               op_index = ((op_index + (adj_opcode / lh->line_range))
15172                           % lh->maximum_ops_per_instruction);
15173               line += lh->line_base + (adj_opcode % lh->line_range);
15174               if (lh->num_file_names < file || file == 0)
15175                 dwarf2_debug_line_missing_file_complaint ();
15176               /* For now we ignore lines not starting on an
15177                  instruction boundary.  */
15178               else if (op_index == 0)
15179                 {
15180                   lh->file_names[file - 1].included_p = 1;
15181                   if (!decode_for_pst_p && is_stmt)
15182                     {
15183                       if (last_subfile != current_subfile)
15184                         {
15185                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15186                           if (last_subfile)
15187                             (*p_record_line) (last_subfile, 0, addr);
15188                           last_subfile = current_subfile;
15189                         }
15190                       /* Append row to matrix using current values.  */
15191                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15192                       (*p_record_line) (current_subfile, line, addr);
15193                     }
15194                 }
15195               basic_block = 0;
15196             }
15197           else switch (op_code)
15198             {
15199             case DW_LNS_extended_op:
15200               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15201                                                    &bytes_read);
15202               line_ptr += bytes_read;
15203               extended_end = line_ptr + extended_len;
15204               extended_op = read_1_byte (abfd, line_ptr);
15205               line_ptr += 1;
15206               switch (extended_op)
15207                 {
15208                 case DW_LNE_end_sequence:
15209                   p_record_line = record_line;
15210                   end_sequence = 1;
15211                   break;
15212                 case DW_LNE_set_address:
15213                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15214
15215                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15216                     {
15217                       /* This line table is for a function which has been
15218                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15219
15220                       long line_offset
15221                         = line_ptr - get_debug_line_section (cu)->buffer;
15222
15223                       complaint (&symfile_complaints,
15224                                  _(".debug_line address at offset 0x%lx is 0 "
15225                                    "[in module %s]"),
15226                                  line_offset, objfile->name);
15227                       p_record_line = noop_record_line;
15228                     }
15229
15230                   op_index = 0;
15231                   line_ptr += bytes_read;
15232                   address += baseaddr;
15233                   break;
15234                 case DW_LNE_define_file:
15235                   {
15236                     char *cur_file;
15237                     unsigned int dir_index, mod_time, length;
15238
15239                     cur_file = read_direct_string (abfd, line_ptr,
15240                                                    &bytes_read);
15241                     line_ptr += bytes_read;
15242                     dir_index =
15243                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15244                     line_ptr += bytes_read;
15245                     mod_time =
15246                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15247                     line_ptr += bytes_read;
15248                     length =
15249                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15250                     line_ptr += bytes_read;
15251                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15252                   }
15253                   break;
15254                 case DW_LNE_set_discriminator:
15255                   /* The discriminator is not interesting to the debugger;
15256                      just ignore it.  */
15257                   line_ptr = extended_end;
15258                   break;
15259                 default:
15260                   complaint (&symfile_complaints,
15261                              _("mangled .debug_line section"));
15262                   return;
15263                 }
15264               /* Make sure that we parsed the extended op correctly.  If e.g.
15265                  we expected a different address size than the producer used,
15266                  we may have read the wrong number of bytes.  */
15267               if (line_ptr != extended_end)
15268                 {
15269                   complaint (&symfile_complaints,
15270                              _("mangled .debug_line section"));
15271                   return;
15272                 }
15273               break;
15274             case DW_LNS_copy:
15275               if (lh->num_file_names < file || file == 0)
15276                 dwarf2_debug_line_missing_file_complaint ();
15277               else
15278                 {
15279                   lh->file_names[file - 1].included_p = 1;
15280                   if (!decode_for_pst_p && is_stmt)
15281                     {
15282                       if (last_subfile != current_subfile)
15283                         {
15284                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15285                           if (last_subfile)
15286                             (*p_record_line) (last_subfile, 0, addr);
15287                           last_subfile = current_subfile;
15288                         }
15289                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15290                       (*p_record_line) (current_subfile, line, addr);
15291                     }
15292                 }
15293               basic_block = 0;
15294               break;
15295             case DW_LNS_advance_pc:
15296               {
15297                 CORE_ADDR adjust
15298                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15299
15300                 address += (((op_index + adjust)
15301                              / lh->maximum_ops_per_instruction)
15302                             * lh->minimum_instruction_length);
15303                 op_index = ((op_index + adjust)
15304                             % lh->maximum_ops_per_instruction);
15305                 line_ptr += bytes_read;
15306               }
15307               break;
15308             case DW_LNS_advance_line:
15309               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15310               line_ptr += bytes_read;
15311               break;
15312             case DW_LNS_set_file:
15313               {
15314                 /* The arrays lh->include_dirs and lh->file_names are
15315                    0-based, but the directory and file name numbers in
15316                    the statement program are 1-based.  */
15317                 struct file_entry *fe;
15318                 char *dir = NULL;
15319
15320                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15321                 line_ptr += bytes_read;
15322                 if (lh->num_file_names < file || file == 0)
15323                   dwarf2_debug_line_missing_file_complaint ();
15324                 else
15325                   {
15326                     fe = &lh->file_names[file - 1];
15327                     if (fe->dir_index)
15328                       dir = lh->include_dirs[fe->dir_index - 1];
15329                     if (!decode_for_pst_p)
15330                       {
15331                         last_subfile = current_subfile;
15332                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15333                       }
15334                   }
15335               }
15336               break;
15337             case DW_LNS_set_column:
15338               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15339               line_ptr += bytes_read;
15340               break;
15341             case DW_LNS_negate_stmt:
15342               is_stmt = (!is_stmt);
15343               break;
15344             case DW_LNS_set_basic_block:
15345               basic_block = 1;
15346               break;
15347             /* Add to the address register of the state machine the
15348                address increment value corresponding to special opcode
15349                255.  I.e., this value is scaled by the minimum
15350                instruction length since special opcode 255 would have
15351                scaled the increment.  */
15352             case DW_LNS_const_add_pc:
15353               {
15354                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15355
15356                 address += (((op_index + adjust)
15357                              / lh->maximum_ops_per_instruction)
15358                             * lh->minimum_instruction_length);
15359                 op_index = ((op_index + adjust)
15360                             % lh->maximum_ops_per_instruction);
15361               }
15362               break;
15363             case DW_LNS_fixed_advance_pc:
15364               address += read_2_bytes (abfd, line_ptr);
15365               op_index = 0;
15366               line_ptr += 2;
15367               break;
15368             default:
15369               {
15370                 /* Unknown standard opcode, ignore it.  */
15371                 int i;
15372
15373                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15374                   {
15375                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15376                     line_ptr += bytes_read;
15377                   }
15378               }
15379             }
15380         }
15381       if (lh->num_file_names < file || file == 0)
15382         dwarf2_debug_line_missing_file_complaint ();
15383       else
15384         {
15385           lh->file_names[file - 1].included_p = 1;
15386           if (!decode_for_pst_p)
15387             {
15388               addr = gdbarch_addr_bits_remove (gdbarch, address);
15389               (*p_record_line) (current_subfile, 0, addr);
15390             }
15391         }
15392     }
15393 }
15394
15395 /* Decode the Line Number Program (LNP) for the given line_header
15396    structure and CU.  The actual information extracted and the type
15397    of structures created from the LNP depends on the value of PST.
15398
15399    1. If PST is NULL, then this procedure uses the data from the program
15400       to create all necessary symbol tables, and their linetables.
15401
15402    2. If PST is not NULL, this procedure reads the program to determine
15403       the list of files included by the unit represented by PST, and
15404       builds all the associated partial symbol tables.
15405
15406    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15407    It is used for relative paths in the line table.
15408    NOTE: When processing partial symtabs (pst != NULL),
15409    comp_dir == pst->dirname.
15410
15411    NOTE: It is important that psymtabs have the same file name (via strcmp)
15412    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15413    symtab we don't use it in the name of the psymtabs we create.
15414    E.g. expand_line_sal requires this when finding psymtabs to expand.
15415    A good testcase for this is mb-inline.exp.  */
15416
15417 static void
15418 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15419                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15420                     int want_line_info)
15421 {
15422   struct objfile *objfile = cu->objfile;
15423   const int decode_for_pst_p = (pst != NULL);
15424   struct subfile *first_subfile = current_subfile;
15425
15426   if (want_line_info)
15427     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15428
15429   if (decode_for_pst_p)
15430     {
15431       int file_index;
15432
15433       /* Now that we're done scanning the Line Header Program, we can
15434          create the psymtab of each included file.  */
15435       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15436         if (lh->file_names[file_index].included_p == 1)
15437           {
15438             char *include_name =
15439               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15440             if (include_name != NULL)
15441               dwarf2_create_include_psymtab (include_name, pst, objfile);
15442           }
15443     }
15444   else
15445     {
15446       /* Make sure a symtab is created for every file, even files
15447          which contain only variables (i.e. no code with associated
15448          line numbers).  */
15449       int i;
15450
15451       for (i = 0; i < lh->num_file_names; i++)
15452         {
15453           char *dir = NULL;
15454           struct file_entry *fe;
15455
15456           fe = &lh->file_names[i];
15457           if (fe->dir_index)
15458             dir = lh->include_dirs[fe->dir_index - 1];
15459           dwarf2_start_subfile (fe->name, dir, comp_dir);
15460
15461           /* Skip the main file; we don't need it, and it must be
15462              allocated last, so that it will show up before the
15463              non-primary symtabs in the objfile's symtab list.  */
15464           if (current_subfile == first_subfile)
15465             continue;
15466
15467           if (current_subfile->symtab == NULL)
15468             current_subfile->symtab = allocate_symtab (current_subfile->name,
15469                                                        objfile);
15470           fe->symtab = current_subfile->symtab;
15471         }
15472     }
15473 }
15474
15475 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15476    DIRNAME the name of the source directory which contains FILENAME
15477    or NULL if not known.  COMP_DIR is the compilation directory for the
15478    linetable's compilation unit or NULL if not known.
15479    This routine tries to keep line numbers from identical absolute and
15480    relative file names in a common subfile.
15481
15482    Using the `list' example from the GDB testsuite, which resides in
15483    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15484    of /srcdir/list0.c yields the following debugging information for list0.c:
15485
15486    DW_AT_name:          /srcdir/list0.c
15487    DW_AT_comp_dir:              /compdir
15488    files.files[0].name: list0.h
15489    files.files[0].dir:  /srcdir
15490    files.files[1].name: list0.c
15491    files.files[1].dir:  /srcdir
15492
15493    The line number information for list0.c has to end up in a single
15494    subfile, so that `break /srcdir/list0.c:1' works as expected.
15495    start_subfile will ensure that this happens provided that we pass the
15496    concatenation of files.files[1].dir and files.files[1].name as the
15497    subfile's name.  */
15498
15499 static void
15500 dwarf2_start_subfile (char *filename, const char *dirname,
15501                       const char *comp_dir)
15502 {
15503   char *fullname;
15504
15505   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15506      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15507      second argument to start_subfile.  To be consistent, we do the
15508      same here.  In order not to lose the line information directory,
15509      we concatenate it to the filename when it makes sense.
15510      Note that the Dwarf3 standard says (speaking of filenames in line
15511      information): ``The directory index is ignored for file names
15512      that represent full path names''.  Thus ignoring dirname in the
15513      `else' branch below isn't an issue.  */
15514
15515   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15516     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15517   else
15518     fullname = filename;
15519
15520   start_subfile (fullname, comp_dir);
15521
15522   if (fullname != filename)
15523     xfree (fullname);
15524 }
15525
15526 /* Start a symtab for DWARF.
15527    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15528
15529 static void
15530 dwarf2_start_symtab (struct dwarf2_cu *cu,
15531                      char *name, char *comp_dir, CORE_ADDR low_pc)
15532 {
15533   start_symtab (name, comp_dir, low_pc);
15534   record_debugformat ("DWARF 2");
15535   record_producer (cu->producer);
15536
15537   /* We assume that we're processing GCC output.  */
15538   processing_gcc_compilation = 2;
15539
15540   processing_has_namespace_info = 0;
15541 }
15542
15543 static void
15544 var_decode_location (struct attribute *attr, struct symbol *sym,
15545                      struct dwarf2_cu *cu)
15546 {
15547   struct objfile *objfile = cu->objfile;
15548   struct comp_unit_head *cu_header = &cu->header;
15549
15550   /* NOTE drow/2003-01-30: There used to be a comment and some special
15551      code here to turn a symbol with DW_AT_external and a
15552      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15553      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15554      with some versions of binutils) where shared libraries could have
15555      relocations against symbols in their debug information - the
15556      minimal symbol would have the right address, but the debug info
15557      would not.  It's no longer necessary, because we will explicitly
15558      apply relocations when we read in the debug information now.  */
15559
15560   /* A DW_AT_location attribute with no contents indicates that a
15561      variable has been optimized away.  */
15562   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15563     {
15564       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15565       return;
15566     }
15567
15568   /* Handle one degenerate form of location expression specially, to
15569      preserve GDB's previous behavior when section offsets are
15570      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15571      then mark this symbol as LOC_STATIC.  */
15572
15573   if (attr_form_is_block (attr)
15574       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15575            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15576           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15577               && (DW_BLOCK (attr)->size
15578                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15579     {
15580       unsigned int dummy;
15581
15582       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15583         SYMBOL_VALUE_ADDRESS (sym) =
15584           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15585       else
15586         SYMBOL_VALUE_ADDRESS (sym) =
15587           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15588       SYMBOL_CLASS (sym) = LOC_STATIC;
15589       fixup_symbol_section (sym, objfile);
15590       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15591                                               SYMBOL_SECTION (sym));
15592       return;
15593     }
15594
15595   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15596      expression evaluator, and use LOC_COMPUTED only when necessary
15597      (i.e. when the value of a register or memory location is
15598      referenced, or a thread-local block, etc.).  Then again, it might
15599      not be worthwhile.  I'm assuming that it isn't unless performance
15600      or memory numbers show me otherwise.  */
15601
15602   dwarf2_symbol_mark_computed (attr, sym, cu);
15603   SYMBOL_CLASS (sym) = LOC_COMPUTED;
15604
15605   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
15606     cu->has_loclist = 1;
15607 }
15608
15609 /* Given a pointer to a DWARF information entry, figure out if we need
15610    to make a symbol table entry for it, and if so, create a new entry
15611    and return a pointer to it.
15612    If TYPE is NULL, determine symbol type from the die, otherwise
15613    used the passed type.
15614    If SPACE is not NULL, use it to hold the new symbol.  If it is
15615    NULL, allocate a new symbol on the objfile's obstack.  */
15616
15617 static struct symbol *
15618 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15619                  struct symbol *space)
15620 {
15621   struct objfile *objfile = cu->objfile;
15622   struct symbol *sym = NULL;
15623   char *name;
15624   struct attribute *attr = NULL;
15625   struct attribute *attr2 = NULL;
15626   CORE_ADDR baseaddr;
15627   struct pending **list_to_add = NULL;
15628
15629   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15630
15631   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15632
15633   name = dwarf2_name (die, cu);
15634   if (name)
15635     {
15636       const char *linkagename;
15637       int suppress_add = 0;
15638
15639       if (space)
15640         sym = space;
15641       else
15642         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
15643       OBJSTAT (objfile, n_syms++);
15644
15645       /* Cache this symbol's name and the name's demangled form (if any).  */
15646       SYMBOL_SET_LANGUAGE (sym, cu->language);
15647       linkagename = dwarf2_physname (name, die, cu);
15648       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15649
15650       /* Fortran does not have mangling standard and the mangling does differ
15651          between gfortran, iFort etc.  */
15652       if (cu->language == language_fortran
15653           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15654         symbol_set_demangled_name (&(sym->ginfo),
15655                                    (char *) dwarf2_full_name (name, die, cu),
15656                                    NULL);
15657
15658       /* Default assumptions.
15659          Use the passed type or decode it from the die.  */
15660       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15661       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15662       if (type != NULL)
15663         SYMBOL_TYPE (sym) = type;
15664       else
15665         SYMBOL_TYPE (sym) = die_type (die, cu);
15666       attr = dwarf2_attr (die,
15667                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15668                           cu);
15669       if (attr)
15670         {
15671           SYMBOL_LINE (sym) = DW_UNSND (attr);
15672         }
15673
15674       attr = dwarf2_attr (die,
15675                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
15676                           cu);
15677       if (attr)
15678         {
15679           int file_index = DW_UNSND (attr);
15680
15681           if (cu->line_header == NULL
15682               || file_index > cu->line_header->num_file_names)
15683             complaint (&symfile_complaints,
15684                        _("file index out of range"));
15685           else if (file_index > 0)
15686             {
15687               struct file_entry *fe;
15688
15689               fe = &cu->line_header->file_names[file_index - 1];
15690               SYMBOL_SYMTAB (sym) = fe->symtab;
15691             }
15692         }
15693
15694       switch (die->tag)
15695         {
15696         case DW_TAG_label:
15697           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15698           if (attr)
15699             {
15700               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
15701             }
15702           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
15703           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
15704           SYMBOL_CLASS (sym) = LOC_LABEL;
15705           add_symbol_to_list (sym, cu->list_in_scope);
15706           break;
15707         case DW_TAG_subprogram:
15708           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15709              finish_block.  */
15710           SYMBOL_CLASS (sym) = LOC_BLOCK;
15711           attr2 = dwarf2_attr (die, DW_AT_external, cu);
15712           if ((attr2 && (DW_UNSND (attr2) != 0))
15713               || cu->language == language_ada)
15714             {
15715               /* Subprograms marked external are stored as a global symbol.
15716                  Ada subprograms, whether marked external or not, are always
15717                  stored as a global symbol, because we want to be able to
15718                  access them globally.  For instance, we want to be able
15719                  to break on a nested subprogram without having to
15720                  specify the context.  */
15721               list_to_add = &global_symbols;
15722             }
15723           else
15724             {
15725               list_to_add = cu->list_in_scope;
15726             }
15727           break;
15728         case DW_TAG_inlined_subroutine:
15729           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15730              finish_block.  */
15731           SYMBOL_CLASS (sym) = LOC_BLOCK;
15732           SYMBOL_INLINED (sym) = 1;
15733           list_to_add = cu->list_in_scope;
15734           break;
15735         case DW_TAG_template_value_param:
15736           suppress_add = 1;
15737           /* Fall through.  */
15738         case DW_TAG_constant:
15739         case DW_TAG_variable:
15740         case DW_TAG_member:
15741           /* Compilation with minimal debug info may result in
15742              variables with missing type entries.  Change the
15743              misleading `void' type to something sensible.  */
15744           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
15745             SYMBOL_TYPE (sym)
15746               = objfile_type (objfile)->nodebug_data_symbol;
15747
15748           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15749           /* In the case of DW_TAG_member, we should only be called for
15750              static const members.  */
15751           if (die->tag == DW_TAG_member)
15752             {
15753               /* dwarf2_add_field uses die_is_declaration,
15754                  so we do the same.  */
15755               gdb_assert (die_is_declaration (die, cu));
15756               gdb_assert (attr);
15757             }
15758           if (attr)
15759             {
15760               dwarf2_const_value (attr, sym, cu);
15761               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15762               if (!suppress_add)
15763                 {
15764                   if (attr2 && (DW_UNSND (attr2) != 0))
15765                     list_to_add = &global_symbols;
15766                   else
15767                     list_to_add = cu->list_in_scope;
15768                 }
15769               break;
15770             }
15771           attr = dwarf2_attr (die, DW_AT_location, cu);
15772           if (attr)
15773             {
15774               var_decode_location (attr, sym, cu);
15775               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15776
15777               /* Fortran explicitly imports any global symbols to the local
15778                  scope by DW_TAG_common_block.  */
15779               if (cu->language == language_fortran && die->parent
15780                   && die->parent->tag == DW_TAG_common_block)
15781                 attr2 = NULL;
15782
15783               if (SYMBOL_CLASS (sym) == LOC_STATIC
15784                   && SYMBOL_VALUE_ADDRESS (sym) == 0
15785                   && !dwarf2_per_objfile->has_section_at_zero)
15786                 {
15787                   /* When a static variable is eliminated by the linker,
15788                      the corresponding debug information is not stripped
15789                      out, but the variable address is set to null;
15790                      do not add such variables into symbol table.  */
15791                 }
15792               else if (attr2 && (DW_UNSND (attr2) != 0))
15793                 {
15794                   /* Workaround gfortran PR debug/40040 - it uses
15795                      DW_AT_location for variables in -fPIC libraries which may
15796                      get overriden by other libraries/executable and get
15797                      a different address.  Resolve it by the minimal symbol
15798                      which may come from inferior's executable using copy
15799                      relocation.  Make this workaround only for gfortran as for
15800                      other compilers GDB cannot guess the minimal symbol
15801                      Fortran mangling kind.  */
15802                   if (cu->language == language_fortran && die->parent
15803                       && die->parent->tag == DW_TAG_module
15804                       && cu->producer
15805                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
15806                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15807
15808                   /* A variable with DW_AT_external is never static,
15809                      but it may be block-scoped.  */
15810                   list_to_add = (cu->list_in_scope == &file_symbols
15811                                  ? &global_symbols : cu->list_in_scope);
15812                 }
15813               else
15814                 list_to_add = cu->list_in_scope;
15815             }
15816           else
15817             {
15818               /* We do not know the address of this symbol.
15819                  If it is an external symbol and we have type information
15820                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
15821                  The address of the variable will then be determined from
15822                  the minimal symbol table whenever the variable is
15823                  referenced.  */
15824               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15825
15826               /* Fortran explicitly imports any global symbols to the local
15827                  scope by DW_TAG_common_block.  */
15828               if (cu->language == language_fortran && die->parent
15829                   && die->parent->tag == DW_TAG_common_block)
15830                 {
15831                   /* SYMBOL_CLASS doesn't matter here because
15832                      read_common_block is going to reset it.  */
15833                   if (!suppress_add)
15834                     list_to_add = cu->list_in_scope;
15835                 }
15836               else if (attr2 && (DW_UNSND (attr2) != 0)
15837                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
15838                 {
15839                   /* A variable with DW_AT_external is never static, but it
15840                      may be block-scoped.  */
15841                   list_to_add = (cu->list_in_scope == &file_symbols
15842                                  ? &global_symbols : cu->list_in_scope);
15843
15844                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15845                 }
15846               else if (!die_is_declaration (die, cu))
15847                 {
15848                   /* Use the default LOC_OPTIMIZED_OUT class.  */
15849                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
15850                   if (!suppress_add)
15851                     list_to_add = cu->list_in_scope;
15852                 }
15853             }
15854           break;
15855         case DW_TAG_formal_parameter:
15856           /* If we are inside a function, mark this as an argument.  If
15857              not, we might be looking at an argument to an inlined function
15858              when we do not have enough information to show inlined frames;
15859              pretend it's a local variable in that case so that the user can
15860              still see it.  */
15861           if (context_stack_depth > 0
15862               && context_stack[context_stack_depth - 1].name != NULL)
15863             SYMBOL_IS_ARGUMENT (sym) = 1;
15864           attr = dwarf2_attr (die, DW_AT_location, cu);
15865           if (attr)
15866             {
15867               var_decode_location (attr, sym, cu);
15868             }
15869           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15870           if (attr)
15871             {
15872               dwarf2_const_value (attr, sym, cu);
15873             }
15874
15875           list_to_add = cu->list_in_scope;
15876           break;
15877         case DW_TAG_unspecified_parameters:
15878           /* From varargs functions; gdb doesn't seem to have any
15879              interest in this information, so just ignore it for now.
15880              (FIXME?) */
15881           break;
15882         case DW_TAG_template_type_param:
15883           suppress_add = 1;
15884           /* Fall through.  */
15885         case DW_TAG_class_type:
15886         case DW_TAG_interface_type:
15887         case DW_TAG_structure_type:
15888         case DW_TAG_union_type:
15889         case DW_TAG_set_type:
15890         case DW_TAG_enumeration_type:
15891           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
15892           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
15893
15894           {
15895             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
15896                really ever be static objects: otherwise, if you try
15897                to, say, break of a class's method and you're in a file
15898                which doesn't mention that class, it won't work unless
15899                the check for all static symbols in lookup_symbol_aux
15900                saves you.  See the OtherFileClass tests in
15901                gdb.c++/namespace.exp.  */
15902
15903             if (!suppress_add)
15904               {
15905                 list_to_add = (cu->list_in_scope == &file_symbols
15906                                && (cu->language == language_cplus
15907                                    || cu->language == language_java)
15908                                ? &global_symbols : cu->list_in_scope);
15909
15910                 /* The semantics of C++ state that "struct foo {
15911                    ... }" also defines a typedef for "foo".  A Java
15912                    class declaration also defines a typedef for the
15913                    class.  */
15914                 if (cu->language == language_cplus
15915                     || cu->language == language_java
15916                     || cu->language == language_ada)
15917                   {
15918                     /* The symbol's name is already allocated along
15919                        with this objfile, so we don't need to
15920                        duplicate it for the type.  */
15921                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
15922                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
15923                   }
15924               }
15925           }
15926           break;
15927         case DW_TAG_typedef:
15928           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
15929           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15930           list_to_add = cu->list_in_scope;
15931           break;
15932         case DW_TAG_base_type:
15933         case DW_TAG_subrange_type:
15934           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
15935           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15936           list_to_add = cu->list_in_scope;
15937           break;
15938         case DW_TAG_enumerator:
15939           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15940           if (attr)
15941             {
15942               dwarf2_const_value (attr, sym, cu);
15943             }
15944           {
15945             /* NOTE: carlton/2003-11-10: See comment above in the
15946                DW_TAG_class_type, etc. block.  */
15947
15948             list_to_add = (cu->list_in_scope == &file_symbols
15949                            && (cu->language == language_cplus
15950                                || cu->language == language_java)
15951                            ? &global_symbols : cu->list_in_scope);
15952           }
15953           break;
15954         case DW_TAG_namespace:
15955           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
15956           list_to_add = &global_symbols;
15957           break;
15958         case DW_TAG_common_block:
15959           SYMBOL_CLASS (sym) = LOC_STATIC;
15960           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
15961           add_symbol_to_list (sym, cu->list_in_scope);
15962           break;
15963         default:
15964           /* Not a tag we recognize.  Hopefully we aren't processing
15965              trash data, but since we must specifically ignore things
15966              we don't recognize, there is nothing else we should do at
15967              this point.  */
15968           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
15969                      dwarf_tag_name (die->tag));
15970           break;
15971         }
15972
15973       if (suppress_add)
15974         {
15975           sym->hash_next = objfile->template_symbols;
15976           objfile->template_symbols = sym;
15977           list_to_add = NULL;
15978         }
15979
15980       if (list_to_add != NULL)
15981         add_symbol_to_list (sym, list_to_add);
15982
15983       /* For the benefit of old versions of GCC, check for anonymous
15984          namespaces based on the demangled name.  */
15985       if (!processing_has_namespace_info
15986           && cu->language == language_cplus)
15987         cp_scan_for_anonymous_namespaces (sym, objfile);
15988     }
15989   return (sym);
15990 }
15991
15992 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
15993
15994 static struct symbol *
15995 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
15996 {
15997   return new_symbol_full (die, type, cu, NULL);
15998 }
15999
16000 /* Given an attr with a DW_FORM_dataN value in host byte order,
16001    zero-extend it as appropriate for the symbol's type.  The DWARF
16002    standard (v4) is not entirely clear about the meaning of using
16003    DW_FORM_dataN for a constant with a signed type, where the type is
16004    wider than the data.  The conclusion of a discussion on the DWARF
16005    list was that this is unspecified.  We choose to always zero-extend
16006    because that is the interpretation long in use by GCC.  */
16007
16008 static gdb_byte *
16009 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16010                          const char *name, struct obstack *obstack,
16011                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16012 {
16013   struct objfile *objfile = cu->objfile;
16014   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16015                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16016   LONGEST l = DW_UNSND (attr);
16017
16018   if (bits < sizeof (*value) * 8)
16019     {
16020       l &= ((LONGEST) 1 << bits) - 1;
16021       *value = l;
16022     }
16023   else if (bits == sizeof (*value) * 8)
16024     *value = l;
16025   else
16026     {
16027       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16028       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16029       return bytes;
16030     }
16031
16032   return NULL;
16033 }
16034
16035 /* Read a constant value from an attribute.  Either set *VALUE, or if
16036    the value does not fit in *VALUE, set *BYTES - either already
16037    allocated on the objfile obstack, or newly allocated on OBSTACK,
16038    or, set *BATON, if we translated the constant to a location
16039    expression.  */
16040
16041 static void
16042 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16043                          const char *name, struct obstack *obstack,
16044                          struct dwarf2_cu *cu,
16045                          LONGEST *value, gdb_byte **bytes,
16046                          struct dwarf2_locexpr_baton **baton)
16047 {
16048   struct objfile *objfile = cu->objfile;
16049   struct comp_unit_head *cu_header = &cu->header;
16050   struct dwarf_block *blk;
16051   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16052                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16053
16054   *value = 0;
16055   *bytes = NULL;
16056   *baton = NULL;
16057
16058   switch (attr->form)
16059     {
16060     case DW_FORM_addr:
16061     case DW_FORM_GNU_addr_index:
16062       {
16063         gdb_byte *data;
16064
16065         if (TYPE_LENGTH (type) != cu_header->addr_size)
16066           dwarf2_const_value_length_mismatch_complaint (name,
16067                                                         cu_header->addr_size,
16068                                                         TYPE_LENGTH (type));
16069         /* Symbols of this form are reasonably rare, so we just
16070            piggyback on the existing location code rather than writing
16071            a new implementation of symbol_computed_ops.  */
16072         *baton = obstack_alloc (&objfile->objfile_obstack,
16073                                 sizeof (struct dwarf2_locexpr_baton));
16074         (*baton)->per_cu = cu->per_cu;
16075         gdb_assert ((*baton)->per_cu);
16076
16077         (*baton)->size = 2 + cu_header->addr_size;
16078         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16079         (*baton)->data = data;
16080
16081         data[0] = DW_OP_addr;
16082         store_unsigned_integer (&data[1], cu_header->addr_size,
16083                                 byte_order, DW_ADDR (attr));
16084         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16085       }
16086       break;
16087     case DW_FORM_string:
16088     case DW_FORM_strp:
16089     case DW_FORM_GNU_str_index:
16090     case DW_FORM_GNU_strp_alt:
16091       /* DW_STRING is already allocated on the objfile obstack, point
16092          directly to it.  */
16093       *bytes = (gdb_byte *) DW_STRING (attr);
16094       break;
16095     case DW_FORM_block1:
16096     case DW_FORM_block2:
16097     case DW_FORM_block4:
16098     case DW_FORM_block:
16099     case DW_FORM_exprloc:
16100       blk = DW_BLOCK (attr);
16101       if (TYPE_LENGTH (type) != blk->size)
16102         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16103                                                       TYPE_LENGTH (type));
16104       *bytes = blk->data;
16105       break;
16106
16107       /* The DW_AT_const_value attributes are supposed to carry the
16108          symbol's value "represented as it would be on the target
16109          architecture."  By the time we get here, it's already been
16110          converted to host endianness, so we just need to sign- or
16111          zero-extend it as appropriate.  */
16112     case DW_FORM_data1:
16113       *bytes = dwarf2_const_value_data (attr, type, name,
16114                                         obstack, cu, value, 8);
16115       break;
16116     case DW_FORM_data2:
16117       *bytes = dwarf2_const_value_data (attr, type, name,
16118                                         obstack, cu, value, 16);
16119       break;
16120     case DW_FORM_data4:
16121       *bytes = dwarf2_const_value_data (attr, type, name,
16122                                         obstack, cu, value, 32);
16123       break;
16124     case DW_FORM_data8:
16125       *bytes = dwarf2_const_value_data (attr, type, name,
16126                                         obstack, cu, value, 64);
16127       break;
16128
16129     case DW_FORM_sdata:
16130       *value = DW_SND (attr);
16131       break;
16132
16133     case DW_FORM_udata:
16134       *value = DW_UNSND (attr);
16135       break;
16136
16137     default:
16138       complaint (&symfile_complaints,
16139                  _("unsupported const value attribute form: '%s'"),
16140                  dwarf_form_name (attr->form));
16141       *value = 0;
16142       break;
16143     }
16144 }
16145
16146
16147 /* Copy constant value from an attribute to a symbol.  */
16148
16149 static void
16150 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16151                     struct dwarf2_cu *cu)
16152 {
16153   struct objfile *objfile = cu->objfile;
16154   struct comp_unit_head *cu_header = &cu->header;
16155   LONGEST value;
16156   gdb_byte *bytes;
16157   struct dwarf2_locexpr_baton *baton;
16158
16159   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16160                            SYMBOL_PRINT_NAME (sym),
16161                            &objfile->objfile_obstack, cu,
16162                            &value, &bytes, &baton);
16163
16164   if (baton != NULL)
16165     {
16166       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
16167       SYMBOL_LOCATION_BATON (sym) = baton;
16168       SYMBOL_CLASS (sym) = LOC_COMPUTED;
16169     }
16170   else if (bytes != NULL)
16171      {
16172       SYMBOL_VALUE_BYTES (sym) = bytes;
16173       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
16174     }
16175   else
16176     {
16177       SYMBOL_VALUE (sym) = value;
16178       SYMBOL_CLASS (sym) = LOC_CONST;
16179     }
16180 }
16181
16182 /* Return the type of the die in question using its DW_AT_type attribute.  */
16183
16184 static struct type *
16185 die_type (struct die_info *die, struct dwarf2_cu *cu)
16186 {
16187   struct attribute *type_attr;
16188
16189   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16190   if (!type_attr)
16191     {
16192       /* A missing DW_AT_type represents a void type.  */
16193       return objfile_type (cu->objfile)->builtin_void;
16194     }
16195
16196   return lookup_die_type (die, type_attr, cu);
16197 }
16198
16199 /* True iff CU's producer generates GNAT Ada auxiliary information
16200    that allows to find parallel types through that information instead
16201    of having to do expensive parallel lookups by type name.  */
16202
16203 static int
16204 need_gnat_info (struct dwarf2_cu *cu)
16205 {
16206   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16207      of GNAT produces this auxiliary information, without any indication
16208      that it is produced.  Part of enhancing the FSF version of GNAT
16209      to produce that information will be to put in place an indicator
16210      that we can use in order to determine whether the descriptive type
16211      info is available or not.  One suggestion that has been made is
16212      to use a new attribute, attached to the CU die.  For now, assume
16213      that the descriptive type info is not available.  */
16214   return 0;
16215 }
16216
16217 /* Return the auxiliary type of the die in question using its
16218    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16219    attribute is not present.  */
16220
16221 static struct type *
16222 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16223 {
16224   struct attribute *type_attr;
16225
16226   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16227   if (!type_attr)
16228     return NULL;
16229
16230   return lookup_die_type (die, type_attr, cu);
16231 }
16232
16233 /* If DIE has a descriptive_type attribute, then set the TYPE's
16234    descriptive type accordingly.  */
16235
16236 static void
16237 set_descriptive_type (struct type *type, struct die_info *die,
16238                       struct dwarf2_cu *cu)
16239 {
16240   struct type *descriptive_type = die_descriptive_type (die, cu);
16241
16242   if (descriptive_type)
16243     {
16244       ALLOCATE_GNAT_AUX_TYPE (type);
16245       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16246     }
16247 }
16248
16249 /* Return the containing type of the die in question using its
16250    DW_AT_containing_type attribute.  */
16251
16252 static struct type *
16253 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16254 {
16255   struct attribute *type_attr;
16256
16257   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16258   if (!type_attr)
16259     error (_("Dwarf Error: Problem turning containing type into gdb type "
16260              "[in module %s]"), cu->objfile->name);
16261
16262   return lookup_die_type (die, type_attr, cu);
16263 }
16264
16265 /* Look up the type of DIE in CU using its type attribute ATTR.
16266    If there is no type substitute an error marker.  */
16267
16268 static struct type *
16269 lookup_die_type (struct die_info *die, struct attribute *attr,
16270                  struct dwarf2_cu *cu)
16271 {
16272   struct objfile *objfile = cu->objfile;
16273   struct type *this_type;
16274
16275   /* First see if we have it cached.  */
16276
16277   if (attr->form == DW_FORM_GNU_ref_alt)
16278     {
16279       struct dwarf2_per_cu_data *per_cu;
16280       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16281
16282       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16283       this_type = get_die_type_at_offset (offset, per_cu);
16284     }
16285   else if (is_ref_attr (attr))
16286     {
16287       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16288
16289       this_type = get_die_type_at_offset (offset, cu->per_cu);
16290     }
16291   else if (attr->form == DW_FORM_ref_sig8)
16292     {
16293       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16294
16295       /* sig_type will be NULL if the signatured type is missing from
16296          the debug info.  */
16297       if (sig_type == NULL)
16298         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16299                  "at 0x%x [in module %s]"),
16300                die->offset.sect_off, objfile->name);
16301
16302       gdb_assert (sig_type->per_cu.is_debug_types);
16303       /* If we haven't filled in type_offset_in_section yet, then we
16304          haven't read the type in yet.  */
16305       this_type = NULL;
16306       if (sig_type->type_offset_in_section.sect_off != 0)
16307         {
16308           this_type =
16309             get_die_type_at_offset (sig_type->type_offset_in_section,
16310                                     &sig_type->per_cu);
16311         }
16312     }
16313   else
16314     {
16315       dump_die_for_error (die);
16316       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16317              dwarf_attr_name (attr->name), objfile->name);
16318     }
16319
16320   /* If not cached we need to read it in.  */
16321
16322   if (this_type == NULL)
16323     {
16324       struct die_info *type_die;
16325       struct dwarf2_cu *type_cu = cu;
16326
16327       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16328       /* If we found the type now, it's probably because the type came
16329          from an inter-CU reference and the type's CU got expanded before
16330          ours.  */
16331       this_type = get_die_type (type_die, type_cu);
16332       if (this_type == NULL)
16333         this_type = read_type_die_1 (type_die, type_cu);
16334     }
16335
16336   /* If we still don't have a type use an error marker.  */
16337
16338   if (this_type == NULL)
16339     {
16340       char *message, *saved;
16341
16342       /* read_type_die already issued a complaint.  */
16343       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16344                             objfile->name,
16345                             cu->header.offset.sect_off,
16346                             die->offset.sect_off);
16347       saved = obstack_copy0 (&objfile->objfile_obstack,
16348                              message, strlen (message));
16349       xfree (message);
16350
16351       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16352     }
16353
16354   return this_type;
16355 }
16356
16357 /* Return the type in DIE, CU.
16358    Returns NULL for invalid types.
16359
16360    This first does a lookup in the appropriate type_hash table,
16361    and only reads the die in if necessary.
16362
16363    NOTE: This can be called when reading in partial or full symbols.  */
16364
16365 static struct type *
16366 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16367 {
16368   struct type *this_type;
16369
16370   this_type = get_die_type (die, cu);
16371   if (this_type)
16372     return this_type;
16373
16374   return read_type_die_1 (die, cu);
16375 }
16376
16377 /* Read the type in DIE, CU.
16378    Returns NULL for invalid types.  */
16379
16380 static struct type *
16381 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16382 {
16383   struct type *this_type = NULL;
16384
16385   switch (die->tag)
16386     {
16387     case DW_TAG_class_type:
16388     case DW_TAG_interface_type:
16389     case DW_TAG_structure_type:
16390     case DW_TAG_union_type:
16391       this_type = read_structure_type (die, cu);
16392       break;
16393     case DW_TAG_enumeration_type:
16394       this_type = read_enumeration_type (die, cu);
16395       break;
16396     case DW_TAG_subprogram:
16397     case DW_TAG_subroutine_type:
16398     case DW_TAG_inlined_subroutine:
16399       this_type = read_subroutine_type (die, cu);
16400       break;
16401     case DW_TAG_array_type:
16402       this_type = read_array_type (die, cu);
16403       break;
16404     case DW_TAG_set_type:
16405       this_type = read_set_type (die, cu);
16406       break;
16407     case DW_TAG_pointer_type:
16408       this_type = read_tag_pointer_type (die, cu);
16409       break;
16410     case DW_TAG_ptr_to_member_type:
16411       this_type = read_tag_ptr_to_member_type (die, cu);
16412       break;
16413     case DW_TAG_reference_type:
16414       this_type = read_tag_reference_type (die, cu);
16415       break;
16416     case DW_TAG_const_type:
16417       this_type = read_tag_const_type (die, cu);
16418       break;
16419     case DW_TAG_volatile_type:
16420       this_type = read_tag_volatile_type (die, cu);
16421       break;
16422     case DW_TAG_string_type:
16423       this_type = read_tag_string_type (die, cu);
16424       break;
16425     case DW_TAG_typedef:
16426       this_type = read_typedef (die, cu);
16427       break;
16428     case DW_TAG_subrange_type:
16429       this_type = read_subrange_type (die, cu);
16430       break;
16431     case DW_TAG_base_type:
16432       this_type = read_base_type (die, cu);
16433       break;
16434     case DW_TAG_unspecified_type:
16435       this_type = read_unspecified_type (die, cu);
16436       break;
16437     case DW_TAG_namespace:
16438       this_type = read_namespace_type (die, cu);
16439       break;
16440     case DW_TAG_module:
16441       this_type = read_module_type (die, cu);
16442       break;
16443     default:
16444       complaint (&symfile_complaints,
16445                  _("unexpected tag in read_type_die: '%s'"),
16446                  dwarf_tag_name (die->tag));
16447       break;
16448     }
16449
16450   return this_type;
16451 }
16452
16453 /* See if we can figure out if the class lives in a namespace.  We do
16454    this by looking for a member function; its demangled name will
16455    contain namespace info, if there is any.
16456    Return the computed name or NULL.
16457    Space for the result is allocated on the objfile's obstack.
16458    This is the full-die version of guess_partial_die_structure_name.
16459    In this case we know DIE has no useful parent.  */
16460
16461 static char *
16462 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16463 {
16464   struct die_info *spec_die;
16465   struct dwarf2_cu *spec_cu;
16466   struct die_info *child;
16467
16468   spec_cu = cu;
16469   spec_die = die_specification (die, &spec_cu);
16470   if (spec_die != NULL)
16471     {
16472       die = spec_die;
16473       cu = spec_cu;
16474     }
16475
16476   for (child = die->child;
16477        child != NULL;
16478        child = child->sibling)
16479     {
16480       if (child->tag == DW_TAG_subprogram)
16481         {
16482           struct attribute *attr;
16483
16484           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16485           if (attr == NULL)
16486             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16487           if (attr != NULL)
16488             {
16489               char *actual_name
16490                 = language_class_name_from_physname (cu->language_defn,
16491                                                      DW_STRING (attr));
16492               char *name = NULL;
16493
16494               if (actual_name != NULL)
16495                 {
16496                   char *die_name = dwarf2_name (die, cu);
16497
16498                   if (die_name != NULL
16499                       && strcmp (die_name, actual_name) != 0)
16500                     {
16501                       /* Strip off the class name from the full name.
16502                          We want the prefix.  */
16503                       int die_name_len = strlen (die_name);
16504                       int actual_name_len = strlen (actual_name);
16505
16506                       /* Test for '::' as a sanity check.  */
16507                       if (actual_name_len > die_name_len + 2
16508                           && actual_name[actual_name_len
16509                                          - die_name_len - 1] == ':')
16510                         name =
16511                           obsavestring (actual_name,
16512                                         actual_name_len - die_name_len - 2,
16513                                         &cu->objfile->objfile_obstack);
16514                     }
16515                 }
16516               xfree (actual_name);
16517               return name;
16518             }
16519         }
16520     }
16521
16522   return NULL;
16523 }
16524
16525 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16526    prefix part in such case.  See
16527    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16528
16529 static char *
16530 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16531 {
16532   struct attribute *attr;
16533   char *base;
16534
16535   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16536       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16537     return NULL;
16538
16539   attr = dwarf2_attr (die, DW_AT_name, cu);
16540   if (attr != NULL && DW_STRING (attr) != NULL)
16541     return NULL;
16542
16543   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16544   if (attr == NULL)
16545     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16546   if (attr == NULL || DW_STRING (attr) == NULL)
16547     return NULL;
16548
16549   /* dwarf2_name had to be already called.  */
16550   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16551
16552   /* Strip the base name, keep any leading namespaces/classes.  */
16553   base = strrchr (DW_STRING (attr), ':');
16554   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16555     return "";
16556
16557   return obsavestring (DW_STRING (attr), &base[-1] - DW_STRING (attr),
16558                        &cu->objfile->objfile_obstack);
16559 }
16560
16561 /* Return the name of the namespace/class that DIE is defined within,
16562    or "" if we can't tell.  The caller should not xfree the result.
16563
16564    For example, if we're within the method foo() in the following
16565    code:
16566
16567    namespace N {
16568      class C {
16569        void foo () {
16570        }
16571      };
16572    }
16573
16574    then determine_prefix on foo's die will return "N::C".  */
16575
16576 static const char *
16577 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16578 {
16579   struct die_info *parent, *spec_die;
16580   struct dwarf2_cu *spec_cu;
16581   struct type *parent_type;
16582   char *retval;
16583
16584   if (cu->language != language_cplus && cu->language != language_java
16585       && cu->language != language_fortran)
16586     return "";
16587
16588   retval = anonymous_struct_prefix (die, cu);
16589   if (retval)
16590     return retval;
16591
16592   /* We have to be careful in the presence of DW_AT_specification.
16593      For example, with GCC 3.4, given the code
16594
16595      namespace N {
16596        void foo() {
16597          // Definition of N::foo.
16598        }
16599      }
16600
16601      then we'll have a tree of DIEs like this:
16602
16603      1: DW_TAG_compile_unit
16604        2: DW_TAG_namespace        // N
16605          3: DW_TAG_subprogram     // declaration of N::foo
16606        4: DW_TAG_subprogram       // definition of N::foo
16607             DW_AT_specification   // refers to die #3
16608
16609      Thus, when processing die #4, we have to pretend that we're in
16610      the context of its DW_AT_specification, namely the contex of die
16611      #3.  */
16612   spec_cu = cu;
16613   spec_die = die_specification (die, &spec_cu);
16614   if (spec_die == NULL)
16615     parent = die->parent;
16616   else
16617     {
16618       parent = spec_die->parent;
16619       cu = spec_cu;
16620     }
16621
16622   if (parent == NULL)
16623     return "";
16624   else if (parent->building_fullname)
16625     {
16626       const char *name;
16627       const char *parent_name;
16628
16629       /* It has been seen on RealView 2.2 built binaries,
16630          DW_TAG_template_type_param types actually _defined_ as
16631          children of the parent class:
16632
16633          enum E {};
16634          template class <class Enum> Class{};
16635          Class<enum E> class_e;
16636
16637          1: DW_TAG_class_type (Class)
16638            2: DW_TAG_enumeration_type (E)
16639              3: DW_TAG_enumerator (enum1:0)
16640              3: DW_TAG_enumerator (enum2:1)
16641              ...
16642            2: DW_TAG_template_type_param
16643               DW_AT_type  DW_FORM_ref_udata (E)
16644
16645          Besides being broken debug info, it can put GDB into an
16646          infinite loop.  Consider:
16647
16648          When we're building the full name for Class<E>, we'll start
16649          at Class, and go look over its template type parameters,
16650          finding E.  We'll then try to build the full name of E, and
16651          reach here.  We're now trying to build the full name of E,
16652          and look over the parent DIE for containing scope.  In the
16653          broken case, if we followed the parent DIE of E, we'd again
16654          find Class, and once again go look at its template type
16655          arguments, etc., etc.  Simply don't consider such parent die
16656          as source-level parent of this die (it can't be, the language
16657          doesn't allow it), and break the loop here.  */
16658       name = dwarf2_name (die, cu);
16659       parent_name = dwarf2_name (parent, cu);
16660       complaint (&symfile_complaints,
16661                  _("template param type '%s' defined within parent '%s'"),
16662                  name ? name : "<unknown>",
16663                  parent_name ? parent_name : "<unknown>");
16664       return "";
16665     }
16666   else
16667     switch (parent->tag)
16668       {
16669       case DW_TAG_namespace:
16670         parent_type = read_type_die (parent, cu);
16671         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
16672            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
16673            Work around this problem here.  */
16674         if (cu->language == language_cplus
16675             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
16676           return "";
16677         /* We give a name to even anonymous namespaces.  */
16678         return TYPE_TAG_NAME (parent_type);
16679       case DW_TAG_class_type:
16680       case DW_TAG_interface_type:
16681       case DW_TAG_structure_type:
16682       case DW_TAG_union_type:
16683       case DW_TAG_module:
16684         parent_type = read_type_die (parent, cu);
16685         if (TYPE_TAG_NAME (parent_type) != NULL)
16686           return TYPE_TAG_NAME (parent_type);
16687         else
16688           /* An anonymous structure is only allowed non-static data
16689              members; no typedefs, no member functions, et cetera.
16690              So it does not need a prefix.  */
16691           return "";
16692       case DW_TAG_compile_unit:
16693       case DW_TAG_partial_unit:
16694         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
16695         if (cu->language == language_cplus
16696             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16697             && die->child != NULL
16698             && (die->tag == DW_TAG_class_type
16699                 || die->tag == DW_TAG_structure_type
16700                 || die->tag == DW_TAG_union_type))
16701           {
16702             char *name = guess_full_die_structure_name (die, cu);
16703             if (name != NULL)
16704               return name;
16705           }
16706         return "";
16707       default:
16708         return determine_prefix (parent, cu);
16709       }
16710 }
16711
16712 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
16713    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
16714    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
16715    an obconcat, otherwise allocate storage for the result.  The CU argument is
16716    used to determine the language and hence, the appropriate separator.  */
16717
16718 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
16719
16720 static char *
16721 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
16722                  int physname, struct dwarf2_cu *cu)
16723 {
16724   const char *lead = "";
16725   const char *sep;
16726
16727   if (suffix == NULL || suffix[0] == '\0'
16728       || prefix == NULL || prefix[0] == '\0')
16729     sep = "";
16730   else if (cu->language == language_java)
16731     sep = ".";
16732   else if (cu->language == language_fortran && physname)
16733     {
16734       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
16735          DW_AT_MIPS_linkage_name is preferred and used instead.  */
16736
16737       lead = "__";
16738       sep = "_MOD_";
16739     }
16740   else
16741     sep = "::";
16742
16743   if (prefix == NULL)
16744     prefix = "";
16745   if (suffix == NULL)
16746     suffix = "";
16747
16748   if (obs == NULL)
16749     {
16750       char *retval
16751         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
16752
16753       strcpy (retval, lead);
16754       strcat (retval, prefix);
16755       strcat (retval, sep);
16756       strcat (retval, suffix);
16757       return retval;
16758     }
16759   else
16760     {
16761       /* We have an obstack.  */
16762       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
16763     }
16764 }
16765
16766 /* Return sibling of die, NULL if no sibling.  */
16767
16768 static struct die_info *
16769 sibling_die (struct die_info *die)
16770 {
16771   return die->sibling;
16772 }
16773
16774 /* Get name of a die, return NULL if not found.  */
16775
16776 static char *
16777 dwarf2_canonicalize_name (char *name, struct dwarf2_cu *cu,
16778                           struct obstack *obstack)
16779 {
16780   if (name && cu->language == language_cplus)
16781     {
16782       char *canon_name = cp_canonicalize_string (name);
16783
16784       if (canon_name != NULL)
16785         {
16786           if (strcmp (canon_name, name) != 0)
16787             name = obsavestring (canon_name, strlen (canon_name),
16788                                  obstack);
16789           xfree (canon_name);
16790         }
16791     }
16792
16793   return name;
16794 }
16795
16796 /* Get name of a die, return NULL if not found.  */
16797
16798 static char *
16799 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
16800 {
16801   struct attribute *attr;
16802
16803   attr = dwarf2_attr (die, DW_AT_name, cu);
16804   if ((!attr || !DW_STRING (attr))
16805       && die->tag != DW_TAG_class_type
16806       && die->tag != DW_TAG_interface_type
16807       && die->tag != DW_TAG_structure_type
16808       && die->tag != DW_TAG_union_type)
16809     return NULL;
16810
16811   switch (die->tag)
16812     {
16813     case DW_TAG_compile_unit:
16814     case DW_TAG_partial_unit:
16815       /* Compilation units have a DW_AT_name that is a filename, not
16816          a source language identifier.  */
16817     case DW_TAG_enumeration_type:
16818     case DW_TAG_enumerator:
16819       /* These tags always have simple identifiers already; no need
16820          to canonicalize them.  */
16821       return DW_STRING (attr);
16822
16823     case DW_TAG_subprogram:
16824       /* Java constructors will all be named "<init>", so return
16825          the class name when we see this special case.  */
16826       if (cu->language == language_java
16827           && DW_STRING (attr) != NULL
16828           && strcmp (DW_STRING (attr), "<init>") == 0)
16829         {
16830           struct dwarf2_cu *spec_cu = cu;
16831           struct die_info *spec_die;
16832
16833           /* GCJ will output '<init>' for Java constructor names.
16834              For this special case, return the name of the parent class.  */
16835
16836           /* GCJ may output suprogram DIEs with AT_specification set.
16837              If so, use the name of the specified DIE.  */
16838           spec_die = die_specification (die, &spec_cu);
16839           if (spec_die != NULL)
16840             return dwarf2_name (spec_die, spec_cu);
16841
16842           do
16843             {
16844               die = die->parent;
16845               if (die->tag == DW_TAG_class_type)
16846                 return dwarf2_name (die, cu);
16847             }
16848           while (die->tag != DW_TAG_compile_unit
16849                  && die->tag != DW_TAG_partial_unit);
16850         }
16851       break;
16852
16853     case DW_TAG_class_type:
16854     case DW_TAG_interface_type:
16855     case DW_TAG_structure_type:
16856     case DW_TAG_union_type:
16857       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
16858          structures or unions.  These were of the form "._%d" in GCC 4.1,
16859          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
16860          and GCC 4.4.  We work around this problem by ignoring these.  */
16861       if (attr && DW_STRING (attr)
16862           && (strncmp (DW_STRING (attr), "._", 2) == 0
16863               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
16864         return NULL;
16865
16866       /* GCC might emit a nameless typedef that has a linkage name.  See
16867          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16868       if (!attr || DW_STRING (attr) == NULL)
16869         {
16870           char *demangled = NULL;
16871
16872           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16873           if (attr == NULL)
16874             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16875
16876           if (attr == NULL || DW_STRING (attr) == NULL)
16877             return NULL;
16878
16879           /* Avoid demangling DW_STRING (attr) the second time on a second
16880              call for the same DIE.  */
16881           if (!DW_STRING_IS_CANONICAL (attr))
16882             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
16883
16884           if (demangled)
16885             {
16886               char *base;
16887
16888               /* FIXME: we already did this for the partial symbol... */
16889               DW_STRING (attr) = obsavestring (demangled, strlen (demangled),
16890                                                &cu->objfile->objfile_obstack);
16891               DW_STRING_IS_CANONICAL (attr) = 1;
16892               xfree (demangled);
16893
16894               /* Strip any leading namespaces/classes, keep only the base name.
16895                  DW_AT_name for named DIEs does not contain the prefixes.  */
16896               base = strrchr (DW_STRING (attr), ':');
16897               if (base && base > DW_STRING (attr) && base[-1] == ':')
16898                 return &base[1];
16899               else
16900                 return DW_STRING (attr);
16901             }
16902         }
16903       break;
16904
16905     default:
16906       break;
16907     }
16908
16909   if (!DW_STRING_IS_CANONICAL (attr))
16910     {
16911       DW_STRING (attr)
16912         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
16913                                     &cu->objfile->objfile_obstack);
16914       DW_STRING_IS_CANONICAL (attr) = 1;
16915     }
16916   return DW_STRING (attr);
16917 }
16918
16919 /* Return the die that this die in an extension of, or NULL if there
16920    is none.  *EXT_CU is the CU containing DIE on input, and the CU
16921    containing the return value on output.  */
16922
16923 static struct die_info *
16924 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
16925 {
16926   struct attribute *attr;
16927
16928   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
16929   if (attr == NULL)
16930     return NULL;
16931
16932   return follow_die_ref (die, attr, ext_cu);
16933 }
16934
16935 /* Convert a DIE tag into its string name.  */
16936
16937 static const char *
16938 dwarf_tag_name (unsigned tag)
16939 {
16940   const char *name = get_DW_TAG_name (tag);
16941
16942   if (name == NULL)
16943     return "DW_TAG_<unknown>";
16944
16945   return name;
16946 }
16947
16948 /* Convert a DWARF attribute code into its string name.  */
16949
16950 static const char *
16951 dwarf_attr_name (unsigned attr)
16952 {
16953   const char *name;
16954
16955 #ifdef MIPS /* collides with DW_AT_HP_block_index */
16956   if (attr == DW_AT_MIPS_fde)
16957     return "DW_AT_MIPS_fde";
16958 #else
16959   if (attr == DW_AT_HP_block_index)
16960     return "DW_AT_HP_block_index";
16961 #endif
16962
16963   name = get_DW_AT_name (attr);
16964
16965   if (name == NULL)
16966     return "DW_AT_<unknown>";
16967
16968   return name;
16969 }
16970
16971 /* Convert a DWARF value form code into its string name.  */
16972
16973 static const char *
16974 dwarf_form_name (unsigned form)
16975 {
16976   const char *name = get_DW_FORM_name (form);
16977
16978   if (name == NULL)
16979     return "DW_FORM_<unknown>";
16980
16981   return name;
16982 }
16983
16984 static char *
16985 dwarf_bool_name (unsigned mybool)
16986 {
16987   if (mybool)
16988     return "TRUE";
16989   else
16990     return "FALSE";
16991 }
16992
16993 /* Convert a DWARF type code into its string name.  */
16994
16995 static const char *
16996 dwarf_type_encoding_name (unsigned enc)
16997 {
16998   const char *name = get_DW_ATE_name (enc);
16999
17000   if (name == NULL)
17001     return "DW_ATE_<unknown>";
17002
17003   return name;
17004 }
17005
17006 static void
17007 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17008 {
17009   unsigned int i;
17010
17011   print_spaces (indent, f);
17012   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17013            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17014
17015   if (die->parent != NULL)
17016     {
17017       print_spaces (indent, f);
17018       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17019                           die->parent->offset.sect_off);
17020     }
17021
17022   print_spaces (indent, f);
17023   fprintf_unfiltered (f, "  has children: %s\n",
17024            dwarf_bool_name (die->child != NULL));
17025
17026   print_spaces (indent, f);
17027   fprintf_unfiltered (f, "  attributes:\n");
17028
17029   for (i = 0; i < die->num_attrs; ++i)
17030     {
17031       print_spaces (indent, f);
17032       fprintf_unfiltered (f, "    %s (%s) ",
17033                dwarf_attr_name (die->attrs[i].name),
17034                dwarf_form_name (die->attrs[i].form));
17035
17036       switch (die->attrs[i].form)
17037         {
17038         case DW_FORM_addr:
17039         case DW_FORM_GNU_addr_index:
17040           fprintf_unfiltered (f, "address: ");
17041           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17042           break;
17043         case DW_FORM_block2:
17044         case DW_FORM_block4:
17045         case DW_FORM_block:
17046         case DW_FORM_block1:
17047           fprintf_unfiltered (f, "block: size %s",
17048                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17049           break;
17050         case DW_FORM_exprloc:
17051           fprintf_unfiltered (f, "expression: size %s",
17052                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17053           break;
17054         case DW_FORM_ref_addr:
17055           fprintf_unfiltered (f, "ref address: ");
17056           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17057           break;
17058         case DW_FORM_GNU_ref_alt:
17059           fprintf_unfiltered (f, "alt ref address: ");
17060           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17061           break;
17062         case DW_FORM_ref1:
17063         case DW_FORM_ref2:
17064         case DW_FORM_ref4:
17065         case DW_FORM_ref8:
17066         case DW_FORM_ref_udata:
17067           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17068                               (long) (DW_UNSND (&die->attrs[i])));
17069           break;
17070         case DW_FORM_data1:
17071         case DW_FORM_data2:
17072         case DW_FORM_data4:
17073         case DW_FORM_data8:
17074         case DW_FORM_udata:
17075         case DW_FORM_sdata:
17076           fprintf_unfiltered (f, "constant: %s",
17077                               pulongest (DW_UNSND (&die->attrs[i])));
17078           break;
17079         case DW_FORM_sec_offset:
17080           fprintf_unfiltered (f, "section offset: %s",
17081                               pulongest (DW_UNSND (&die->attrs[i])));
17082           break;
17083         case DW_FORM_ref_sig8:
17084           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17085             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
17086                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
17087           else
17088             fprintf_unfiltered (f, "signatured type, offset: unknown");
17089           break;
17090         case DW_FORM_string:
17091         case DW_FORM_strp:
17092         case DW_FORM_GNU_str_index:
17093         case DW_FORM_GNU_strp_alt:
17094           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17095                    DW_STRING (&die->attrs[i])
17096                    ? DW_STRING (&die->attrs[i]) : "",
17097                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17098           break;
17099         case DW_FORM_flag:
17100           if (DW_UNSND (&die->attrs[i]))
17101             fprintf_unfiltered (f, "flag: TRUE");
17102           else
17103             fprintf_unfiltered (f, "flag: FALSE");
17104           break;
17105         case DW_FORM_flag_present:
17106           fprintf_unfiltered (f, "flag: TRUE");
17107           break;
17108         case DW_FORM_indirect:
17109           /* The reader will have reduced the indirect form to
17110              the "base form" so this form should not occur.  */
17111           fprintf_unfiltered (f, 
17112                               "unexpected attribute form: DW_FORM_indirect");
17113           break;
17114         default:
17115           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17116                    die->attrs[i].form);
17117           break;
17118         }
17119       fprintf_unfiltered (f, "\n");
17120     }
17121 }
17122
17123 static void
17124 dump_die_for_error (struct die_info *die)
17125 {
17126   dump_die_shallow (gdb_stderr, 0, die);
17127 }
17128
17129 static void
17130 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17131 {
17132   int indent = level * 4;
17133
17134   gdb_assert (die != NULL);
17135
17136   if (level >= max_level)
17137     return;
17138
17139   dump_die_shallow (f, indent, die);
17140
17141   if (die->child != NULL)
17142     {
17143       print_spaces (indent, f);
17144       fprintf_unfiltered (f, "  Children:");
17145       if (level + 1 < max_level)
17146         {
17147           fprintf_unfiltered (f, "\n");
17148           dump_die_1 (f, level + 1, max_level, die->child);
17149         }
17150       else
17151         {
17152           fprintf_unfiltered (f,
17153                               " [not printed, max nesting level reached]\n");
17154         }
17155     }
17156
17157   if (die->sibling != NULL && level > 0)
17158     {
17159       dump_die_1 (f, level, max_level, die->sibling);
17160     }
17161 }
17162
17163 /* This is called from the pdie macro in gdbinit.in.
17164    It's not static so gcc will keep a copy callable from gdb.  */
17165
17166 void
17167 dump_die (struct die_info *die, int max_level)
17168 {
17169   dump_die_1 (gdb_stdlog, 0, max_level, die);
17170 }
17171
17172 static void
17173 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17174 {
17175   void **slot;
17176
17177   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17178                                    INSERT);
17179
17180   *slot = die;
17181 }
17182
17183 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17184    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17185
17186 static int
17187 is_ref_attr (struct attribute *attr)
17188 {
17189   switch (attr->form)
17190     {
17191     case DW_FORM_ref_addr:
17192     case DW_FORM_ref1:
17193     case DW_FORM_ref2:
17194     case DW_FORM_ref4:
17195     case DW_FORM_ref8:
17196     case DW_FORM_ref_udata:
17197     case DW_FORM_GNU_ref_alt:
17198       return 1;
17199     default:
17200       return 0;
17201     }
17202 }
17203
17204 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17205    required kind.  */
17206
17207 static sect_offset
17208 dwarf2_get_ref_die_offset (struct attribute *attr)
17209 {
17210   sect_offset retval = { DW_UNSND (attr) };
17211
17212   if (is_ref_attr (attr))
17213     return retval;
17214
17215   retval.sect_off = 0;
17216   complaint (&symfile_complaints,
17217              _("unsupported die ref attribute form: '%s'"),
17218              dwarf_form_name (attr->form));
17219   return retval;
17220 }
17221
17222 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17223  * the value held by the attribute is not constant.  */
17224
17225 static LONGEST
17226 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17227 {
17228   if (attr->form == DW_FORM_sdata)
17229     return DW_SND (attr);
17230   else if (attr->form == DW_FORM_udata
17231            || attr->form == DW_FORM_data1
17232            || attr->form == DW_FORM_data2
17233            || attr->form == DW_FORM_data4
17234            || attr->form == DW_FORM_data8)
17235     return DW_UNSND (attr);
17236   else
17237     {
17238       complaint (&symfile_complaints,
17239                  _("Attribute value is not a constant (%s)"),
17240                  dwarf_form_name (attr->form));
17241       return default_value;
17242     }
17243 }
17244
17245 /* Follow reference or signature attribute ATTR of SRC_DIE.
17246    On entry *REF_CU is the CU of SRC_DIE.
17247    On exit *REF_CU is the CU of the result.  */
17248
17249 static struct die_info *
17250 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17251                        struct dwarf2_cu **ref_cu)
17252 {
17253   struct die_info *die;
17254
17255   if (is_ref_attr (attr))
17256     die = follow_die_ref (src_die, attr, ref_cu);
17257   else if (attr->form == DW_FORM_ref_sig8)
17258     die = follow_die_sig (src_die, attr, ref_cu);
17259   else
17260     {
17261       dump_die_for_error (src_die);
17262       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17263              (*ref_cu)->objfile->name);
17264     }
17265
17266   return die;
17267 }
17268
17269 /* Follow reference OFFSET.
17270    On entry *REF_CU is the CU of the source die referencing OFFSET.
17271    On exit *REF_CU is the CU of the result.
17272    Returns NULL if OFFSET is invalid.  */
17273
17274 static struct die_info *
17275 follow_die_offset (sect_offset offset, int offset_in_dwz,
17276                    struct dwarf2_cu **ref_cu)
17277 {
17278   struct die_info temp_die;
17279   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17280
17281   gdb_assert (cu->per_cu != NULL);
17282
17283   target_cu = cu;
17284
17285   if (cu->per_cu->is_debug_types)
17286     {
17287       /* .debug_types CUs cannot reference anything outside their CU.
17288          If they need to, they have to reference a signatured type via
17289          DW_FORM_ref_sig8.  */
17290       if (! offset_in_cu_p (&cu->header, offset))
17291         return NULL;
17292     }
17293   else if (offset_in_dwz != cu->per_cu->is_dwz
17294            || ! offset_in_cu_p (&cu->header, offset))
17295     {
17296       struct dwarf2_per_cu_data *per_cu;
17297
17298       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17299                                                  cu->objfile);
17300
17301       /* If necessary, add it to the queue and load its DIEs.  */
17302       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17303         load_full_comp_unit (per_cu, cu->language);
17304
17305       target_cu = per_cu->cu;
17306     }
17307   else if (cu->dies == NULL)
17308     {
17309       /* We're loading full DIEs during partial symbol reading.  */
17310       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17311       load_full_comp_unit (cu->per_cu, language_minimal);
17312     }
17313
17314   *ref_cu = target_cu;
17315   temp_die.offset = offset;
17316   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17317 }
17318
17319 /* Follow reference attribute ATTR of SRC_DIE.
17320    On entry *REF_CU is the CU of SRC_DIE.
17321    On exit *REF_CU is the CU of the result.  */
17322
17323 static struct die_info *
17324 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17325                 struct dwarf2_cu **ref_cu)
17326 {
17327   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17328   struct dwarf2_cu *cu = *ref_cu;
17329   struct die_info *die;
17330
17331   die = follow_die_offset (offset,
17332                            (attr->form == DW_FORM_GNU_ref_alt
17333                             || cu->per_cu->is_dwz),
17334                            ref_cu);
17335   if (!die)
17336     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17337            "at 0x%x [in module %s]"),
17338            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17339
17340   return die;
17341 }
17342
17343 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17344    Returned value is intended for DW_OP_call*.  Returned
17345    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17346
17347 struct dwarf2_locexpr_baton
17348 dwarf2_fetch_die_location_block (cu_offset offset_in_cu,
17349                                  struct dwarf2_per_cu_data *per_cu,
17350                                  CORE_ADDR (*get_frame_pc) (void *baton),
17351                                  void *baton)
17352 {
17353   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17354   struct dwarf2_cu *cu;
17355   struct die_info *die;
17356   struct attribute *attr;
17357   struct dwarf2_locexpr_baton retval;
17358
17359   dw2_setup (per_cu->objfile);
17360
17361   if (per_cu->cu == NULL)
17362     load_cu (per_cu);
17363   cu = per_cu->cu;
17364
17365   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17366   if (!die)
17367     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17368            offset.sect_off, per_cu->objfile->name);
17369
17370   attr = dwarf2_attr (die, DW_AT_location, cu);
17371   if (!attr)
17372     {
17373       /* DWARF: "If there is no such attribute, then there is no effect.".
17374          DATA is ignored if SIZE is 0.  */
17375
17376       retval.data = NULL;
17377       retval.size = 0;
17378     }
17379   else if (attr_form_is_section_offset (attr))
17380     {
17381       struct dwarf2_loclist_baton loclist_baton;
17382       CORE_ADDR pc = (*get_frame_pc) (baton);
17383       size_t size;
17384
17385       fill_in_loclist_baton (cu, &loclist_baton, attr);
17386
17387       retval.data = dwarf2_find_location_expression (&loclist_baton,
17388                                                      &size, pc);
17389       retval.size = size;
17390     }
17391   else
17392     {
17393       if (!attr_form_is_block (attr))
17394         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17395                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17396                offset.sect_off, per_cu->objfile->name);
17397
17398       retval.data = DW_BLOCK (attr)->data;
17399       retval.size = DW_BLOCK (attr)->size;
17400     }
17401   retval.per_cu = cu->per_cu;
17402
17403   age_cached_comp_units ();
17404
17405   return retval;
17406 }
17407
17408 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17409    PER_CU.  */
17410
17411 struct type *
17412 dwarf2_get_die_type (cu_offset die_offset,
17413                      struct dwarf2_per_cu_data *per_cu)
17414 {
17415   sect_offset die_offset_sect;
17416
17417   dw2_setup (per_cu->objfile);
17418
17419   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17420   return get_die_type_at_offset (die_offset_sect, per_cu);
17421 }
17422
17423 /* Follow the signature attribute ATTR in SRC_DIE.
17424    On entry *REF_CU is the CU of SRC_DIE.
17425    On exit *REF_CU is the CU of the result.  */
17426
17427 static struct die_info *
17428 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17429                 struct dwarf2_cu **ref_cu)
17430 {
17431   struct objfile *objfile = (*ref_cu)->objfile;
17432   struct die_info temp_die;
17433   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17434   struct dwarf2_cu *sig_cu;
17435   struct die_info *die;
17436
17437   /* sig_type will be NULL if the signatured type is missing from
17438      the debug info.  */
17439   if (sig_type == NULL)
17440     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17441              "at 0x%x [in module %s]"),
17442            src_die->offset.sect_off, objfile->name);
17443
17444   /* If necessary, add it to the queue and load its DIEs.  */
17445
17446   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17447     read_signatured_type (sig_type);
17448
17449   gdb_assert (sig_type->per_cu.cu != NULL);
17450
17451   sig_cu = sig_type->per_cu.cu;
17452   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17453   temp_die.offset = sig_type->type_offset_in_section;
17454   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17455                              temp_die.offset.sect_off);
17456   if (die)
17457     {
17458       *ref_cu = sig_cu;
17459       return die;
17460     }
17461
17462   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17463          "from DIE at 0x%x [in module %s]"),
17464          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17465 }
17466
17467 /* Given an offset of a signatured type, return its signatured_type.  */
17468
17469 static struct signatured_type *
17470 lookup_signatured_type_at_offset (struct objfile *objfile,
17471                                   struct dwarf2_section_info *section,
17472                                   sect_offset offset)
17473 {
17474   gdb_byte *info_ptr = section->buffer + offset.sect_off;
17475   unsigned int length, initial_length_size;
17476   unsigned int sig_offset;
17477   struct signatured_type find_entry, *sig_type;
17478
17479   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
17480   sig_offset = (initial_length_size
17481                 + 2 /*version*/
17482                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
17483                 + 1 /*address_size*/);
17484   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
17485   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
17486
17487   /* This is only used to lookup previously recorded types.
17488      If we didn't find it, it's our bug.  */
17489   gdb_assert (sig_type != NULL);
17490   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
17491
17492   return sig_type;
17493 }
17494
17495 /* Load the DIEs associated with type unit PER_CU into memory.  */
17496
17497 static void
17498 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17499 {
17500   struct signatured_type *sig_type;
17501
17502   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17503   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17504
17505   /* We have the per_cu, but we need the signatured_type.
17506      Fortunately this is an easy translation.  */
17507   gdb_assert (per_cu->is_debug_types);
17508   sig_type = (struct signatured_type *) per_cu;
17509
17510   gdb_assert (per_cu->cu == NULL);
17511
17512   read_signatured_type (sig_type);
17513
17514   gdb_assert (per_cu->cu != NULL);
17515 }
17516
17517 /* die_reader_func for read_signatured_type.
17518    This is identical to load_full_comp_unit_reader,
17519    but is kept separate for now.  */
17520
17521 static void
17522 read_signatured_type_reader (const struct die_reader_specs *reader,
17523                              gdb_byte *info_ptr,
17524                              struct die_info *comp_unit_die,
17525                              int has_children,
17526                              void *data)
17527 {
17528   struct dwarf2_cu *cu = reader->cu;
17529
17530   gdb_assert (cu->die_hash == NULL);
17531   cu->die_hash =
17532     htab_create_alloc_ex (cu->header.length / 12,
17533                           die_hash,
17534                           die_eq,
17535                           NULL,
17536                           &cu->comp_unit_obstack,
17537                           hashtab_obstack_allocate,
17538                           dummy_obstack_deallocate);
17539
17540   if (has_children)
17541     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17542                                                   &info_ptr, comp_unit_die);
17543   cu->dies = comp_unit_die;
17544   /* comp_unit_die is not stored in die_hash, no need.  */
17545
17546   /* We try not to read any attributes in this function, because not
17547      all CUs needed for references have been loaded yet, and symbol
17548      table processing isn't initialized.  But we have to set the CU language,
17549      or we won't be able to build types correctly.
17550      Similarly, if we do not read the producer, we can not apply
17551      producer-specific interpretation.  */
17552   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17553 }
17554
17555 /* Read in a signatured type and build its CU and DIEs.
17556    If the type is a stub for the real type in a DWO file,
17557    read in the real type from the DWO file as well.  */
17558
17559 static void
17560 read_signatured_type (struct signatured_type *sig_type)
17561 {
17562   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17563
17564   gdb_assert (per_cu->is_debug_types);
17565   gdb_assert (per_cu->cu == NULL);
17566
17567   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17568                            read_signatured_type_reader, NULL);
17569 }
17570
17571 /* Decode simple location descriptions.
17572    Given a pointer to a dwarf block that defines a location, compute
17573    the location and return the value.
17574
17575    NOTE drow/2003-11-18: This function is called in two situations
17576    now: for the address of static or global variables (partial symbols
17577    only) and for offsets into structures which are expected to be
17578    (more or less) constant.  The partial symbol case should go away,
17579    and only the constant case should remain.  That will let this
17580    function complain more accurately.  A few special modes are allowed
17581    without complaint for global variables (for instance, global
17582    register values and thread-local values).
17583
17584    A location description containing no operations indicates that the
17585    object is optimized out.  The return value is 0 for that case.
17586    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17587    callers will only want a very basic result and this can become a
17588    complaint.
17589
17590    Note that stack[0] is unused except as a default error return.  */
17591
17592 static CORE_ADDR
17593 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17594 {
17595   struct objfile *objfile = cu->objfile;
17596   size_t i;
17597   size_t size = blk->size;
17598   gdb_byte *data = blk->data;
17599   CORE_ADDR stack[64];
17600   int stacki;
17601   unsigned int bytes_read, unsnd;
17602   gdb_byte op;
17603
17604   i = 0;
17605   stacki = 0;
17606   stack[stacki] = 0;
17607   stack[++stacki] = 0;
17608
17609   while (i < size)
17610     {
17611       op = data[i++];
17612       switch (op)
17613         {
17614         case DW_OP_lit0:
17615         case DW_OP_lit1:
17616         case DW_OP_lit2:
17617         case DW_OP_lit3:
17618         case DW_OP_lit4:
17619         case DW_OP_lit5:
17620         case DW_OP_lit6:
17621         case DW_OP_lit7:
17622         case DW_OP_lit8:
17623         case DW_OP_lit9:
17624         case DW_OP_lit10:
17625         case DW_OP_lit11:
17626         case DW_OP_lit12:
17627         case DW_OP_lit13:
17628         case DW_OP_lit14:
17629         case DW_OP_lit15:
17630         case DW_OP_lit16:
17631         case DW_OP_lit17:
17632         case DW_OP_lit18:
17633         case DW_OP_lit19:
17634         case DW_OP_lit20:
17635         case DW_OP_lit21:
17636         case DW_OP_lit22:
17637         case DW_OP_lit23:
17638         case DW_OP_lit24:
17639         case DW_OP_lit25:
17640         case DW_OP_lit26:
17641         case DW_OP_lit27:
17642         case DW_OP_lit28:
17643         case DW_OP_lit29:
17644         case DW_OP_lit30:
17645         case DW_OP_lit31:
17646           stack[++stacki] = op - DW_OP_lit0;
17647           break;
17648
17649         case DW_OP_reg0:
17650         case DW_OP_reg1:
17651         case DW_OP_reg2:
17652         case DW_OP_reg3:
17653         case DW_OP_reg4:
17654         case DW_OP_reg5:
17655         case DW_OP_reg6:
17656         case DW_OP_reg7:
17657         case DW_OP_reg8:
17658         case DW_OP_reg9:
17659         case DW_OP_reg10:
17660         case DW_OP_reg11:
17661         case DW_OP_reg12:
17662         case DW_OP_reg13:
17663         case DW_OP_reg14:
17664         case DW_OP_reg15:
17665         case DW_OP_reg16:
17666         case DW_OP_reg17:
17667         case DW_OP_reg18:
17668         case DW_OP_reg19:
17669         case DW_OP_reg20:
17670         case DW_OP_reg21:
17671         case DW_OP_reg22:
17672         case DW_OP_reg23:
17673         case DW_OP_reg24:
17674         case DW_OP_reg25:
17675         case DW_OP_reg26:
17676         case DW_OP_reg27:
17677         case DW_OP_reg28:
17678         case DW_OP_reg29:
17679         case DW_OP_reg30:
17680         case DW_OP_reg31:
17681           stack[++stacki] = op - DW_OP_reg0;
17682           if (i < size)
17683             dwarf2_complex_location_expr_complaint ();
17684           break;
17685
17686         case DW_OP_regx:
17687           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
17688           i += bytes_read;
17689           stack[++stacki] = unsnd;
17690           if (i < size)
17691             dwarf2_complex_location_expr_complaint ();
17692           break;
17693
17694         case DW_OP_addr:
17695           stack[++stacki] = read_address (objfile->obfd, &data[i],
17696                                           cu, &bytes_read);
17697           i += bytes_read;
17698           break;
17699
17700         case DW_OP_const1u:
17701           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
17702           i += 1;
17703           break;
17704
17705         case DW_OP_const1s:
17706           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
17707           i += 1;
17708           break;
17709
17710         case DW_OP_const2u:
17711           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
17712           i += 2;
17713           break;
17714
17715         case DW_OP_const2s:
17716           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
17717           i += 2;
17718           break;
17719
17720         case DW_OP_const4u:
17721           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
17722           i += 4;
17723           break;
17724
17725         case DW_OP_const4s:
17726           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
17727           i += 4;
17728           break;
17729
17730         case DW_OP_const8u:
17731           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
17732           i += 8;
17733           break;
17734
17735         case DW_OP_constu:
17736           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
17737                                                   &bytes_read);
17738           i += bytes_read;
17739           break;
17740
17741         case DW_OP_consts:
17742           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
17743           i += bytes_read;
17744           break;
17745
17746         case DW_OP_dup:
17747           stack[stacki + 1] = stack[stacki];
17748           stacki++;
17749           break;
17750
17751         case DW_OP_plus:
17752           stack[stacki - 1] += stack[stacki];
17753           stacki--;
17754           break;
17755
17756         case DW_OP_plus_uconst:
17757           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
17758                                                  &bytes_read);
17759           i += bytes_read;
17760           break;
17761
17762         case DW_OP_minus:
17763           stack[stacki - 1] -= stack[stacki];
17764           stacki--;
17765           break;
17766
17767         case DW_OP_deref:
17768           /* If we're not the last op, then we definitely can't encode
17769              this using GDB's address_class enum.  This is valid for partial
17770              global symbols, although the variable's address will be bogus
17771              in the psymtab.  */
17772           if (i < size)
17773             dwarf2_complex_location_expr_complaint ();
17774           break;
17775
17776         case DW_OP_GNU_push_tls_address:
17777           /* The top of the stack has the offset from the beginning
17778              of the thread control block at which the variable is located.  */
17779           /* Nothing should follow this operator, so the top of stack would
17780              be returned.  */
17781           /* This is valid for partial global symbols, but the variable's
17782              address will be bogus in the psymtab.  Make it always at least
17783              non-zero to not look as a variable garbage collected by linker
17784              which have DW_OP_addr 0.  */
17785           if (i < size)
17786             dwarf2_complex_location_expr_complaint ();
17787           stack[stacki]++;
17788           break;
17789
17790         case DW_OP_GNU_uninit:
17791           break;
17792
17793         case DW_OP_GNU_addr_index:
17794         case DW_OP_GNU_const_index:
17795           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
17796                                                          &bytes_read);
17797           i += bytes_read;
17798           break;
17799
17800         default:
17801           {
17802             const char *name = get_DW_OP_name (op);
17803
17804             if (name)
17805               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
17806                          name);
17807             else
17808               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
17809                          op);
17810           }
17811
17812           return (stack[stacki]);
17813         }
17814
17815       /* Enforce maximum stack depth of SIZE-1 to avoid writing
17816          outside of the allocated space.  Also enforce minimum>0.  */
17817       if (stacki >= ARRAY_SIZE (stack) - 1)
17818         {
17819           complaint (&symfile_complaints,
17820                      _("location description stack overflow"));
17821           return 0;
17822         }
17823
17824       if (stacki <= 0)
17825         {
17826           complaint (&symfile_complaints,
17827                      _("location description stack underflow"));
17828           return 0;
17829         }
17830     }
17831   return (stack[stacki]);
17832 }
17833
17834 /* memory allocation interface */
17835
17836 static struct dwarf_block *
17837 dwarf_alloc_block (struct dwarf2_cu *cu)
17838 {
17839   struct dwarf_block *blk;
17840
17841   blk = (struct dwarf_block *)
17842     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
17843   return (blk);
17844 }
17845
17846 static struct die_info *
17847 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
17848 {
17849   struct die_info *die;
17850   size_t size = sizeof (struct die_info);
17851
17852   if (num_attrs > 1)
17853     size += (num_attrs - 1) * sizeof (struct attribute);
17854
17855   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
17856   memset (die, 0, sizeof (struct die_info));
17857   return (die);
17858 }
17859
17860 \f
17861 /* Macro support.  */
17862
17863 /* Return the full name of file number I in *LH's file name table.
17864    Use COMP_DIR as the name of the current directory of the
17865    compilation.  The result is allocated using xmalloc; the caller is
17866    responsible for freeing it.  */
17867 static char *
17868 file_full_name (int file, struct line_header *lh, const char *comp_dir)
17869 {
17870   /* Is the file number a valid index into the line header's file name
17871      table?  Remember that file numbers start with one, not zero.  */
17872   if (1 <= file && file <= lh->num_file_names)
17873     {
17874       struct file_entry *fe = &lh->file_names[file - 1];
17875
17876       if (IS_ABSOLUTE_PATH (fe->name))
17877         return xstrdup (fe->name);
17878       else
17879         {
17880           const char *dir;
17881           int dir_len;
17882           char *full_name;
17883
17884           if (fe->dir_index)
17885             dir = lh->include_dirs[fe->dir_index - 1];
17886           else
17887             dir = comp_dir;
17888
17889           if (dir)
17890             {
17891               dir_len = strlen (dir);
17892               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
17893               strcpy (full_name, dir);
17894               full_name[dir_len] = '/';
17895               strcpy (full_name + dir_len + 1, fe->name);
17896               return full_name;
17897             }
17898           else
17899             return xstrdup (fe->name);
17900         }
17901     }
17902   else
17903     {
17904       /* The compiler produced a bogus file number.  We can at least
17905          record the macro definitions made in the file, even if we
17906          won't be able to find the file by name.  */
17907       char fake_name[80];
17908
17909       xsnprintf (fake_name, sizeof (fake_name),
17910                  "<bad macro file number %d>", file);
17911
17912       complaint (&symfile_complaints,
17913                  _("bad file number in macro information (%d)"),
17914                  file);
17915
17916       return xstrdup (fake_name);
17917     }
17918 }
17919
17920
17921 static struct macro_source_file *
17922 macro_start_file (int file, int line,
17923                   struct macro_source_file *current_file,
17924                   const char *comp_dir,
17925                   struct line_header *lh, struct objfile *objfile)
17926 {
17927   /* The full name of this source file.  */
17928   char *full_name = file_full_name (file, lh, comp_dir);
17929
17930   /* We don't create a macro table for this compilation unit
17931      at all until we actually get a filename.  */
17932   if (! pending_macros)
17933     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
17934                                       objfile->per_bfd->macro_cache);
17935
17936   if (! current_file)
17937     {
17938       /* If we have no current file, then this must be the start_file
17939          directive for the compilation unit's main source file.  */
17940       current_file = macro_set_main (pending_macros, full_name);
17941       macro_define_special (pending_macros);
17942     }
17943   else
17944     current_file = macro_include (current_file, line, full_name);
17945
17946   xfree (full_name);
17947
17948   return current_file;
17949 }
17950
17951
17952 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
17953    followed by a null byte.  */
17954 static char *
17955 copy_string (const char *buf, int len)
17956 {
17957   char *s = xmalloc (len + 1);
17958
17959   memcpy (s, buf, len);
17960   s[len] = '\0';
17961   return s;
17962 }
17963
17964
17965 static const char *
17966 consume_improper_spaces (const char *p, const char *body)
17967 {
17968   if (*p == ' ')
17969     {
17970       complaint (&symfile_complaints,
17971                  _("macro definition contains spaces "
17972                    "in formal argument list:\n`%s'"),
17973                  body);
17974
17975       while (*p == ' ')
17976         p++;
17977     }
17978
17979   return p;
17980 }
17981
17982
17983 static void
17984 parse_macro_definition (struct macro_source_file *file, int line,
17985                         const char *body)
17986 {
17987   const char *p;
17988
17989   /* The body string takes one of two forms.  For object-like macro
17990      definitions, it should be:
17991
17992         <macro name> " " <definition>
17993
17994      For function-like macro definitions, it should be:
17995
17996         <macro name> "() " <definition>
17997      or
17998         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
17999
18000      Spaces may appear only where explicitly indicated, and in the
18001      <definition>.
18002
18003      The Dwarf 2 spec says that an object-like macro's name is always
18004      followed by a space, but versions of GCC around March 2002 omit
18005      the space when the macro's definition is the empty string.
18006
18007      The Dwarf 2 spec says that there should be no spaces between the
18008      formal arguments in a function-like macro's formal argument list,
18009      but versions of GCC around March 2002 include spaces after the
18010      commas.  */
18011
18012
18013   /* Find the extent of the macro name.  The macro name is terminated
18014      by either a space or null character (for an object-like macro) or
18015      an opening paren (for a function-like macro).  */
18016   for (p = body; *p; p++)
18017     if (*p == ' ' || *p == '(')
18018       break;
18019
18020   if (*p == ' ' || *p == '\0')
18021     {
18022       /* It's an object-like macro.  */
18023       int name_len = p - body;
18024       char *name = copy_string (body, name_len);
18025       const char *replacement;
18026
18027       if (*p == ' ')
18028         replacement = body + name_len + 1;
18029       else
18030         {
18031           dwarf2_macro_malformed_definition_complaint (body);
18032           replacement = body + name_len;
18033         }
18034
18035       macro_define_object (file, line, name, replacement);
18036
18037       xfree (name);
18038     }
18039   else if (*p == '(')
18040     {
18041       /* It's a function-like macro.  */
18042       char *name = copy_string (body, p - body);
18043       int argc = 0;
18044       int argv_size = 1;
18045       char **argv = xmalloc (argv_size * sizeof (*argv));
18046
18047       p++;
18048
18049       p = consume_improper_spaces (p, body);
18050
18051       /* Parse the formal argument list.  */
18052       while (*p && *p != ')')
18053         {
18054           /* Find the extent of the current argument name.  */
18055           const char *arg_start = p;
18056
18057           while (*p && *p != ',' && *p != ')' && *p != ' ')
18058             p++;
18059
18060           if (! *p || p == arg_start)
18061             dwarf2_macro_malformed_definition_complaint (body);
18062           else
18063             {
18064               /* Make sure argv has room for the new argument.  */
18065               if (argc >= argv_size)
18066                 {
18067                   argv_size *= 2;
18068                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18069                 }
18070
18071               argv[argc++] = copy_string (arg_start, p - arg_start);
18072             }
18073
18074           p = consume_improper_spaces (p, body);
18075
18076           /* Consume the comma, if present.  */
18077           if (*p == ',')
18078             {
18079               p++;
18080
18081               p = consume_improper_spaces (p, body);
18082             }
18083         }
18084
18085       if (*p == ')')
18086         {
18087           p++;
18088
18089           if (*p == ' ')
18090             /* Perfectly formed definition, no complaints.  */
18091             macro_define_function (file, line, name,
18092                                    argc, (const char **) argv,
18093                                    p + 1);
18094           else if (*p == '\0')
18095             {
18096               /* Complain, but do define it.  */
18097               dwarf2_macro_malformed_definition_complaint (body);
18098               macro_define_function (file, line, name,
18099                                      argc, (const char **) argv,
18100                                      p);
18101             }
18102           else
18103             /* Just complain.  */
18104             dwarf2_macro_malformed_definition_complaint (body);
18105         }
18106       else
18107         /* Just complain.  */
18108         dwarf2_macro_malformed_definition_complaint (body);
18109
18110       xfree (name);
18111       {
18112         int i;
18113
18114         for (i = 0; i < argc; i++)
18115           xfree (argv[i]);
18116       }
18117       xfree (argv);
18118     }
18119   else
18120     dwarf2_macro_malformed_definition_complaint (body);
18121 }
18122
18123 /* Skip some bytes from BYTES according to the form given in FORM.
18124    Returns the new pointer.  */
18125
18126 static gdb_byte *
18127 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
18128                  enum dwarf_form form,
18129                  unsigned int offset_size,
18130                  struct dwarf2_section_info *section)
18131 {
18132   unsigned int bytes_read;
18133
18134   switch (form)
18135     {
18136     case DW_FORM_data1:
18137     case DW_FORM_flag:
18138       ++bytes;
18139       break;
18140
18141     case DW_FORM_data2:
18142       bytes += 2;
18143       break;
18144
18145     case DW_FORM_data4:
18146       bytes += 4;
18147       break;
18148
18149     case DW_FORM_data8:
18150       bytes += 8;
18151       break;
18152
18153     case DW_FORM_string:
18154       read_direct_string (abfd, bytes, &bytes_read);
18155       bytes += bytes_read;
18156       break;
18157
18158     case DW_FORM_sec_offset:
18159     case DW_FORM_strp:
18160     case DW_FORM_GNU_strp_alt:
18161       bytes += offset_size;
18162       break;
18163
18164     case DW_FORM_block:
18165       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18166       bytes += bytes_read;
18167       break;
18168
18169     case DW_FORM_block1:
18170       bytes += 1 + read_1_byte (abfd, bytes);
18171       break;
18172     case DW_FORM_block2:
18173       bytes += 2 + read_2_bytes (abfd, bytes);
18174       break;
18175     case DW_FORM_block4:
18176       bytes += 4 + read_4_bytes (abfd, bytes);
18177       break;
18178
18179     case DW_FORM_sdata:
18180     case DW_FORM_udata:
18181     case DW_FORM_GNU_addr_index:
18182     case DW_FORM_GNU_str_index:
18183       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
18184       if (bytes == NULL)
18185         {
18186           dwarf2_section_buffer_overflow_complaint (section);
18187           return NULL;
18188         }
18189       break;
18190
18191     default:
18192       {
18193       complain:
18194         complaint (&symfile_complaints,
18195                    _("invalid form 0x%x in `%s'"),
18196                    form,
18197                    section->asection->name);
18198         return NULL;
18199       }
18200     }
18201
18202   return bytes;
18203 }
18204
18205 /* A helper for dwarf_decode_macros that handles skipping an unknown
18206    opcode.  Returns an updated pointer to the macro data buffer; or,
18207    on error, issues a complaint and returns NULL.  */
18208
18209 static gdb_byte *
18210 skip_unknown_opcode (unsigned int opcode,
18211                      gdb_byte **opcode_definitions,
18212                      gdb_byte *mac_ptr, gdb_byte *mac_end,
18213                      bfd *abfd,
18214                      unsigned int offset_size,
18215                      struct dwarf2_section_info *section)
18216 {
18217   unsigned int bytes_read, i;
18218   unsigned long arg;
18219   gdb_byte *defn;
18220
18221   if (opcode_definitions[opcode] == NULL)
18222     {
18223       complaint (&symfile_complaints,
18224                  _("unrecognized DW_MACFINO opcode 0x%x"),
18225                  opcode);
18226       return NULL;
18227     }
18228
18229   defn = opcode_definitions[opcode];
18230   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18231   defn += bytes_read;
18232
18233   for (i = 0; i < arg; ++i)
18234     {
18235       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18236                                  section);
18237       if (mac_ptr == NULL)
18238         {
18239           /* skip_form_bytes already issued the complaint.  */
18240           return NULL;
18241         }
18242     }
18243
18244   return mac_ptr;
18245 }
18246
18247 /* A helper function which parses the header of a macro section.
18248    If the macro section is the extended (for now called "GNU") type,
18249    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18250    the header, or issues a complaint and returns NULL on error.  */
18251
18252 static gdb_byte *
18253 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
18254                           bfd *abfd,
18255                           gdb_byte *mac_ptr,
18256                           unsigned int *offset_size,
18257                           int section_is_gnu)
18258 {
18259   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18260
18261   if (section_is_gnu)
18262     {
18263       unsigned int version, flags;
18264
18265       version = read_2_bytes (abfd, mac_ptr);
18266       if (version != 4)
18267         {
18268           complaint (&symfile_complaints,
18269                      _("unrecognized version `%d' in .debug_macro section"),
18270                      version);
18271           return NULL;
18272         }
18273       mac_ptr += 2;
18274
18275       flags = read_1_byte (abfd, mac_ptr);
18276       ++mac_ptr;
18277       *offset_size = (flags & 1) ? 8 : 4;
18278
18279       if ((flags & 2) != 0)
18280         /* We don't need the line table offset.  */
18281         mac_ptr += *offset_size;
18282
18283       /* Vendor opcode descriptions.  */
18284       if ((flags & 4) != 0)
18285         {
18286           unsigned int i, count;
18287
18288           count = read_1_byte (abfd, mac_ptr);
18289           ++mac_ptr;
18290           for (i = 0; i < count; ++i)
18291             {
18292               unsigned int opcode, bytes_read;
18293               unsigned long arg;
18294
18295               opcode = read_1_byte (abfd, mac_ptr);
18296               ++mac_ptr;
18297               opcode_definitions[opcode] = mac_ptr;
18298               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18299               mac_ptr += bytes_read;
18300               mac_ptr += arg;
18301             }
18302         }
18303     }
18304
18305   return mac_ptr;
18306 }
18307
18308 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18309    including DW_MACRO_GNU_transparent_include.  */
18310
18311 static void
18312 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
18313                           struct macro_source_file *current_file,
18314                           struct line_header *lh, char *comp_dir,
18315                           struct dwarf2_section_info *section,
18316                           int section_is_gnu, int section_is_dwz,
18317                           unsigned int offset_size,
18318                           struct objfile *objfile,
18319                           htab_t include_hash)
18320 {
18321   enum dwarf_macro_record_type macinfo_type;
18322   int at_commandline;
18323   gdb_byte *opcode_definitions[256];
18324
18325   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18326                                       &offset_size, section_is_gnu);
18327   if (mac_ptr == NULL)
18328     {
18329       /* We already issued a complaint.  */
18330       return;
18331     }
18332
18333   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18334      GDB is still reading the definitions from command line.  First
18335      DW_MACINFO_start_file will need to be ignored as it was already executed
18336      to create CURRENT_FILE for the main source holding also the command line
18337      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18338      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18339
18340   at_commandline = 1;
18341
18342   do
18343     {
18344       /* Do we at least have room for a macinfo type byte?  */
18345       if (mac_ptr >= mac_end)
18346         {
18347           dwarf2_section_buffer_overflow_complaint (section);
18348           break;
18349         }
18350
18351       macinfo_type = read_1_byte (abfd, mac_ptr);
18352       mac_ptr++;
18353
18354       /* Note that we rely on the fact that the corresponding GNU and
18355          DWARF constants are the same.  */
18356       switch (macinfo_type)
18357         {
18358           /* A zero macinfo type indicates the end of the macro
18359              information.  */
18360         case 0:
18361           break;
18362
18363         case DW_MACRO_GNU_define:
18364         case DW_MACRO_GNU_undef:
18365         case DW_MACRO_GNU_define_indirect:
18366         case DW_MACRO_GNU_undef_indirect:
18367         case DW_MACRO_GNU_define_indirect_alt:
18368         case DW_MACRO_GNU_undef_indirect_alt:
18369           {
18370             unsigned int bytes_read;
18371             int line;
18372             char *body;
18373             int is_define;
18374
18375             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18376             mac_ptr += bytes_read;
18377
18378             if (macinfo_type == DW_MACRO_GNU_define
18379                 || macinfo_type == DW_MACRO_GNU_undef)
18380               {
18381                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18382                 mac_ptr += bytes_read;
18383               }
18384             else
18385               {
18386                 LONGEST str_offset;
18387
18388                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18389                 mac_ptr += offset_size;
18390
18391                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18392                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18393                     || section_is_dwz)
18394                   {
18395                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18396
18397                     body = read_indirect_string_from_dwz (dwz, str_offset);
18398                   }
18399                 else
18400                   body = read_indirect_string_at_offset (abfd, str_offset);
18401               }
18402
18403             is_define = (macinfo_type == DW_MACRO_GNU_define
18404                          || macinfo_type == DW_MACRO_GNU_define_indirect
18405                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18406             if (! current_file)
18407               {
18408                 /* DWARF violation as no main source is present.  */
18409                 complaint (&symfile_complaints,
18410                            _("debug info with no main source gives macro %s "
18411                              "on line %d: %s"),
18412                            is_define ? _("definition") : _("undefinition"),
18413                            line, body);
18414                 break;
18415               }
18416             if ((line == 0 && !at_commandline)
18417                 || (line != 0 && at_commandline))
18418               complaint (&symfile_complaints,
18419                          _("debug info gives %s macro %s with %s line %d: %s"),
18420                          at_commandline ? _("command-line") : _("in-file"),
18421                          is_define ? _("definition") : _("undefinition"),
18422                          line == 0 ? _("zero") : _("non-zero"), line, body);
18423
18424             if (is_define)
18425               parse_macro_definition (current_file, line, body);
18426             else
18427               {
18428                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18429                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18430                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18431                 macro_undef (current_file, line, body);
18432               }
18433           }
18434           break;
18435
18436         case DW_MACRO_GNU_start_file:
18437           {
18438             unsigned int bytes_read;
18439             int line, file;
18440
18441             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18442             mac_ptr += bytes_read;
18443             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18444             mac_ptr += bytes_read;
18445
18446             if ((line == 0 && !at_commandline)
18447                 || (line != 0 && at_commandline))
18448               complaint (&symfile_complaints,
18449                          _("debug info gives source %d included "
18450                            "from %s at %s line %d"),
18451                          file, at_commandline ? _("command-line") : _("file"),
18452                          line == 0 ? _("zero") : _("non-zero"), line);
18453
18454             if (at_commandline)
18455               {
18456                 /* This DW_MACRO_GNU_start_file was executed in the
18457                    pass one.  */
18458                 at_commandline = 0;
18459               }
18460             else
18461               current_file = macro_start_file (file, line,
18462                                                current_file, comp_dir,
18463                                                lh, objfile);
18464           }
18465           break;
18466
18467         case DW_MACRO_GNU_end_file:
18468           if (! current_file)
18469             complaint (&symfile_complaints,
18470                        _("macro debug info has an unmatched "
18471                          "`close_file' directive"));
18472           else
18473             {
18474               current_file = current_file->included_by;
18475               if (! current_file)
18476                 {
18477                   enum dwarf_macro_record_type next_type;
18478
18479                   /* GCC circa March 2002 doesn't produce the zero
18480                      type byte marking the end of the compilation
18481                      unit.  Complain if it's not there, but exit no
18482                      matter what.  */
18483
18484                   /* Do we at least have room for a macinfo type byte?  */
18485                   if (mac_ptr >= mac_end)
18486                     {
18487                       dwarf2_section_buffer_overflow_complaint (section);
18488                       return;
18489                     }
18490
18491                   /* We don't increment mac_ptr here, so this is just
18492                      a look-ahead.  */
18493                   next_type = read_1_byte (abfd, mac_ptr);
18494                   if (next_type != 0)
18495                     complaint (&symfile_complaints,
18496                                _("no terminating 0-type entry for "
18497                                  "macros in `.debug_macinfo' section"));
18498
18499                   return;
18500                 }
18501             }
18502           break;
18503
18504         case DW_MACRO_GNU_transparent_include:
18505         case DW_MACRO_GNU_transparent_include_alt:
18506           {
18507             LONGEST offset;
18508             void **slot;
18509             bfd *include_bfd = abfd;
18510             struct dwarf2_section_info *include_section = section;
18511             struct dwarf2_section_info alt_section;
18512             gdb_byte *include_mac_end = mac_end;
18513             int is_dwz = section_is_dwz;
18514             gdb_byte *new_mac_ptr;
18515
18516             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18517             mac_ptr += offset_size;
18518
18519             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18520               {
18521                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18522
18523                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18524                                      &dwz->macro);
18525
18526                 include_bfd = dwz->macro.asection->owner;
18527                 include_section = &dwz->macro;
18528                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18529                 is_dwz = 1;
18530               }
18531
18532             new_mac_ptr = include_section->buffer + offset;
18533             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18534
18535             if (*slot != NULL)
18536               {
18537                 /* This has actually happened; see
18538                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18539                 complaint (&symfile_complaints,
18540                            _("recursive DW_MACRO_GNU_transparent_include in "
18541                              ".debug_macro section"));
18542               }
18543             else
18544               {
18545                 *slot = new_mac_ptr;
18546
18547                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18548                                           include_mac_end, current_file,
18549                                           lh, comp_dir,
18550                                           section, section_is_gnu, is_dwz,
18551                                           offset_size, objfile, include_hash);
18552
18553                 htab_remove_elt (include_hash, new_mac_ptr);
18554               }
18555           }
18556           break;
18557
18558         case DW_MACINFO_vendor_ext:
18559           if (!section_is_gnu)
18560             {
18561               unsigned int bytes_read;
18562               int constant;
18563
18564               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18565               mac_ptr += bytes_read;
18566               read_direct_string (abfd, mac_ptr, &bytes_read);
18567               mac_ptr += bytes_read;
18568
18569               /* We don't recognize any vendor extensions.  */
18570               break;
18571             }
18572           /* FALLTHROUGH */
18573
18574         default:
18575           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18576                                          mac_ptr, mac_end, abfd, offset_size,
18577                                          section);
18578           if (mac_ptr == NULL)
18579             return;
18580           break;
18581         }
18582     } while (macinfo_type != 0);
18583 }
18584
18585 static void
18586 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18587                      char *comp_dir, int section_is_gnu)
18588 {
18589   struct objfile *objfile = dwarf2_per_objfile->objfile;
18590   struct line_header *lh = cu->line_header;
18591   bfd *abfd;
18592   gdb_byte *mac_ptr, *mac_end;
18593   struct macro_source_file *current_file = 0;
18594   enum dwarf_macro_record_type macinfo_type;
18595   unsigned int offset_size = cu->header.offset_size;
18596   gdb_byte *opcode_definitions[256];
18597   struct cleanup *cleanup;
18598   htab_t include_hash;
18599   void **slot;
18600   struct dwarf2_section_info *section;
18601   const char *section_name;
18602
18603   if (cu->dwo_unit != NULL)
18604     {
18605       if (section_is_gnu)
18606         {
18607           section = &cu->dwo_unit->dwo_file->sections.macro;
18608           section_name = ".debug_macro.dwo";
18609         }
18610       else
18611         {
18612           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18613           section_name = ".debug_macinfo.dwo";
18614         }
18615     }
18616   else
18617     {
18618       if (section_is_gnu)
18619         {
18620           section = &dwarf2_per_objfile->macro;
18621           section_name = ".debug_macro";
18622         }
18623       else
18624         {
18625           section = &dwarf2_per_objfile->macinfo;
18626           section_name = ".debug_macinfo";
18627         }
18628     }
18629
18630   dwarf2_read_section (objfile, section);
18631   if (section->buffer == NULL)
18632     {
18633       complaint (&symfile_complaints, _("missing %s section"), section_name);
18634       return;
18635     }
18636   abfd = section->asection->owner;
18637
18638   /* First pass: Find the name of the base filename.
18639      This filename is needed in order to process all macros whose definition
18640      (or undefinition) comes from the command line.  These macros are defined
18641      before the first DW_MACINFO_start_file entry, and yet still need to be
18642      associated to the base file.
18643
18644      To determine the base file name, we scan the macro definitions until we
18645      reach the first DW_MACINFO_start_file entry.  We then initialize
18646      CURRENT_FILE accordingly so that any macro definition found before the
18647      first DW_MACINFO_start_file can still be associated to the base file.  */
18648
18649   mac_ptr = section->buffer + offset;
18650   mac_end = section->buffer + section->size;
18651
18652   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18653                                       &offset_size, section_is_gnu);
18654   if (mac_ptr == NULL)
18655     {
18656       /* We already issued a complaint.  */
18657       return;
18658     }
18659
18660   do
18661     {
18662       /* Do we at least have room for a macinfo type byte?  */
18663       if (mac_ptr >= mac_end)
18664         {
18665           /* Complaint is printed during the second pass as GDB will probably
18666              stop the first pass earlier upon finding
18667              DW_MACINFO_start_file.  */
18668           break;
18669         }
18670
18671       macinfo_type = read_1_byte (abfd, mac_ptr);
18672       mac_ptr++;
18673
18674       /* Note that we rely on the fact that the corresponding GNU and
18675          DWARF constants are the same.  */
18676       switch (macinfo_type)
18677         {
18678           /* A zero macinfo type indicates the end of the macro
18679              information.  */
18680         case 0:
18681           break;
18682
18683         case DW_MACRO_GNU_define:
18684         case DW_MACRO_GNU_undef:
18685           /* Only skip the data by MAC_PTR.  */
18686           {
18687             unsigned int bytes_read;
18688
18689             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18690             mac_ptr += bytes_read;
18691             read_direct_string (abfd, mac_ptr, &bytes_read);
18692             mac_ptr += bytes_read;
18693           }
18694           break;
18695
18696         case DW_MACRO_GNU_start_file:
18697           {
18698             unsigned int bytes_read;
18699             int line, file;
18700
18701             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18702             mac_ptr += bytes_read;
18703             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18704             mac_ptr += bytes_read;
18705
18706             current_file = macro_start_file (file, line, current_file,
18707                                              comp_dir, lh, objfile);
18708           }
18709           break;
18710
18711         case DW_MACRO_GNU_end_file:
18712           /* No data to skip by MAC_PTR.  */
18713           break;
18714
18715         case DW_MACRO_GNU_define_indirect:
18716         case DW_MACRO_GNU_undef_indirect:
18717         case DW_MACRO_GNU_define_indirect_alt:
18718         case DW_MACRO_GNU_undef_indirect_alt:
18719           {
18720             unsigned int bytes_read;
18721
18722             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18723             mac_ptr += bytes_read;
18724             mac_ptr += offset_size;
18725           }
18726           break;
18727
18728         case DW_MACRO_GNU_transparent_include:
18729         case DW_MACRO_GNU_transparent_include_alt:
18730           /* Note that, according to the spec, a transparent include
18731              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
18732              skip this opcode.  */
18733           mac_ptr += offset_size;
18734           break;
18735
18736         case DW_MACINFO_vendor_ext:
18737           /* Only skip the data by MAC_PTR.  */
18738           if (!section_is_gnu)
18739             {
18740               unsigned int bytes_read;
18741
18742               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18743               mac_ptr += bytes_read;
18744               read_direct_string (abfd, mac_ptr, &bytes_read);
18745               mac_ptr += bytes_read;
18746             }
18747           /* FALLTHROUGH */
18748
18749         default:
18750           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18751                                          mac_ptr, mac_end, abfd, offset_size,
18752                                          section);
18753           if (mac_ptr == NULL)
18754             return;
18755           break;
18756         }
18757     } while (macinfo_type != 0 && current_file == NULL);
18758
18759   /* Second pass: Process all entries.
18760
18761      Use the AT_COMMAND_LINE flag to determine whether we are still processing
18762      command-line macro definitions/undefinitions.  This flag is unset when we
18763      reach the first DW_MACINFO_start_file entry.  */
18764
18765   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
18766                                     NULL, xcalloc, xfree);
18767   cleanup = make_cleanup_htab_delete (include_hash);
18768   mac_ptr = section->buffer + offset;
18769   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
18770   *slot = mac_ptr;
18771   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
18772                             current_file, lh, comp_dir, section,
18773                             section_is_gnu, 0,
18774                             offset_size, objfile, include_hash);
18775   do_cleanups (cleanup);
18776 }
18777
18778 /* Check if the attribute's form is a DW_FORM_block*
18779    if so return true else false.  */
18780
18781 static int
18782 attr_form_is_block (struct attribute *attr)
18783 {
18784   return (attr == NULL ? 0 :
18785       attr->form == DW_FORM_block1
18786       || attr->form == DW_FORM_block2
18787       || attr->form == DW_FORM_block4
18788       || attr->form == DW_FORM_block
18789       || attr->form == DW_FORM_exprloc);
18790 }
18791
18792 /* Return non-zero if ATTR's value is a section offset --- classes
18793    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
18794    You may use DW_UNSND (attr) to retrieve such offsets.
18795
18796    Section 7.5.4, "Attribute Encodings", explains that no attribute
18797    may have a value that belongs to more than one of these classes; it
18798    would be ambiguous if we did, because we use the same forms for all
18799    of them.  */
18800
18801 static int
18802 attr_form_is_section_offset (struct attribute *attr)
18803 {
18804   return (attr->form == DW_FORM_data4
18805           || attr->form == DW_FORM_data8
18806           || attr->form == DW_FORM_sec_offset);
18807 }
18808
18809 /* Return non-zero if ATTR's value falls in the 'constant' class, or
18810    zero otherwise.  When this function returns true, you can apply
18811    dwarf2_get_attr_constant_value to it.
18812
18813    However, note that for some attributes you must check
18814    attr_form_is_section_offset before using this test.  DW_FORM_data4
18815    and DW_FORM_data8 are members of both the constant class, and of
18816    the classes that contain offsets into other debug sections
18817    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
18818    that, if an attribute's can be either a constant or one of the
18819    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
18820    taken as section offsets, not constants.  */
18821
18822 static int
18823 attr_form_is_constant (struct attribute *attr)
18824 {
18825   switch (attr->form)
18826     {
18827     case DW_FORM_sdata:
18828     case DW_FORM_udata:
18829     case DW_FORM_data1:
18830     case DW_FORM_data2:
18831     case DW_FORM_data4:
18832     case DW_FORM_data8:
18833       return 1;
18834     default:
18835       return 0;
18836     }
18837 }
18838
18839 /* Return the .debug_loc section to use for CU.
18840    For DWO files use .debug_loc.dwo.  */
18841
18842 static struct dwarf2_section_info *
18843 cu_debug_loc_section (struct dwarf2_cu *cu)
18844 {
18845   if (cu->dwo_unit)
18846     return &cu->dwo_unit->dwo_file->sections.loc;
18847   return &dwarf2_per_objfile->loc;
18848 }
18849
18850 /* A helper function that fills in a dwarf2_loclist_baton.  */
18851
18852 static void
18853 fill_in_loclist_baton (struct dwarf2_cu *cu,
18854                        struct dwarf2_loclist_baton *baton,
18855                        struct attribute *attr)
18856 {
18857   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
18858
18859   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18860
18861   baton->per_cu = cu->per_cu;
18862   gdb_assert (baton->per_cu);
18863   /* We don't know how long the location list is, but make sure we
18864      don't run off the edge of the section.  */
18865   baton->size = section->size - DW_UNSND (attr);
18866   baton->data = section->buffer + DW_UNSND (attr);
18867   baton->base_address = cu->base_address;
18868   baton->from_dwo = cu->dwo_unit != NULL;
18869 }
18870
18871 static void
18872 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
18873                              struct dwarf2_cu *cu)
18874 {
18875   struct objfile *objfile = dwarf2_per_objfile->objfile;
18876   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
18877
18878   if (attr_form_is_section_offset (attr)
18879       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
18880          the section.  If so, fall through to the complaint in the
18881          other branch.  */
18882       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
18883     {
18884       struct dwarf2_loclist_baton *baton;
18885
18886       baton = obstack_alloc (&objfile->objfile_obstack,
18887                              sizeof (struct dwarf2_loclist_baton));
18888
18889       fill_in_loclist_baton (cu, baton, attr);
18890
18891       if (cu->base_known == 0)
18892         complaint (&symfile_complaints,
18893                    _("Location list used without "
18894                      "specifying the CU base address."));
18895
18896       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
18897       SYMBOL_LOCATION_BATON (sym) = baton;
18898     }
18899   else
18900     {
18901       struct dwarf2_locexpr_baton *baton;
18902
18903       baton = obstack_alloc (&objfile->objfile_obstack,
18904                              sizeof (struct dwarf2_locexpr_baton));
18905       baton->per_cu = cu->per_cu;
18906       gdb_assert (baton->per_cu);
18907
18908       if (attr_form_is_block (attr))
18909         {
18910           /* Note that we're just copying the block's data pointer
18911              here, not the actual data.  We're still pointing into the
18912              info_buffer for SYM's objfile; right now we never release
18913              that buffer, but when we do clean up properly this may
18914              need to change.  */
18915           baton->size = DW_BLOCK (attr)->size;
18916           baton->data = DW_BLOCK (attr)->data;
18917         }
18918       else
18919         {
18920           dwarf2_invalid_attrib_class_complaint ("location description",
18921                                                  SYMBOL_NATURAL_NAME (sym));
18922           baton->size = 0;
18923         }
18924
18925       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
18926       SYMBOL_LOCATION_BATON (sym) = baton;
18927     }
18928 }
18929
18930 /* Return the OBJFILE associated with the compilation unit CU.  If CU
18931    came from a separate debuginfo file, then the master objfile is
18932    returned.  */
18933
18934 struct objfile *
18935 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
18936 {
18937   struct objfile *objfile = per_cu->objfile;
18938
18939   /* Return the master objfile, so that we can report and look up the
18940      correct file containing this variable.  */
18941   if (objfile->separate_debug_objfile_backlink)
18942     objfile = objfile->separate_debug_objfile_backlink;
18943
18944   return objfile;
18945 }
18946
18947 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
18948    (CU_HEADERP is unused in such case) or prepare a temporary copy at
18949    CU_HEADERP first.  */
18950
18951 static const struct comp_unit_head *
18952 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
18953                        struct dwarf2_per_cu_data *per_cu)
18954 {
18955   gdb_byte *info_ptr;
18956
18957   if (per_cu->cu)
18958     return &per_cu->cu->header;
18959
18960   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
18961
18962   memset (cu_headerp, 0, sizeof (*cu_headerp));
18963   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
18964
18965   return cu_headerp;
18966 }
18967
18968 /* Return the address size given in the compilation unit header for CU.  */
18969
18970 int
18971 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
18972 {
18973   struct comp_unit_head cu_header_local;
18974   const struct comp_unit_head *cu_headerp;
18975
18976   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
18977
18978   return cu_headerp->addr_size;
18979 }
18980
18981 /* Return the offset size given in the compilation unit header for CU.  */
18982
18983 int
18984 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
18985 {
18986   struct comp_unit_head cu_header_local;
18987   const struct comp_unit_head *cu_headerp;
18988
18989   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
18990
18991   return cu_headerp->offset_size;
18992 }
18993
18994 /* See its dwarf2loc.h declaration.  */
18995
18996 int
18997 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
18998 {
18999   struct comp_unit_head cu_header_local;
19000   const struct comp_unit_head *cu_headerp;
19001
19002   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19003
19004   if (cu_headerp->version == 2)
19005     return cu_headerp->addr_size;
19006   else
19007     return cu_headerp->offset_size;
19008 }
19009
19010 /* Return the text offset of the CU.  The returned offset comes from
19011    this CU's objfile.  If this objfile came from a separate debuginfo
19012    file, then the offset may be different from the corresponding
19013    offset in the parent objfile.  */
19014
19015 CORE_ADDR
19016 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19017 {
19018   struct objfile *objfile = per_cu->objfile;
19019
19020   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19021 }
19022
19023 /* Locate the .debug_info compilation unit from CU's objfile which contains
19024    the DIE at OFFSET.  Raises an error on failure.  */
19025
19026 static struct dwarf2_per_cu_data *
19027 dwarf2_find_containing_comp_unit (sect_offset offset,
19028                                   unsigned int offset_in_dwz,
19029                                   struct objfile *objfile)
19030 {
19031   struct dwarf2_per_cu_data *this_cu;
19032   int low, high;
19033   const sect_offset *cu_off;
19034
19035   low = 0;
19036   high = dwarf2_per_objfile->n_comp_units - 1;
19037   while (high > low)
19038     {
19039       struct dwarf2_per_cu_data *mid_cu;
19040       int mid = low + (high - low) / 2;
19041
19042       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19043       cu_off = &mid_cu->offset;
19044       if (mid_cu->is_dwz > offset_in_dwz
19045           || (mid_cu->is_dwz == offset_in_dwz
19046               && cu_off->sect_off >= offset.sect_off))
19047         high = mid;
19048       else
19049         low = mid + 1;
19050     }
19051   gdb_assert (low == high);
19052   this_cu = dwarf2_per_objfile->all_comp_units[low];
19053   cu_off = &this_cu->offset;
19054   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19055     {
19056       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19057         error (_("Dwarf Error: could not find partial DIE containing "
19058                "offset 0x%lx [in module %s]"),
19059                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19060
19061       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19062                   <= offset.sect_off);
19063       return dwarf2_per_objfile->all_comp_units[low-1];
19064     }
19065   else
19066     {
19067       this_cu = dwarf2_per_objfile->all_comp_units[low];
19068       if (low == dwarf2_per_objfile->n_comp_units - 1
19069           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19070         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19071       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19072       return this_cu;
19073     }
19074 }
19075
19076 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19077
19078 static void
19079 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19080 {
19081   memset (cu, 0, sizeof (*cu));
19082   per_cu->cu = cu;
19083   cu->per_cu = per_cu;
19084   cu->objfile = per_cu->objfile;
19085   obstack_init (&cu->comp_unit_obstack);
19086 }
19087
19088 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19089
19090 static void
19091 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19092                        enum language pretend_language)
19093 {
19094   struct attribute *attr;
19095
19096   /* Set the language we're debugging.  */
19097   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19098   if (attr)
19099     set_cu_language (DW_UNSND (attr), cu);
19100   else
19101     {
19102       cu->language = pretend_language;
19103       cu->language_defn = language_def (cu->language);
19104     }
19105
19106   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19107   if (attr)
19108     cu->producer = DW_STRING (attr);
19109 }
19110
19111 /* Release one cached compilation unit, CU.  We unlink it from the tree
19112    of compilation units, but we don't remove it from the read_in_chain;
19113    the caller is responsible for that.
19114    NOTE: DATA is a void * because this function is also used as a
19115    cleanup routine.  */
19116
19117 static void
19118 free_heap_comp_unit (void *data)
19119 {
19120   struct dwarf2_cu *cu = data;
19121
19122   gdb_assert (cu->per_cu != NULL);
19123   cu->per_cu->cu = NULL;
19124   cu->per_cu = NULL;
19125
19126   obstack_free (&cu->comp_unit_obstack, NULL);
19127
19128   xfree (cu);
19129 }
19130
19131 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19132    when we're finished with it.  We can't free the pointer itself, but be
19133    sure to unlink it from the cache.  Also release any associated storage.  */
19134
19135 static void
19136 free_stack_comp_unit (void *data)
19137 {
19138   struct dwarf2_cu *cu = data;
19139
19140   gdb_assert (cu->per_cu != NULL);
19141   cu->per_cu->cu = NULL;
19142   cu->per_cu = NULL;
19143
19144   obstack_free (&cu->comp_unit_obstack, NULL);
19145   cu->partial_dies = NULL;
19146 }
19147
19148 /* Free all cached compilation units.  */
19149
19150 static void
19151 free_cached_comp_units (void *data)
19152 {
19153   struct dwarf2_per_cu_data *per_cu, **last_chain;
19154
19155   per_cu = dwarf2_per_objfile->read_in_chain;
19156   last_chain = &dwarf2_per_objfile->read_in_chain;
19157   while (per_cu != NULL)
19158     {
19159       struct dwarf2_per_cu_data *next_cu;
19160
19161       next_cu = per_cu->cu->read_in_chain;
19162
19163       free_heap_comp_unit (per_cu->cu);
19164       *last_chain = next_cu;
19165
19166       per_cu = next_cu;
19167     }
19168 }
19169
19170 /* Increase the age counter on each cached compilation unit, and free
19171    any that are too old.  */
19172
19173 static void
19174 age_cached_comp_units (void)
19175 {
19176   struct dwarf2_per_cu_data *per_cu, **last_chain;
19177
19178   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19179   per_cu = dwarf2_per_objfile->read_in_chain;
19180   while (per_cu != NULL)
19181     {
19182       per_cu->cu->last_used ++;
19183       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19184         dwarf2_mark (per_cu->cu);
19185       per_cu = per_cu->cu->read_in_chain;
19186     }
19187
19188   per_cu = dwarf2_per_objfile->read_in_chain;
19189   last_chain = &dwarf2_per_objfile->read_in_chain;
19190   while (per_cu != NULL)
19191     {
19192       struct dwarf2_per_cu_data *next_cu;
19193
19194       next_cu = per_cu->cu->read_in_chain;
19195
19196       if (!per_cu->cu->mark)
19197         {
19198           free_heap_comp_unit (per_cu->cu);
19199           *last_chain = next_cu;
19200         }
19201       else
19202         last_chain = &per_cu->cu->read_in_chain;
19203
19204       per_cu = next_cu;
19205     }
19206 }
19207
19208 /* Remove a single compilation unit from the cache.  */
19209
19210 static void
19211 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19212 {
19213   struct dwarf2_per_cu_data *per_cu, **last_chain;
19214
19215   per_cu = dwarf2_per_objfile->read_in_chain;
19216   last_chain = &dwarf2_per_objfile->read_in_chain;
19217   while (per_cu != NULL)
19218     {
19219       struct dwarf2_per_cu_data *next_cu;
19220
19221       next_cu = per_cu->cu->read_in_chain;
19222
19223       if (per_cu == target_per_cu)
19224         {
19225           free_heap_comp_unit (per_cu->cu);
19226           per_cu->cu = NULL;
19227           *last_chain = next_cu;
19228           break;
19229         }
19230       else
19231         last_chain = &per_cu->cu->read_in_chain;
19232
19233       per_cu = next_cu;
19234     }
19235 }
19236
19237 /* Release all extra memory associated with OBJFILE.  */
19238
19239 void
19240 dwarf2_free_objfile (struct objfile *objfile)
19241 {
19242   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19243
19244   if (dwarf2_per_objfile == NULL)
19245     return;
19246
19247   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19248   free_cached_comp_units (NULL);
19249
19250   if (dwarf2_per_objfile->quick_file_names_table)
19251     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19252
19253   /* Everything else should be on the objfile obstack.  */
19254 }
19255
19256 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19257    We store these in a hash table separate from the DIEs, and preserve them
19258    when the DIEs are flushed out of cache.
19259
19260    The CU "per_cu" pointer is needed because offset alone is not enough to
19261    uniquely identify the type.  A file may have multiple .debug_types sections,
19262    or the type may come from a DWO file.  We have to use something in
19263    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
19264    routine, get_die_type_at_offset, from outside this file, and thus won't
19265    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
19266    of the objfile.  */
19267
19268 struct dwarf2_per_cu_offset_and_type
19269 {
19270   const struct dwarf2_per_cu_data *per_cu;
19271   sect_offset offset;
19272   struct type *type;
19273 };
19274
19275 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19276
19277 static hashval_t
19278 per_cu_offset_and_type_hash (const void *item)
19279 {
19280   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19281
19282   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19283 }
19284
19285 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19286
19287 static int
19288 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19289 {
19290   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19291   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19292
19293   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19294           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19295 }
19296
19297 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19298    table if necessary.  For convenience, return TYPE.
19299
19300    The DIEs reading must have careful ordering to:
19301     * Not cause infite loops trying to read in DIEs as a prerequisite for
19302       reading current DIE.
19303     * Not trying to dereference contents of still incompletely read in types
19304       while reading in other DIEs.
19305     * Enable referencing still incompletely read in types just by a pointer to
19306       the type without accessing its fields.
19307
19308    Therefore caller should follow these rules:
19309      * Try to fetch any prerequisite types we may need to build this DIE type
19310        before building the type and calling set_die_type.
19311      * After building type call set_die_type for current DIE as soon as
19312        possible before fetching more types to complete the current type.
19313      * Make the type as complete as possible before fetching more types.  */
19314
19315 static struct type *
19316 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19317 {
19318   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19319   struct objfile *objfile = cu->objfile;
19320
19321   /* For Ada types, make sure that the gnat-specific data is always
19322      initialized (if not already set).  There are a few types where
19323      we should not be doing so, because the type-specific area is
19324      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19325      where the type-specific area is used to store the floatformat).
19326      But this is not a problem, because the gnat-specific information
19327      is actually not needed for these types.  */
19328   if (need_gnat_info (cu)
19329       && TYPE_CODE (type) != TYPE_CODE_FUNC
19330       && TYPE_CODE (type) != TYPE_CODE_FLT
19331       && !HAVE_GNAT_AUX_INFO (type))
19332     INIT_GNAT_SPECIFIC (type);
19333
19334   if (dwarf2_per_objfile->die_type_hash == NULL)
19335     {
19336       dwarf2_per_objfile->die_type_hash =
19337         htab_create_alloc_ex (127,
19338                               per_cu_offset_and_type_hash,
19339                               per_cu_offset_and_type_eq,
19340                               NULL,
19341                               &objfile->objfile_obstack,
19342                               hashtab_obstack_allocate,
19343                               dummy_obstack_deallocate);
19344     }
19345
19346   ofs.per_cu = cu->per_cu;
19347   ofs.offset = die->offset;
19348   ofs.type = type;
19349   slot = (struct dwarf2_per_cu_offset_and_type **)
19350     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19351   if (*slot)
19352     complaint (&symfile_complaints,
19353                _("A problem internal to GDB: DIE 0x%x has type already set"),
19354                die->offset.sect_off);
19355   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19356   **slot = ofs;
19357   return type;
19358 }
19359
19360 /* Look up the type for the die at OFFSET in the appropriate type_hash
19361    table, or return NULL if the die does not have a saved type.  */
19362
19363 static struct type *
19364 get_die_type_at_offset (sect_offset offset,
19365                         struct dwarf2_per_cu_data *per_cu)
19366 {
19367   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19368
19369   if (dwarf2_per_objfile->die_type_hash == NULL)
19370     return NULL;
19371
19372   ofs.per_cu = per_cu;
19373   ofs.offset = offset;
19374   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19375   if (slot)
19376     return slot->type;
19377   else
19378     return NULL;
19379 }
19380
19381 /* Look up the type for DIE in the appropriate type_hash table,
19382    or return NULL if DIE does not have a saved type.  */
19383
19384 static struct type *
19385 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19386 {
19387   return get_die_type_at_offset (die->offset, cu->per_cu);
19388 }
19389
19390 /* Add a dependence relationship from CU to REF_PER_CU.  */
19391
19392 static void
19393 dwarf2_add_dependence (struct dwarf2_cu *cu,
19394                        struct dwarf2_per_cu_data *ref_per_cu)
19395 {
19396   void **slot;
19397
19398   if (cu->dependencies == NULL)
19399     cu->dependencies
19400       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19401                               NULL, &cu->comp_unit_obstack,
19402                               hashtab_obstack_allocate,
19403                               dummy_obstack_deallocate);
19404
19405   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19406   if (*slot == NULL)
19407     *slot = ref_per_cu;
19408 }
19409
19410 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19411    Set the mark field in every compilation unit in the
19412    cache that we must keep because we are keeping CU.  */
19413
19414 static int
19415 dwarf2_mark_helper (void **slot, void *data)
19416 {
19417   struct dwarf2_per_cu_data *per_cu;
19418
19419   per_cu = (struct dwarf2_per_cu_data *) *slot;
19420
19421   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19422      reading of the chain.  As such dependencies remain valid it is not much
19423      useful to track and undo them during QUIT cleanups.  */
19424   if (per_cu->cu == NULL)
19425     return 1;
19426
19427   if (per_cu->cu->mark)
19428     return 1;
19429   per_cu->cu->mark = 1;
19430
19431   if (per_cu->cu->dependencies != NULL)
19432     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19433
19434   return 1;
19435 }
19436
19437 /* Set the mark field in CU and in every other compilation unit in the
19438    cache that we must keep because we are keeping CU.  */
19439
19440 static void
19441 dwarf2_mark (struct dwarf2_cu *cu)
19442 {
19443   if (cu->mark)
19444     return;
19445   cu->mark = 1;
19446   if (cu->dependencies != NULL)
19447     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19448 }
19449
19450 static void
19451 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19452 {
19453   while (per_cu)
19454     {
19455       per_cu->cu->mark = 0;
19456       per_cu = per_cu->cu->read_in_chain;
19457     }
19458 }
19459
19460 /* Trivial hash function for partial_die_info: the hash value of a DIE
19461    is its offset in .debug_info for this objfile.  */
19462
19463 static hashval_t
19464 partial_die_hash (const void *item)
19465 {
19466   const struct partial_die_info *part_die = item;
19467
19468   return part_die->offset.sect_off;
19469 }
19470
19471 /* Trivial comparison function for partial_die_info structures: two DIEs
19472    are equal if they have the same offset.  */
19473
19474 static int
19475 partial_die_eq (const void *item_lhs, const void *item_rhs)
19476 {
19477   const struct partial_die_info *part_die_lhs = item_lhs;
19478   const struct partial_die_info *part_die_rhs = item_rhs;
19479
19480   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19481 }
19482
19483 static struct cmd_list_element *set_dwarf2_cmdlist;
19484 static struct cmd_list_element *show_dwarf2_cmdlist;
19485
19486 static void
19487 set_dwarf2_cmd (char *args, int from_tty)
19488 {
19489   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19490 }
19491
19492 static void
19493 show_dwarf2_cmd (char *args, int from_tty)
19494 {
19495   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19496 }
19497
19498 /* Free data associated with OBJFILE, if necessary.  */
19499
19500 static void
19501 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19502 {
19503   struct dwarf2_per_objfile *data = d;
19504   int ix;
19505
19506   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19507     VEC_free (dwarf2_per_cu_ptr,
19508               dwarf2_per_objfile->all_comp_units[ix]->s.imported_symtabs);
19509
19510   VEC_free (dwarf2_section_info_def, data->types);
19511
19512   if (data->dwo_files)
19513     free_dwo_files (data->dwo_files, objfile);
19514
19515   if (data->dwz_file && data->dwz_file->dwz_bfd)
19516     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19517 }
19518
19519 \f
19520 /* The "save gdb-index" command.  */
19521
19522 /* The contents of the hash table we create when building the string
19523    table.  */
19524 struct strtab_entry
19525 {
19526   offset_type offset;
19527   const char *str;
19528 };
19529
19530 /* Hash function for a strtab_entry.
19531
19532    Function is used only during write_hash_table so no index format backward
19533    compatibility is needed.  */
19534
19535 static hashval_t
19536 hash_strtab_entry (const void *e)
19537 {
19538   const struct strtab_entry *entry = e;
19539   return mapped_index_string_hash (INT_MAX, entry->str);
19540 }
19541
19542 /* Equality function for a strtab_entry.  */
19543
19544 static int
19545 eq_strtab_entry (const void *a, const void *b)
19546 {
19547   const struct strtab_entry *ea = a;
19548   const struct strtab_entry *eb = b;
19549   return !strcmp (ea->str, eb->str);
19550 }
19551
19552 /* Create a strtab_entry hash table.  */
19553
19554 static htab_t
19555 create_strtab (void)
19556 {
19557   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19558                             xfree, xcalloc, xfree);
19559 }
19560
19561 /* Add a string to the constant pool.  Return the string's offset in
19562    host order.  */
19563
19564 static offset_type
19565 add_string (htab_t table, struct obstack *cpool, const char *str)
19566 {
19567   void **slot;
19568   struct strtab_entry entry;
19569   struct strtab_entry *result;
19570
19571   entry.str = str;
19572   slot = htab_find_slot (table, &entry, INSERT);
19573   if (*slot)
19574     result = *slot;
19575   else
19576     {
19577       result = XNEW (struct strtab_entry);
19578       result->offset = obstack_object_size (cpool);
19579       result->str = str;
19580       obstack_grow_str0 (cpool, str);
19581       *slot = result;
19582     }
19583   return result->offset;
19584 }
19585
19586 /* An entry in the symbol table.  */
19587 struct symtab_index_entry
19588 {
19589   /* The name of the symbol.  */
19590   const char *name;
19591   /* The offset of the name in the constant pool.  */
19592   offset_type index_offset;
19593   /* A sorted vector of the indices of all the CUs that hold an object
19594      of this name.  */
19595   VEC (offset_type) *cu_indices;
19596 };
19597
19598 /* The symbol table.  This is a power-of-2-sized hash table.  */
19599 struct mapped_symtab
19600 {
19601   offset_type n_elements;
19602   offset_type size;
19603   struct symtab_index_entry **data;
19604 };
19605
19606 /* Hash function for a symtab_index_entry.  */
19607
19608 static hashval_t
19609 hash_symtab_entry (const void *e)
19610 {
19611   const struct symtab_index_entry *entry = e;
19612   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19613                          sizeof (offset_type) * VEC_length (offset_type,
19614                                                             entry->cu_indices),
19615                          0);
19616 }
19617
19618 /* Equality function for a symtab_index_entry.  */
19619
19620 static int
19621 eq_symtab_entry (const void *a, const void *b)
19622 {
19623   const struct symtab_index_entry *ea = a;
19624   const struct symtab_index_entry *eb = b;
19625   int len = VEC_length (offset_type, ea->cu_indices);
19626   if (len != VEC_length (offset_type, eb->cu_indices))
19627     return 0;
19628   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19629                   VEC_address (offset_type, eb->cu_indices),
19630                   sizeof (offset_type) * len);
19631 }
19632
19633 /* Destroy a symtab_index_entry.  */
19634
19635 static void
19636 delete_symtab_entry (void *p)
19637 {
19638   struct symtab_index_entry *entry = p;
19639   VEC_free (offset_type, entry->cu_indices);
19640   xfree (entry);
19641 }
19642
19643 /* Create a hash table holding symtab_index_entry objects.  */
19644
19645 static htab_t
19646 create_symbol_hash_table (void)
19647 {
19648   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19649                             delete_symtab_entry, xcalloc, xfree);
19650 }
19651
19652 /* Create a new mapped symtab object.  */
19653
19654 static struct mapped_symtab *
19655 create_mapped_symtab (void)
19656 {
19657   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
19658   symtab->n_elements = 0;
19659   symtab->size = 1024;
19660   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19661   return symtab;
19662 }
19663
19664 /* Destroy a mapped_symtab.  */
19665
19666 static void
19667 cleanup_mapped_symtab (void *p)
19668 {
19669   struct mapped_symtab *symtab = p;
19670   /* The contents of the array are freed when the other hash table is
19671      destroyed.  */
19672   xfree (symtab->data);
19673   xfree (symtab);
19674 }
19675
19676 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
19677    the slot.
19678    
19679    Function is used only during write_hash_table so no index format backward
19680    compatibility is needed.  */
19681
19682 static struct symtab_index_entry **
19683 find_slot (struct mapped_symtab *symtab, const char *name)
19684 {
19685   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
19686
19687   index = hash & (symtab->size - 1);
19688   step = ((hash * 17) & (symtab->size - 1)) | 1;
19689
19690   for (;;)
19691     {
19692       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
19693         return &symtab->data[index];
19694       index = (index + step) & (symtab->size - 1);
19695     }
19696 }
19697
19698 /* Expand SYMTAB's hash table.  */
19699
19700 static void
19701 hash_expand (struct mapped_symtab *symtab)
19702 {
19703   offset_type old_size = symtab->size;
19704   offset_type i;
19705   struct symtab_index_entry **old_entries = symtab->data;
19706
19707   symtab->size *= 2;
19708   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19709
19710   for (i = 0; i < old_size; ++i)
19711     {
19712       if (old_entries[i])
19713         {
19714           struct symtab_index_entry **slot = find_slot (symtab,
19715                                                         old_entries[i]->name);
19716           *slot = old_entries[i];
19717         }
19718     }
19719
19720   xfree (old_entries);
19721 }
19722
19723 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
19724    CU_INDEX is the index of the CU in which the symbol appears.
19725    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
19726
19727 static void
19728 add_index_entry (struct mapped_symtab *symtab, const char *name,
19729                  int is_static, gdb_index_symbol_kind kind,
19730                  offset_type cu_index)
19731 {
19732   struct symtab_index_entry **slot;
19733   offset_type cu_index_and_attrs;
19734
19735   ++symtab->n_elements;
19736   if (4 * symtab->n_elements / 3 >= symtab->size)
19737     hash_expand (symtab);
19738
19739   slot = find_slot (symtab, name);
19740   if (!*slot)
19741     {
19742       *slot = XNEW (struct symtab_index_entry);
19743       (*slot)->name = name;
19744       /* index_offset is set later.  */
19745       (*slot)->cu_indices = NULL;
19746     }
19747
19748   cu_index_and_attrs = 0;
19749   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
19750   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
19751   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
19752
19753   /* We don't want to record an index value twice as we want to avoid the
19754      duplication.
19755      We process all global symbols and then all static symbols
19756      (which would allow us to avoid the duplication by only having to check
19757      the last entry pushed), but a symbol could have multiple kinds in one CU.
19758      To keep things simple we don't worry about the duplication here and
19759      sort and uniqufy the list after we've processed all symbols.  */
19760   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
19761 }
19762
19763 /* qsort helper routine for uniquify_cu_indices.  */
19764
19765 static int
19766 offset_type_compare (const void *ap, const void *bp)
19767 {
19768   offset_type a = *(offset_type *) ap;
19769   offset_type b = *(offset_type *) bp;
19770
19771   return (a > b) - (b > a);
19772 }
19773
19774 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
19775
19776 static void
19777 uniquify_cu_indices (struct mapped_symtab *symtab)
19778 {
19779   int i;
19780
19781   for (i = 0; i < symtab->size; ++i)
19782     {
19783       struct symtab_index_entry *entry = symtab->data[i];
19784
19785       if (entry
19786           && entry->cu_indices != NULL)
19787         {
19788           unsigned int next_to_insert, next_to_check;
19789           offset_type last_value;
19790
19791           qsort (VEC_address (offset_type, entry->cu_indices),
19792                  VEC_length (offset_type, entry->cu_indices),
19793                  sizeof (offset_type), offset_type_compare);
19794
19795           last_value = VEC_index (offset_type, entry->cu_indices, 0);
19796           next_to_insert = 1;
19797           for (next_to_check = 1;
19798                next_to_check < VEC_length (offset_type, entry->cu_indices);
19799                ++next_to_check)
19800             {
19801               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
19802                   != last_value)
19803                 {
19804                   last_value = VEC_index (offset_type, entry->cu_indices,
19805                                           next_to_check);
19806                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
19807                                last_value);
19808                   ++next_to_insert;
19809                 }
19810             }
19811           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
19812         }
19813     }
19814 }
19815
19816 /* Add a vector of indices to the constant pool.  */
19817
19818 static offset_type
19819 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
19820                       struct symtab_index_entry *entry)
19821 {
19822   void **slot;
19823
19824   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
19825   if (!*slot)
19826     {
19827       offset_type len = VEC_length (offset_type, entry->cu_indices);
19828       offset_type val = MAYBE_SWAP (len);
19829       offset_type iter;
19830       int i;
19831
19832       *slot = entry;
19833       entry->index_offset = obstack_object_size (cpool);
19834
19835       obstack_grow (cpool, &val, sizeof (val));
19836       for (i = 0;
19837            VEC_iterate (offset_type, entry->cu_indices, i, iter);
19838            ++i)
19839         {
19840           val = MAYBE_SWAP (iter);
19841           obstack_grow (cpool, &val, sizeof (val));
19842         }
19843     }
19844   else
19845     {
19846       struct symtab_index_entry *old_entry = *slot;
19847       entry->index_offset = old_entry->index_offset;
19848       entry = old_entry;
19849     }
19850   return entry->index_offset;
19851 }
19852
19853 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
19854    constant pool entries going into the obstack CPOOL.  */
19855
19856 static void
19857 write_hash_table (struct mapped_symtab *symtab,
19858                   struct obstack *output, struct obstack *cpool)
19859 {
19860   offset_type i;
19861   htab_t symbol_hash_table;
19862   htab_t str_table;
19863
19864   symbol_hash_table = create_symbol_hash_table ();
19865   str_table = create_strtab ();
19866
19867   /* We add all the index vectors to the constant pool first, to
19868      ensure alignment is ok.  */
19869   for (i = 0; i < symtab->size; ++i)
19870     {
19871       if (symtab->data[i])
19872         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
19873     }
19874
19875   /* Now write out the hash table.  */
19876   for (i = 0; i < symtab->size; ++i)
19877     {
19878       offset_type str_off, vec_off;
19879
19880       if (symtab->data[i])
19881         {
19882           str_off = add_string (str_table, cpool, symtab->data[i]->name);
19883           vec_off = symtab->data[i]->index_offset;
19884         }
19885       else
19886         {
19887           /* While 0 is a valid constant pool index, it is not valid
19888              to have 0 for both offsets.  */
19889           str_off = 0;
19890           vec_off = 0;
19891         }
19892
19893       str_off = MAYBE_SWAP (str_off);
19894       vec_off = MAYBE_SWAP (vec_off);
19895
19896       obstack_grow (output, &str_off, sizeof (str_off));
19897       obstack_grow (output, &vec_off, sizeof (vec_off));
19898     }
19899
19900   htab_delete (str_table);
19901   htab_delete (symbol_hash_table);
19902 }
19903
19904 /* Struct to map psymtab to CU index in the index file.  */
19905 struct psymtab_cu_index_map
19906 {
19907   struct partial_symtab *psymtab;
19908   unsigned int cu_index;
19909 };
19910
19911 static hashval_t
19912 hash_psymtab_cu_index (const void *item)
19913 {
19914   const struct psymtab_cu_index_map *map = item;
19915
19916   return htab_hash_pointer (map->psymtab);
19917 }
19918
19919 static int
19920 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
19921 {
19922   const struct psymtab_cu_index_map *lhs = item_lhs;
19923   const struct psymtab_cu_index_map *rhs = item_rhs;
19924
19925   return lhs->psymtab == rhs->psymtab;
19926 }
19927
19928 /* Helper struct for building the address table.  */
19929 struct addrmap_index_data
19930 {
19931   struct objfile *objfile;
19932   struct obstack *addr_obstack;
19933   htab_t cu_index_htab;
19934
19935   /* Non-zero if the previous_* fields are valid.
19936      We can't write an entry until we see the next entry (since it is only then
19937      that we know the end of the entry).  */
19938   int previous_valid;
19939   /* Index of the CU in the table of all CUs in the index file.  */
19940   unsigned int previous_cu_index;
19941   /* Start address of the CU.  */
19942   CORE_ADDR previous_cu_start;
19943 };
19944
19945 /* Write an address entry to OBSTACK.  */
19946
19947 static void
19948 add_address_entry (struct objfile *objfile, struct obstack *obstack,
19949                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
19950 {
19951   offset_type cu_index_to_write;
19952   char addr[8];
19953   CORE_ADDR baseaddr;
19954
19955   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19956
19957   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
19958   obstack_grow (obstack, addr, 8);
19959   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
19960   obstack_grow (obstack, addr, 8);
19961   cu_index_to_write = MAYBE_SWAP (cu_index);
19962   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
19963 }
19964
19965 /* Worker function for traversing an addrmap to build the address table.  */
19966
19967 static int
19968 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
19969 {
19970   struct addrmap_index_data *data = datap;
19971   struct partial_symtab *pst = obj;
19972
19973   if (data->previous_valid)
19974     add_address_entry (data->objfile, data->addr_obstack,
19975                        data->previous_cu_start, start_addr,
19976                        data->previous_cu_index);
19977
19978   data->previous_cu_start = start_addr;
19979   if (pst != NULL)
19980     {
19981       struct psymtab_cu_index_map find_map, *map;
19982       find_map.psymtab = pst;
19983       map = htab_find (data->cu_index_htab, &find_map);
19984       gdb_assert (map != NULL);
19985       data->previous_cu_index = map->cu_index;
19986       data->previous_valid = 1;
19987     }
19988   else
19989       data->previous_valid = 0;
19990
19991   return 0;
19992 }
19993
19994 /* Write OBJFILE's address map to OBSTACK.
19995    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
19996    in the index file.  */
19997
19998 static void
19999 write_address_map (struct objfile *objfile, struct obstack *obstack,
20000                    htab_t cu_index_htab)
20001 {
20002   struct addrmap_index_data addrmap_index_data;
20003
20004   /* When writing the address table, we have to cope with the fact that
20005      the addrmap iterator only provides the start of a region; we have to
20006      wait until the next invocation to get the start of the next region.  */
20007
20008   addrmap_index_data.objfile = objfile;
20009   addrmap_index_data.addr_obstack = obstack;
20010   addrmap_index_data.cu_index_htab = cu_index_htab;
20011   addrmap_index_data.previous_valid = 0;
20012
20013   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20014                    &addrmap_index_data);
20015
20016   /* It's highly unlikely the last entry (end address = 0xff...ff)
20017      is valid, but we should still handle it.
20018      The end address is recorded as the start of the next region, but that
20019      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20020      anyway.  */
20021   if (addrmap_index_data.previous_valid)
20022     add_address_entry (objfile, obstack,
20023                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20024                        addrmap_index_data.previous_cu_index);
20025 }
20026
20027 /* Return the symbol kind of PSYM.  */
20028
20029 static gdb_index_symbol_kind
20030 symbol_kind (struct partial_symbol *psym)
20031 {
20032   domain_enum domain = PSYMBOL_DOMAIN (psym);
20033   enum address_class aclass = PSYMBOL_CLASS (psym);
20034
20035   switch (domain)
20036     {
20037     case VAR_DOMAIN:
20038       switch (aclass)
20039         {
20040         case LOC_BLOCK:
20041           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20042         case LOC_TYPEDEF:
20043           return GDB_INDEX_SYMBOL_KIND_TYPE;
20044         case LOC_COMPUTED:
20045         case LOC_CONST_BYTES:
20046         case LOC_OPTIMIZED_OUT:
20047         case LOC_STATIC:
20048           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20049         case LOC_CONST:
20050           /* Note: It's currently impossible to recognize psyms as enum values
20051              short of reading the type info.  For now punt.  */
20052           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20053         default:
20054           /* There are other LOC_FOO values that one might want to classify
20055              as variables, but dwarf2read.c doesn't currently use them.  */
20056           return GDB_INDEX_SYMBOL_KIND_OTHER;
20057         }
20058     case STRUCT_DOMAIN:
20059       return GDB_INDEX_SYMBOL_KIND_TYPE;
20060     default:
20061       return GDB_INDEX_SYMBOL_KIND_OTHER;
20062     }
20063 }
20064
20065 /* Add a list of partial symbols to SYMTAB.  */
20066
20067 static void
20068 write_psymbols (struct mapped_symtab *symtab,
20069                 htab_t psyms_seen,
20070                 struct partial_symbol **psymp,
20071                 int count,
20072                 offset_type cu_index,
20073                 int is_static)
20074 {
20075   for (; count-- > 0; ++psymp)
20076     {
20077       struct partial_symbol *psym = *psymp;
20078       void **slot;
20079
20080       if (SYMBOL_LANGUAGE (psym) == language_ada)
20081         error (_("Ada is not currently supported by the index"));
20082
20083       /* Only add a given psymbol once.  */
20084       slot = htab_find_slot (psyms_seen, psym, INSERT);
20085       if (!*slot)
20086         {
20087           gdb_index_symbol_kind kind = symbol_kind (psym);
20088
20089           *slot = psym;
20090           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20091                            is_static, kind, cu_index);
20092         }
20093     }
20094 }
20095
20096 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20097    exception if there is an error.  */
20098
20099 static void
20100 write_obstack (FILE *file, struct obstack *obstack)
20101 {
20102   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20103               file)
20104       != obstack_object_size (obstack))
20105     error (_("couldn't data write to file"));
20106 }
20107
20108 /* Unlink a file if the argument is not NULL.  */
20109
20110 static void
20111 unlink_if_set (void *p)
20112 {
20113   char **filename = p;
20114   if (*filename)
20115     unlink (*filename);
20116 }
20117
20118 /* A helper struct used when iterating over debug_types.  */
20119 struct signatured_type_index_data
20120 {
20121   struct objfile *objfile;
20122   struct mapped_symtab *symtab;
20123   struct obstack *types_list;
20124   htab_t psyms_seen;
20125   int cu_index;
20126 };
20127
20128 /* A helper function that writes a single signatured_type to an
20129    obstack.  */
20130
20131 static int
20132 write_one_signatured_type (void **slot, void *d)
20133 {
20134   struct signatured_type_index_data *info = d;
20135   struct signatured_type *entry = (struct signatured_type *) *slot;
20136   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
20137   struct partial_symtab *psymtab = per_cu->v.psymtab;
20138   gdb_byte val[8];
20139
20140   write_psymbols (info->symtab,
20141                   info->psyms_seen,
20142                   info->objfile->global_psymbols.list
20143                   + psymtab->globals_offset,
20144                   psymtab->n_global_syms, info->cu_index,
20145                   0);
20146   write_psymbols (info->symtab,
20147                   info->psyms_seen,
20148                   info->objfile->static_psymbols.list
20149                   + psymtab->statics_offset,
20150                   psymtab->n_static_syms, info->cu_index,
20151                   1);
20152
20153   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20154                           entry->per_cu.offset.sect_off);
20155   obstack_grow (info->types_list, val, 8);
20156   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20157                           entry->type_offset_in_tu.cu_off);
20158   obstack_grow (info->types_list, val, 8);
20159   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20160   obstack_grow (info->types_list, val, 8);
20161
20162   ++info->cu_index;
20163
20164   return 1;
20165 }
20166
20167 /* Recurse into all "included" dependencies and write their symbols as
20168    if they appeared in this psymtab.  */
20169
20170 static void
20171 recursively_write_psymbols (struct objfile *objfile,
20172                             struct partial_symtab *psymtab,
20173                             struct mapped_symtab *symtab,
20174                             htab_t psyms_seen,
20175                             offset_type cu_index)
20176 {
20177   int i;
20178
20179   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20180     if (psymtab->dependencies[i]->user != NULL)
20181       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20182                                   symtab, psyms_seen, cu_index);
20183
20184   write_psymbols (symtab,
20185                   psyms_seen,
20186                   objfile->global_psymbols.list + psymtab->globals_offset,
20187                   psymtab->n_global_syms, cu_index,
20188                   0);
20189   write_psymbols (symtab,
20190                   psyms_seen,
20191                   objfile->static_psymbols.list + psymtab->statics_offset,
20192                   psymtab->n_static_syms, cu_index,
20193                   1);
20194 }
20195
20196 /* Create an index file for OBJFILE in the directory DIR.  */
20197
20198 static void
20199 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20200 {
20201   struct cleanup *cleanup;
20202   char *filename, *cleanup_filename;
20203   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20204   struct obstack cu_list, types_cu_list;
20205   int i;
20206   FILE *out_file;
20207   struct mapped_symtab *symtab;
20208   offset_type val, size_of_contents, total_len;
20209   struct stat st;
20210   htab_t psyms_seen;
20211   htab_t cu_index_htab;
20212   struct psymtab_cu_index_map *psymtab_cu_index_map;
20213
20214   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20215     return;
20216
20217   if (dwarf2_per_objfile->using_index)
20218     error (_("Cannot use an index to create the index"));
20219
20220   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20221     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20222
20223   if (stat (objfile->name, &st) < 0)
20224     perror_with_name (objfile->name);
20225
20226   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20227                      INDEX_SUFFIX, (char *) NULL);
20228   cleanup = make_cleanup (xfree, filename);
20229
20230   out_file = fopen (filename, "wb");
20231   if (!out_file)
20232     error (_("Can't open `%s' for writing"), filename);
20233
20234   cleanup_filename = filename;
20235   make_cleanup (unlink_if_set, &cleanup_filename);
20236
20237   symtab = create_mapped_symtab ();
20238   make_cleanup (cleanup_mapped_symtab, symtab);
20239
20240   obstack_init (&addr_obstack);
20241   make_cleanup_obstack_free (&addr_obstack);
20242
20243   obstack_init (&cu_list);
20244   make_cleanup_obstack_free (&cu_list);
20245
20246   obstack_init (&types_cu_list);
20247   make_cleanup_obstack_free (&types_cu_list);
20248
20249   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20250                                   NULL, xcalloc, xfree);
20251   make_cleanup_htab_delete (psyms_seen);
20252
20253   /* While we're scanning CU's create a table that maps a psymtab pointer
20254      (which is what addrmap records) to its index (which is what is recorded
20255      in the index file).  This will later be needed to write the address
20256      table.  */
20257   cu_index_htab = htab_create_alloc (100,
20258                                      hash_psymtab_cu_index,
20259                                      eq_psymtab_cu_index,
20260                                      NULL, xcalloc, xfree);
20261   make_cleanup_htab_delete (cu_index_htab);
20262   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20263     xmalloc (sizeof (struct psymtab_cu_index_map)
20264              * dwarf2_per_objfile->n_comp_units);
20265   make_cleanup (xfree, psymtab_cu_index_map);
20266
20267   /* The CU list is already sorted, so we don't need to do additional
20268      work here.  Also, the debug_types entries do not appear in
20269      all_comp_units, but only in their own hash table.  */
20270   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20271     {
20272       struct dwarf2_per_cu_data *per_cu
20273         = dwarf2_per_objfile->all_comp_units[i];
20274       struct partial_symtab *psymtab = per_cu->v.psymtab;
20275       gdb_byte val[8];
20276       struct psymtab_cu_index_map *map;
20277       void **slot;
20278
20279       if (psymtab->user == NULL)
20280         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20281
20282       map = &psymtab_cu_index_map[i];
20283       map->psymtab = psymtab;
20284       map->cu_index = i;
20285       slot = htab_find_slot (cu_index_htab, map, INSERT);
20286       gdb_assert (slot != NULL);
20287       gdb_assert (*slot == NULL);
20288       *slot = map;
20289
20290       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20291                               per_cu->offset.sect_off);
20292       obstack_grow (&cu_list, val, 8);
20293       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20294       obstack_grow (&cu_list, val, 8);
20295     }
20296
20297   /* Dump the address map.  */
20298   write_address_map (objfile, &addr_obstack, cu_index_htab);
20299
20300   /* Write out the .debug_type entries, if any.  */
20301   if (dwarf2_per_objfile->signatured_types)
20302     {
20303       struct signatured_type_index_data sig_data;
20304
20305       sig_data.objfile = objfile;
20306       sig_data.symtab = symtab;
20307       sig_data.types_list = &types_cu_list;
20308       sig_data.psyms_seen = psyms_seen;
20309       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20310       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20311                               write_one_signatured_type, &sig_data);
20312     }
20313
20314   /* Now that we've processed all symbols we can shrink their cu_indices
20315      lists.  */
20316   uniquify_cu_indices (symtab);
20317
20318   obstack_init (&constant_pool);
20319   make_cleanup_obstack_free (&constant_pool);
20320   obstack_init (&symtab_obstack);
20321   make_cleanup_obstack_free (&symtab_obstack);
20322   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20323
20324   obstack_init (&contents);
20325   make_cleanup_obstack_free (&contents);
20326   size_of_contents = 6 * sizeof (offset_type);
20327   total_len = size_of_contents;
20328
20329   /* The version number.  */
20330   val = MAYBE_SWAP (7);
20331   obstack_grow (&contents, &val, sizeof (val));
20332
20333   /* The offset of the CU list from the start of the file.  */
20334   val = MAYBE_SWAP (total_len);
20335   obstack_grow (&contents, &val, sizeof (val));
20336   total_len += obstack_object_size (&cu_list);
20337
20338   /* The offset of the types CU list from the start of the file.  */
20339   val = MAYBE_SWAP (total_len);
20340   obstack_grow (&contents, &val, sizeof (val));
20341   total_len += obstack_object_size (&types_cu_list);
20342
20343   /* The offset of the address table from the start of the file.  */
20344   val = MAYBE_SWAP (total_len);
20345   obstack_grow (&contents, &val, sizeof (val));
20346   total_len += obstack_object_size (&addr_obstack);
20347
20348   /* The offset of the symbol table from the start of the file.  */
20349   val = MAYBE_SWAP (total_len);
20350   obstack_grow (&contents, &val, sizeof (val));
20351   total_len += obstack_object_size (&symtab_obstack);
20352
20353   /* The offset of the constant pool from the start of the file.  */
20354   val = MAYBE_SWAP (total_len);
20355   obstack_grow (&contents, &val, sizeof (val));
20356   total_len += obstack_object_size (&constant_pool);
20357
20358   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20359
20360   write_obstack (out_file, &contents);
20361   write_obstack (out_file, &cu_list);
20362   write_obstack (out_file, &types_cu_list);
20363   write_obstack (out_file, &addr_obstack);
20364   write_obstack (out_file, &symtab_obstack);
20365   write_obstack (out_file, &constant_pool);
20366
20367   fclose (out_file);
20368
20369   /* We want to keep the file, so we set cleanup_filename to NULL
20370      here.  See unlink_if_set.  */
20371   cleanup_filename = NULL;
20372
20373   do_cleanups (cleanup);
20374 }
20375
20376 /* Implementation of the `save gdb-index' command.
20377    
20378    Note that the file format used by this command is documented in the
20379    GDB manual.  Any changes here must be documented there.  */
20380
20381 static void
20382 save_gdb_index_command (char *arg, int from_tty)
20383 {
20384   struct objfile *objfile;
20385
20386   if (!arg || !*arg)
20387     error (_("usage: save gdb-index DIRECTORY"));
20388
20389   ALL_OBJFILES (objfile)
20390   {
20391     struct stat st;
20392
20393     /* If the objfile does not correspond to an actual file, skip it.  */
20394     if (stat (objfile->name, &st) < 0)
20395       continue;
20396
20397     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20398     if (dwarf2_per_objfile)
20399       {
20400         volatile struct gdb_exception except;
20401
20402         TRY_CATCH (except, RETURN_MASK_ERROR)
20403           {
20404             write_psymtabs_to_index (objfile, arg);
20405           }
20406         if (except.reason < 0)
20407           exception_fprintf (gdb_stderr, except,
20408                              _("Error while writing index for `%s': "),
20409                              objfile->name);
20410       }
20411   }
20412 }
20413
20414 \f
20415
20416 int dwarf2_always_disassemble;
20417
20418 static void
20419 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20420                                 struct cmd_list_element *c, const char *value)
20421 {
20422   fprintf_filtered (file,
20423                     _("Whether to always disassemble "
20424                       "DWARF expressions is %s.\n"),
20425                     value);
20426 }
20427
20428 static void
20429 show_check_physname (struct ui_file *file, int from_tty,
20430                      struct cmd_list_element *c, const char *value)
20431 {
20432   fprintf_filtered (file,
20433                     _("Whether to check \"physname\" is %s.\n"),
20434                     value);
20435 }
20436
20437 void _initialize_dwarf2_read (void);
20438
20439 void
20440 _initialize_dwarf2_read (void)
20441 {
20442   struct cmd_list_element *c;
20443
20444   dwarf2_objfile_data_key
20445     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20446
20447   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20448 Set DWARF 2 specific variables.\n\
20449 Configure DWARF 2 variables such as the cache size"),
20450                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20451                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20452
20453   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20454 Show DWARF 2 specific variables\n\
20455 Show DWARF 2 variables such as the cache size"),
20456                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20457                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20458
20459   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20460                             &dwarf2_max_cache_age, _("\
20461 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20462 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20463 A higher limit means that cached compilation units will be stored\n\
20464 in memory longer, and more total memory will be used.  Zero disables\n\
20465 caching, which can slow down startup."),
20466                             NULL,
20467                             show_dwarf2_max_cache_age,
20468                             &set_dwarf2_cmdlist,
20469                             &show_dwarf2_cmdlist);
20470
20471   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20472                            &dwarf2_always_disassemble, _("\
20473 Set whether `info address' always disassembles DWARF expressions."), _("\
20474 Show whether `info address' always disassembles DWARF expressions."), _("\
20475 When enabled, DWARF expressions are always printed in an assembly-like\n\
20476 syntax.  When disabled, expressions will be printed in a more\n\
20477 conversational style, when possible."),
20478                            NULL,
20479                            show_dwarf2_always_disassemble,
20480                            &set_dwarf2_cmdlist,
20481                            &show_dwarf2_cmdlist);
20482
20483   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20484 Set debugging of the dwarf2 reader."), _("\
20485 Show debugging of the dwarf2 reader."), _("\
20486 When enabled, debugging messages are printed during dwarf2 reading\n\
20487 and symtab expansion."),
20488                             NULL,
20489                             NULL,
20490                             &setdebuglist, &showdebuglist);
20491
20492   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20493 Set debugging of the dwarf2 DIE reader."), _("\
20494 Show debugging of the dwarf2 DIE reader."), _("\
20495 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20496 The value is the maximum depth to print."),
20497                              NULL,
20498                              NULL,
20499                              &setdebuglist, &showdebuglist);
20500
20501   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20502 Set cross-checking of \"physname\" code against demangler."), _("\
20503 Show cross-checking of \"physname\" code against demangler."), _("\
20504 When enabled, GDB's internal \"physname\" code is checked against\n\
20505 the demangler."),
20506                            NULL, show_check_physname,
20507                            &setdebuglist, &showdebuglist);
20508
20509   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20510                            no_class, &use_deprecated_index_sections, _("\
20511 Set whether to use deprecated gdb_index sections."), _("\
20512 Show whether to use deprecated gdb_index sections."), _("\
20513 When enabled, deprecated .gdb_index sections are used anyway.\n\
20514 Normally they are ignored either because of a missing feature or\n\
20515 performance issue.\n\
20516 Warning: This option must be enabled before gdb reads the file."),
20517                            NULL,
20518                            NULL,
20519                            &setlist, &showlist);
20520
20521   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20522                _("\
20523 Save a gdb-index file.\n\
20524 Usage: save gdb-index DIRECTORY"),
20525                &save_cmdlist);
20526   set_cmd_completer (c, filename_completer);
20527 }