* dwarf2read.c (dwarf2_section_info): Add comment.
[platform/upstream/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72
73 #include <fcntl.h>
74 #include "gdb_string.h"
75 #include "gdb_assert.h"
76 #include <sys/types.h>
77
78 typedef struct symbol *symbolp;
79 DEF_VEC_P (symbolp);
80
81 /* When non-zero, print basic high level tracing messages.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 struct dwarf2_section_info
104 {
105   asection *asection;
106   /* Pointer to section data, only valid if readin.  */
107   const gdb_byte *buffer;
108   bfd_size_type size;
109   /* True if we have tried to read this section.  */
110   int readin;
111 };
112
113 typedef struct dwarf2_section_info dwarf2_section_info_def;
114 DEF_VEC_O (dwarf2_section_info_def);
115
116 /* All offsets in the index are of this type.  It must be
117    architecture-independent.  */
118 typedef uint32_t offset_type;
119
120 DEF_VEC_I (offset_type);
121
122 /* Ensure only legit values are used.  */
123 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
124   do { \
125     gdb_assert ((unsigned int) (value) <= 1); \
126     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
127   } while (0)
128
129 /* Ensure only legit values are used.  */
130 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
131   do { \
132     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
133                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
134     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
135   } while (0)
136
137 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
138 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
139   do { \
140     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
141     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
142   } while (0)
143
144 /* A description of the mapped index.  The file format is described in
145    a comment by the code that writes the index.  */
146 struct mapped_index
147 {
148   /* Index data format version.  */
149   int version;
150
151   /* The total length of the buffer.  */
152   off_t total_size;
153
154   /* A pointer to the address table data.  */
155   const gdb_byte *address_table;
156
157   /* Size of the address table data in bytes.  */
158   offset_type address_table_size;
159
160   /* The symbol table, implemented as a hash table.  */
161   const offset_type *symbol_table;
162
163   /* Size in slots, each slot is 2 offset_types.  */
164   offset_type symbol_table_slots;
165
166   /* A pointer to the constant pool.  */
167   const char *constant_pool;
168 };
169
170 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
171 DEF_VEC_P (dwarf2_per_cu_ptr);
172
173 /* Collection of data recorded per objfile.
174    This hangs off of dwarf2_objfile_data_key.  */
175
176 struct dwarf2_per_objfile
177 {
178   struct dwarf2_section_info info;
179   struct dwarf2_section_info abbrev;
180   struct dwarf2_section_info line;
181   struct dwarf2_section_info loc;
182   struct dwarf2_section_info macinfo;
183   struct dwarf2_section_info macro;
184   struct dwarf2_section_info str;
185   struct dwarf2_section_info ranges;
186   struct dwarf2_section_info addr;
187   struct dwarf2_section_info frame;
188   struct dwarf2_section_info eh_frame;
189   struct dwarf2_section_info gdb_index;
190
191   VEC (dwarf2_section_info_def) *types;
192
193   /* Back link.  */
194   struct objfile *objfile;
195
196   /* Table of all the compilation units.  This is used to locate
197      the target compilation unit of a particular reference.  */
198   struct dwarf2_per_cu_data **all_comp_units;
199
200   /* The number of compilation units in ALL_COMP_UNITS.  */
201   int n_comp_units;
202
203   /* The number of .debug_types-related CUs.  */
204   int n_type_units;
205
206   /* The .debug_types-related CUs (TUs).
207      This is stored in malloc space because we may realloc it.  */
208   struct signatured_type **all_type_units;
209
210   /* The number of entries in all_type_unit_groups.  */
211   int n_type_unit_groups;
212
213   /* Table of type unit groups.
214      This exists to make it easy to iterate over all CUs and TU groups.  */
215   struct type_unit_group **all_type_unit_groups;
216
217   /* Table of struct type_unit_group objects.
218      The hash key is the DW_AT_stmt_list value.  */
219   htab_t type_unit_groups;
220
221   /* A table mapping .debug_types signatures to its signatured_type entry.
222      This is NULL if the .debug_types section hasn't been read in yet.  */
223   htab_t signatured_types;
224
225   /* Type unit statistics, to see how well the scaling improvements
226      are doing.  */
227   struct tu_stats
228   {
229     int nr_uniq_abbrev_tables;
230     int nr_symtabs;
231     int nr_symtab_sharers;
232     int nr_stmt_less_type_units;
233   } tu_stats;
234
235   /* A chain of compilation units that are currently read in, so that
236      they can be freed later.  */
237   struct dwarf2_per_cu_data *read_in_chain;
238
239   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
240      This is NULL if the table hasn't been allocated yet.  */
241   htab_t dwo_files;
242
243   /* Non-zero if we've check for whether there is a DWP file.  */
244   int dwp_checked;
245
246   /* The DWP file if there is one, or NULL.  */
247   struct dwp_file *dwp_file;
248
249   /* The shared '.dwz' file, if one exists.  This is used when the
250      original data was compressed using 'dwz -m'.  */
251   struct dwz_file *dwz_file;
252
253   /* A flag indicating wether this objfile has a section loaded at a
254      VMA of 0.  */
255   int has_section_at_zero;
256
257   /* True if we are using the mapped index,
258      or we are faking it for OBJF_READNOW's sake.  */
259   unsigned char using_index;
260
261   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
262   struct mapped_index *index_table;
263
264   /* When using index_table, this keeps track of all quick_file_names entries.
265      TUs typically share line table entries with a CU, so we maintain a
266      separate table of all line table entries to support the sharing.
267      Note that while there can be way more TUs than CUs, we've already
268      sorted all the TUs into "type unit groups", grouped by their
269      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
270      CU and its associated TU group if there is one.  */
271   htab_t quick_file_names_table;
272
273   /* Set during partial symbol reading, to prevent queueing of full
274      symbols.  */
275   int reading_partial_symbols;
276
277   /* Table mapping type DIEs to their struct type *.
278      This is NULL if not allocated yet.
279      The mapping is done via (CU/TU + DIE offset) -> type.  */
280   htab_t die_type_hash;
281
282   /* The CUs we recently read.  */
283   VEC (dwarf2_per_cu_ptr) *just_read_cus;
284 };
285
286 static struct dwarf2_per_objfile *dwarf2_per_objfile;
287
288 /* Default names of the debugging sections.  */
289
290 /* Note that if the debugging section has been compressed, it might
291    have a name like .zdebug_info.  */
292
293 static const struct dwarf2_debug_sections dwarf2_elf_names =
294 {
295   { ".debug_info", ".zdebug_info" },
296   { ".debug_abbrev", ".zdebug_abbrev" },
297   { ".debug_line", ".zdebug_line" },
298   { ".debug_loc", ".zdebug_loc" },
299   { ".debug_macinfo", ".zdebug_macinfo" },
300   { ".debug_macro", ".zdebug_macro" },
301   { ".debug_str", ".zdebug_str" },
302   { ".debug_ranges", ".zdebug_ranges" },
303   { ".debug_types", ".zdebug_types" },
304   { ".debug_addr", ".zdebug_addr" },
305   { ".debug_frame", ".zdebug_frame" },
306   { ".eh_frame", NULL },
307   { ".gdb_index", ".zgdb_index" },
308   23
309 };
310
311 /* List of DWO/DWP sections.  */
312
313 static const struct dwop_section_names
314 {
315   struct dwarf2_section_names abbrev_dwo;
316   struct dwarf2_section_names info_dwo;
317   struct dwarf2_section_names line_dwo;
318   struct dwarf2_section_names loc_dwo;
319   struct dwarf2_section_names macinfo_dwo;
320   struct dwarf2_section_names macro_dwo;
321   struct dwarf2_section_names str_dwo;
322   struct dwarf2_section_names str_offsets_dwo;
323   struct dwarf2_section_names types_dwo;
324   struct dwarf2_section_names cu_index;
325   struct dwarf2_section_names tu_index;
326 }
327 dwop_section_names =
328 {
329   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
330   { ".debug_info.dwo", ".zdebug_info.dwo" },
331   { ".debug_line.dwo", ".zdebug_line.dwo" },
332   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
333   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
334   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
335   { ".debug_str.dwo", ".zdebug_str.dwo" },
336   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
337   { ".debug_types.dwo", ".zdebug_types.dwo" },
338   { ".debug_cu_index", ".zdebug_cu_index" },
339   { ".debug_tu_index", ".zdebug_tu_index" },
340 };
341
342 /* local data types */
343
344 /* The data in a compilation unit header, after target2host
345    translation, looks like this.  */
346 struct comp_unit_head
347 {
348   unsigned int length;
349   short version;
350   unsigned char addr_size;
351   unsigned char signed_addr_p;
352   sect_offset abbrev_offset;
353
354   /* Size of file offsets; either 4 or 8.  */
355   unsigned int offset_size;
356
357   /* Size of the length field; either 4 or 12.  */
358   unsigned int initial_length_size;
359
360   /* Offset to the first byte of this compilation unit header in the
361      .debug_info section, for resolving relative reference dies.  */
362   sect_offset offset;
363
364   /* Offset to first die in this cu from the start of the cu.
365      This will be the first byte following the compilation unit header.  */
366   cu_offset first_die_offset;
367 };
368
369 /* Type used for delaying computation of method physnames.
370    See comments for compute_delayed_physnames.  */
371 struct delayed_method_info
372 {
373   /* The type to which the method is attached, i.e., its parent class.  */
374   struct type *type;
375
376   /* The index of the method in the type's function fieldlists.  */
377   int fnfield_index;
378
379   /* The index of the method in the fieldlist.  */
380   int index;
381
382   /* The name of the DIE.  */
383   const char *name;
384
385   /*  The DIE associated with this method.  */
386   struct die_info *die;
387 };
388
389 typedef struct delayed_method_info delayed_method_info;
390 DEF_VEC_O (delayed_method_info);
391
392 /* Internal state when decoding a particular compilation unit.  */
393 struct dwarf2_cu
394 {
395   /* The objfile containing this compilation unit.  */
396   struct objfile *objfile;
397
398   /* The header of the compilation unit.  */
399   struct comp_unit_head header;
400
401   /* Base address of this compilation unit.  */
402   CORE_ADDR base_address;
403
404   /* Non-zero if base_address has been set.  */
405   int base_known;
406
407   /* The language we are debugging.  */
408   enum language language;
409   const struct language_defn *language_defn;
410
411   const char *producer;
412
413   /* The generic symbol table building routines have separate lists for
414      file scope symbols and all all other scopes (local scopes).  So
415      we need to select the right one to pass to add_symbol_to_list().
416      We do it by keeping a pointer to the correct list in list_in_scope.
417
418      FIXME: The original dwarf code just treated the file scope as the
419      first local scope, and all other local scopes as nested local
420      scopes, and worked fine.  Check to see if we really need to
421      distinguish these in buildsym.c.  */
422   struct pending **list_in_scope;
423
424   /* The abbrev table for this CU.
425      Normally this points to the abbrev table in the objfile.
426      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
427   struct abbrev_table *abbrev_table;
428
429   /* Hash table holding all the loaded partial DIEs
430      with partial_die->offset.SECT_OFF as hash.  */
431   htab_t partial_dies;
432
433   /* Storage for things with the same lifetime as this read-in compilation
434      unit, including partial DIEs.  */
435   struct obstack comp_unit_obstack;
436
437   /* When multiple dwarf2_cu structures are living in memory, this field
438      chains them all together, so that they can be released efficiently.
439      We will probably also want a generation counter so that most-recently-used
440      compilation units are cached...  */
441   struct dwarf2_per_cu_data *read_in_chain;
442
443   /* Backlink to our per_cu entry.  */
444   struct dwarf2_per_cu_data *per_cu;
445
446   /* How many compilation units ago was this CU last referenced?  */
447   int last_used;
448
449   /* A hash table of DIE cu_offset for following references with
450      die_info->offset.sect_off as hash.  */
451   htab_t die_hash;
452
453   /* Full DIEs if read in.  */
454   struct die_info *dies;
455
456   /* A set of pointers to dwarf2_per_cu_data objects for compilation
457      units referenced by this one.  Only set during full symbol processing;
458      partial symbol tables do not have dependencies.  */
459   htab_t dependencies;
460
461   /* Header data from the line table, during full symbol processing.  */
462   struct line_header *line_header;
463
464   /* A list of methods which need to have physnames computed
465      after all type information has been read.  */
466   VEC (delayed_method_info) *method_list;
467
468   /* To be copied to symtab->call_site_htab.  */
469   htab_t call_site_htab;
470
471   /* Non-NULL if this CU came from a DWO file.
472      There is an invariant here that is important to remember:
473      Except for attributes copied from the top level DIE in the "main"
474      (or "stub") file in preparation for reading the DWO file
475      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
476      Either there isn't a DWO file (in which case this is NULL and the point
477      is moot), or there is and either we're not going to read it (in which
478      case this is NULL) or there is and we are reading it (in which case this
479      is non-NULL).  */
480   struct dwo_unit *dwo_unit;
481
482   /* The DW_AT_addr_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   ULONGEST addr_base;
486
487   /* The DW_AT_ranges_base attribute if present, zero otherwise
488      (zero is a valid value though).
489      Note this value comes from the stub CU/TU's DIE.
490      Also note that the value is zero in the non-DWO case so this value can
491      be used without needing to know whether DWO files are in use or not.
492      N.B. This does not apply to DW_AT_ranges appearing in
493      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
494      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
495      DW_AT_ranges_base *would* have to be applied, and we'd have to care
496      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
497   ULONGEST ranges_base;
498
499   /* Mark used when releasing cached dies.  */
500   unsigned int mark : 1;
501
502   /* This CU references .debug_loc.  See the symtab->locations_valid field.
503      This test is imperfect as there may exist optimized debug code not using
504      any location list and still facing inlining issues if handled as
505      unoptimized code.  For a future better test see GCC PR other/32998.  */
506   unsigned int has_loclist : 1;
507
508   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
509      if all the producer_is_* fields are valid.  This information is cached
510      because profiling CU expansion showed excessive time spent in
511      producer_is_gxx_lt_4_6.  */
512   unsigned int checked_producer : 1;
513   unsigned int producer_is_gxx_lt_4_6 : 1;
514   unsigned int producer_is_gcc_lt_4_3 : 1;
515   unsigned int producer_is_icc : 1;
516
517   /* When set, the file that we're processing is known to have
518      debugging info for C++ namespaces.  GCC 3.3.x did not produce
519      this information, but later versions do.  */
520
521   unsigned int processing_has_namespace_info : 1;
522 };
523
524 /* Persistent data held for a compilation unit, even when not
525    processing it.  We put a pointer to this structure in the
526    read_symtab_private field of the psymtab.  */
527
528 struct dwarf2_per_cu_data
529 {
530   /* The start offset and length of this compilation unit.
531      NOTE: Unlike comp_unit_head.length, this length includes
532      initial_length_size.
533      If the DIE refers to a DWO file, this is always of the original die,
534      not the DWO file.  */
535   sect_offset offset;
536   unsigned int length;
537
538   /* Flag indicating this compilation unit will be read in before
539      any of the current compilation units are processed.  */
540   unsigned int queued : 1;
541
542   /* This flag will be set when reading partial DIEs if we need to load
543      absolutely all DIEs for this compilation unit, instead of just the ones
544      we think are interesting.  It gets set if we look for a DIE in the
545      hash table and don't find it.  */
546   unsigned int load_all_dies : 1;
547
548   /* Non-zero if this CU is from .debug_types.
549      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
550      this is non-zero.  */
551   unsigned int is_debug_types : 1;
552
553   /* Non-zero if this CU is from the .dwz file.  */
554   unsigned int is_dwz : 1;
555
556   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
557      This flag is only valid if is_debug_types is true.
558      We can't read a CU directly from a DWO file: There are required
559      attributes in the stub.  */
560   unsigned int reading_dwo_directly : 1;
561
562   /* Non-zero if the TU has been read.
563      This is used to assist the "Stay in DWO Optimization" for Fission:
564      When reading a DWO, it's faster to read TUs from the DWO instead of
565      fetching them from random other DWOs (due to comdat folding).
566      If the TU has already been read, the optimization is unnecessary
567      (and unwise - we don't want to change where gdb thinks the TU lives
568      "midflight").
569      This flag is only valid if is_debug_types is true.  */
570   unsigned int tu_read : 1;
571
572   /* The section this CU/TU lives in.
573      If the DIE refers to a DWO file, this is always the original die,
574      not the DWO file.  */
575   struct dwarf2_section_info *section;
576
577   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
578      of the CU cache it gets reset to NULL again.  */
579   struct dwarf2_cu *cu;
580
581   /* The corresponding objfile.
582      Normally we can get the objfile from dwarf2_per_objfile.
583      However we can enter this file with just a "per_cu" handle.  */
584   struct objfile *objfile;
585
586   /* When using partial symbol tables, the 'psymtab' field is active.
587      Otherwise the 'quick' field is active.  */
588   union
589   {
590     /* The partial symbol table associated with this compilation unit,
591        or NULL for unread partial units.  */
592     struct partial_symtab *psymtab;
593
594     /* Data needed by the "quick" functions.  */
595     struct dwarf2_per_cu_quick_data *quick;
596   } v;
597
598   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
599      while reading psymtabs, used to compute the psymtab dependencies,
600      and then cleared.  Then it is filled in again while reading full
601      symbols, and only deleted when the objfile is destroyed.
602
603      This is also used to work around a difference between the way gold
604      generates .gdb_index version <=7 and the way gdb does.  Arguably this
605      is a gold bug.  For symbols coming from TUs, gold records in the index
606      the CU that includes the TU instead of the TU itself.  This breaks
607      dw2_lookup_symbol: It assumes that if the index says symbol X lives
608      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
609      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
610      we need to look in TU Z to find X.  Fortunately, this is akin to
611      DW_TAG_imported_unit, so we just use the same mechanism: For
612      .gdb_index version <=7 this also records the TUs that the CU referred
613      to.  Concurrently with this change gdb was modified to emit version 8
614      indices so we only pay a price for gold generated indices.
615      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
616   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
617 };
618
619 /* Entry in the signatured_types hash table.  */
620
621 struct signatured_type
622 {
623   /* The "per_cu" object of this type.
624      This struct is used iff per_cu.is_debug_types.
625      N.B.: This is the first member so that it's easy to convert pointers
626      between them.  */
627   struct dwarf2_per_cu_data per_cu;
628
629   /* The type's signature.  */
630   ULONGEST signature;
631
632   /* Offset in the TU of the type's DIE, as read from the TU header.
633      If this TU is a DWO stub and the definition lives in a DWO file
634      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
635   cu_offset type_offset_in_tu;
636
637   /* Offset in the section of the type's DIE.
638      If the definition lives in a DWO file, this is the offset in the
639      .debug_types.dwo section.
640      The value is zero until the actual value is known.
641      Zero is otherwise not a valid section offset.  */
642   sect_offset type_offset_in_section;
643
644   /* Type units are grouped by their DW_AT_stmt_list entry so that they
645      can share them.  This points to the containing symtab.  */
646   struct type_unit_group *type_unit_group;
647
648   /* The type.
649      The first time we encounter this type we fully read it in and install it
650      in the symbol tables.  Subsequent times we only need the type.  */
651   struct type *type;
652
653   /* Containing DWO unit.
654      This field is valid iff per_cu.reading_dwo_directly.  */
655   struct dwo_unit *dwo_unit;
656 };
657
658 typedef struct signatured_type *sig_type_ptr;
659 DEF_VEC_P (sig_type_ptr);
660
661 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
662    This includes type_unit_group and quick_file_names.  */
663
664 struct stmt_list_hash
665 {
666   /* The DWO unit this table is from or NULL if there is none.  */
667   struct dwo_unit *dwo_unit;
668
669   /* Offset in .debug_line or .debug_line.dwo.  */
670   sect_offset line_offset;
671 };
672
673 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
674    an object of this type.  */
675
676 struct type_unit_group
677 {
678   /* dwarf2read.c's main "handle" on a TU symtab.
679      To simplify things we create an artificial CU that "includes" all the
680      type units using this stmt_list so that the rest of the code still has
681      a "per_cu" handle on the symtab.
682      This PER_CU is recognized by having no section.  */
683 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
684   struct dwarf2_per_cu_data per_cu;
685
686   /* The TUs that share this DW_AT_stmt_list entry.
687      This is added to while parsing type units to build partial symtabs,
688      and is deleted afterwards and not used again.  */
689   VEC (sig_type_ptr) *tus;
690
691   /* The primary symtab.
692      Type units in a group needn't all be defined in the same source file,
693      so we create an essentially anonymous symtab as the primary symtab.  */
694   struct symtab *primary_symtab;
695
696   /* The data used to construct the hash key.  */
697   struct stmt_list_hash hash;
698
699   /* The number of symtabs from the line header.
700      The value here must match line_header.num_file_names.  */
701   unsigned int num_symtabs;
702
703   /* The symbol tables for this TU (obtained from the files listed in
704      DW_AT_stmt_list).
705      WARNING: The order of entries here must match the order of entries
706      in the line header.  After the first TU using this type_unit_group, the
707      line header for the subsequent TUs is recreated from this.  This is done
708      because we need to use the same symtabs for each TU using the same
709      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
710      there's no guarantee the line header doesn't have duplicate entries.  */
711   struct symtab **symtabs;
712 };
713
714 /* These sections are what may appear in a DWO file.  */
715
716 struct dwo_sections
717 {
718   struct dwarf2_section_info abbrev;
719   struct dwarf2_section_info line;
720   struct dwarf2_section_info loc;
721   struct dwarf2_section_info macinfo;
722   struct dwarf2_section_info macro;
723   struct dwarf2_section_info str;
724   struct dwarf2_section_info str_offsets;
725   /* In the case of a virtual DWO file, these two are unused.  */
726   struct dwarf2_section_info info;
727   VEC (dwarf2_section_info_def) *types;
728 };
729
730 /* CUs/TUs in DWP/DWO files.  */
731
732 struct dwo_unit
733 {
734   /* Backlink to the containing struct dwo_file.  */
735   struct dwo_file *dwo_file;
736
737   /* The "id" that distinguishes this CU/TU.
738      .debug_info calls this "dwo_id", .debug_types calls this "signature".
739      Since signatures came first, we stick with it for consistency.  */
740   ULONGEST signature;
741
742   /* The section this CU/TU lives in, in the DWO file.  */
743   struct dwarf2_section_info *section;
744
745   /* Same as dwarf2_per_cu_data:{offset,length} but in the DWO section.  */
746   sect_offset offset;
747   unsigned int length;
748
749   /* For types, offset in the type's DIE of the type defined by this TU.  */
750   cu_offset type_offset_in_tu;
751 };
752
753 /* Data for one DWO file.
754
755    This includes virtual DWO files (a virtual DWO file is a DWO file as it
756    appears in a DWP file).  DWP files don't really have DWO files per se -
757    comdat folding of types "loses" the DWO file they came from, and from
758    a high level view DWP files appear to contain a mass of random types.
759    However, to maintain consistency with the non-DWP case we pretend DWP
760    files contain virtual DWO files, and we assign each TU with one virtual
761    DWO file (generally based on the line and abbrev section offsets -
762    a heuristic that seems to work in practice).  */
763
764 struct dwo_file
765 {
766   /* The DW_AT_GNU_dwo_name attribute.
767      For virtual DWO files the name is constructed from the section offsets
768      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
769      from related CU+TUs.  */
770   const char *dwo_name;
771
772   /* The DW_AT_comp_dir attribute.  */
773   const char *comp_dir;
774
775   /* The bfd, when the file is open.  Otherwise this is NULL.
776      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
777   bfd *dbfd;
778
779   /* Section info for this file.  */
780   struct dwo_sections sections;
781
782   /* The CU in the file.
783      We only support one because having more than one requires hacking the
784      dwo_name of each to match, which is highly unlikely to happen.
785      Doing this means all TUs can share comp_dir: We also assume that
786      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
787   struct dwo_unit *cu;
788
789   /* Table of TUs in the file.
790      Each element is a struct dwo_unit.  */
791   htab_t tus;
792 };
793
794 /* These sections are what may appear in a DWP file.  */
795
796 struct dwp_sections
797 {
798   struct dwarf2_section_info str;
799   struct dwarf2_section_info cu_index;
800   struct dwarf2_section_info tu_index;
801   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
802      by section number.  We don't need to record them here.  */
803 };
804
805 /* These sections are what may appear in a virtual DWO file.  */
806
807 struct virtual_dwo_sections
808 {
809   struct dwarf2_section_info abbrev;
810   struct dwarf2_section_info line;
811   struct dwarf2_section_info loc;
812   struct dwarf2_section_info macinfo;
813   struct dwarf2_section_info macro;
814   struct dwarf2_section_info str_offsets;
815   /* Each DWP hash table entry records one CU or one TU.
816      That is recorded here, and copied to dwo_unit.section.  */
817   struct dwarf2_section_info info_or_types;
818 };
819
820 /* Contents of DWP hash tables.  */
821
822 struct dwp_hash_table
823 {
824   uint32_t nr_units, nr_slots;
825   const gdb_byte *hash_table, *unit_table, *section_pool;
826 };
827
828 /* Data for one DWP file.  */
829
830 struct dwp_file
831 {
832   /* Name of the file.  */
833   const char *name;
834
835   /* The bfd.  */
836   bfd *dbfd;
837
838   /* Section info for this file.  */
839   struct dwp_sections sections;
840
841   /* Table of CUs in the file.  */
842   const struct dwp_hash_table *cus;
843
844   /* Table of TUs in the file.  */
845   const struct dwp_hash_table *tus;
846
847   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
848   htab_t loaded_cus;
849   htab_t loaded_tus;
850
851   /* Table to map ELF section numbers to their sections.  */
852   unsigned int num_sections;
853   asection **elf_sections;
854 };
855
856 /* This represents a '.dwz' file.  */
857
858 struct dwz_file
859 {
860   /* A dwz file can only contain a few sections.  */
861   struct dwarf2_section_info abbrev;
862   struct dwarf2_section_info info;
863   struct dwarf2_section_info str;
864   struct dwarf2_section_info line;
865   struct dwarf2_section_info macro;
866   struct dwarf2_section_info gdb_index;
867
868   /* The dwz's BFD.  */
869   bfd *dwz_bfd;
870 };
871
872 /* Struct used to pass misc. parameters to read_die_and_children, et
873    al.  which are used for both .debug_info and .debug_types dies.
874    All parameters here are unchanging for the life of the call.  This
875    struct exists to abstract away the constant parameters of die reading.  */
876
877 struct die_reader_specs
878 {
879   /* The bfd of die_section.  */
880   bfd* abfd;
881
882   /* The CU of the DIE we are parsing.  */
883   struct dwarf2_cu *cu;
884
885   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
886   struct dwo_file *dwo_file;
887
888   /* The section the die comes from.
889      This is either .debug_info or .debug_types, or the .dwo variants.  */
890   struct dwarf2_section_info *die_section;
891
892   /* die_section->buffer.  */
893   const gdb_byte *buffer;
894
895   /* The end of the buffer.  */
896   const gdb_byte *buffer_end;
897
898   /* The value of the DW_AT_comp_dir attribute.  */
899   const char *comp_dir;
900 };
901
902 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
903 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
904                                       const gdb_byte *info_ptr,
905                                       struct die_info *comp_unit_die,
906                                       int has_children,
907                                       void *data);
908
909 /* The line number information for a compilation unit (found in the
910    .debug_line section) begins with a "statement program header",
911    which contains the following information.  */
912 struct line_header
913 {
914   unsigned int total_length;
915   unsigned short version;
916   unsigned int header_length;
917   unsigned char minimum_instruction_length;
918   unsigned char maximum_ops_per_instruction;
919   unsigned char default_is_stmt;
920   int line_base;
921   unsigned char line_range;
922   unsigned char opcode_base;
923
924   /* standard_opcode_lengths[i] is the number of operands for the
925      standard opcode whose value is i.  This means that
926      standard_opcode_lengths[0] is unused, and the last meaningful
927      element is standard_opcode_lengths[opcode_base - 1].  */
928   unsigned char *standard_opcode_lengths;
929
930   /* The include_directories table.  NOTE!  These strings are not
931      allocated with xmalloc; instead, they are pointers into
932      debug_line_buffer.  If you try to free them, `free' will get
933      indigestion.  */
934   unsigned int num_include_dirs, include_dirs_size;
935   const char **include_dirs;
936
937   /* The file_names table.  NOTE!  These strings are not allocated
938      with xmalloc; instead, they are pointers into debug_line_buffer.
939      Don't try to free them directly.  */
940   unsigned int num_file_names, file_names_size;
941   struct file_entry
942   {
943     const char *name;
944     unsigned int dir_index;
945     unsigned int mod_time;
946     unsigned int length;
947     int included_p; /* Non-zero if referenced by the Line Number Program.  */
948     struct symtab *symtab; /* The associated symbol table, if any.  */
949   } *file_names;
950
951   /* The start and end of the statement program following this
952      header.  These point into dwarf2_per_objfile->line_buffer.  */
953   const gdb_byte *statement_program_start, *statement_program_end;
954 };
955
956 /* When we construct a partial symbol table entry we only
957    need this much information.  */
958 struct partial_die_info
959   {
960     /* Offset of this DIE.  */
961     sect_offset offset;
962
963     /* DWARF-2 tag for this DIE.  */
964     ENUM_BITFIELD(dwarf_tag) tag : 16;
965
966     /* Assorted flags describing the data found in this DIE.  */
967     unsigned int has_children : 1;
968     unsigned int is_external : 1;
969     unsigned int is_declaration : 1;
970     unsigned int has_type : 1;
971     unsigned int has_specification : 1;
972     unsigned int has_pc_info : 1;
973     unsigned int may_be_inlined : 1;
974
975     /* Flag set if the SCOPE field of this structure has been
976        computed.  */
977     unsigned int scope_set : 1;
978
979     /* Flag set if the DIE has a byte_size attribute.  */
980     unsigned int has_byte_size : 1;
981
982     /* Flag set if any of the DIE's children are template arguments.  */
983     unsigned int has_template_arguments : 1;
984
985     /* Flag set if fixup_partial_die has been called on this die.  */
986     unsigned int fixup_called : 1;
987
988     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
989     unsigned int is_dwz : 1;
990
991     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
992     unsigned int spec_is_dwz : 1;
993
994     /* The name of this DIE.  Normally the value of DW_AT_name, but
995        sometimes a default name for unnamed DIEs.  */
996     const char *name;
997
998     /* The linkage name, if present.  */
999     const char *linkage_name;
1000
1001     /* The scope to prepend to our children.  This is generally
1002        allocated on the comp_unit_obstack, so will disappear
1003        when this compilation unit leaves the cache.  */
1004     const char *scope;
1005
1006     /* Some data associated with the partial DIE.  The tag determines
1007        which field is live.  */
1008     union
1009     {
1010       /* The location description associated with this DIE, if any.  */
1011       struct dwarf_block *locdesc;
1012       /* The offset of an import, for DW_TAG_imported_unit.  */
1013       sect_offset offset;
1014     } d;
1015
1016     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1017     CORE_ADDR lowpc;
1018     CORE_ADDR highpc;
1019
1020     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1021        DW_AT_sibling, if any.  */
1022     /* NOTE: This member isn't strictly necessary, read_partial_die could
1023        return DW_AT_sibling values to its caller load_partial_dies.  */
1024     const gdb_byte *sibling;
1025
1026     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1027        DW_AT_specification (or DW_AT_abstract_origin or
1028        DW_AT_extension).  */
1029     sect_offset spec_offset;
1030
1031     /* Pointers to this DIE's parent, first child, and next sibling,
1032        if any.  */
1033     struct partial_die_info *die_parent, *die_child, *die_sibling;
1034   };
1035
1036 /* This data structure holds the information of an abbrev.  */
1037 struct abbrev_info
1038   {
1039     unsigned int number;        /* number identifying abbrev */
1040     enum dwarf_tag tag;         /* dwarf tag */
1041     unsigned short has_children;                /* boolean */
1042     unsigned short num_attrs;   /* number of attributes */
1043     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1044     struct abbrev_info *next;   /* next in chain */
1045   };
1046
1047 struct attr_abbrev
1048   {
1049     ENUM_BITFIELD(dwarf_attribute) name : 16;
1050     ENUM_BITFIELD(dwarf_form) form : 16;
1051   };
1052
1053 /* Size of abbrev_table.abbrev_hash_table.  */
1054 #define ABBREV_HASH_SIZE 121
1055
1056 /* Top level data structure to contain an abbreviation table.  */
1057
1058 struct abbrev_table
1059 {
1060   /* Where the abbrev table came from.
1061      This is used as a sanity check when the table is used.  */
1062   sect_offset offset;
1063
1064   /* Storage for the abbrev table.  */
1065   struct obstack abbrev_obstack;
1066
1067   /* Hash table of abbrevs.
1068      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1069      It could be statically allocated, but the previous code didn't so we
1070      don't either.  */
1071   struct abbrev_info **abbrevs;
1072 };
1073
1074 /* Attributes have a name and a value.  */
1075 struct attribute
1076   {
1077     ENUM_BITFIELD(dwarf_attribute) name : 16;
1078     ENUM_BITFIELD(dwarf_form) form : 15;
1079
1080     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1081        field should be in u.str (existing only for DW_STRING) but it is kept
1082        here for better struct attribute alignment.  */
1083     unsigned int string_is_canonical : 1;
1084
1085     union
1086       {
1087         const char *str;
1088         struct dwarf_block *blk;
1089         ULONGEST unsnd;
1090         LONGEST snd;
1091         CORE_ADDR addr;
1092         ULONGEST signature;
1093       }
1094     u;
1095   };
1096
1097 /* This data structure holds a complete die structure.  */
1098 struct die_info
1099   {
1100     /* DWARF-2 tag for this DIE.  */
1101     ENUM_BITFIELD(dwarf_tag) tag : 16;
1102
1103     /* Number of attributes */
1104     unsigned char num_attrs;
1105
1106     /* True if we're presently building the full type name for the
1107        type derived from this DIE.  */
1108     unsigned char building_fullname : 1;
1109
1110     /* Abbrev number */
1111     unsigned int abbrev;
1112
1113     /* Offset in .debug_info or .debug_types section.  */
1114     sect_offset offset;
1115
1116     /* The dies in a compilation unit form an n-ary tree.  PARENT
1117        points to this die's parent; CHILD points to the first child of
1118        this node; and all the children of a given node are chained
1119        together via their SIBLING fields.  */
1120     struct die_info *child;     /* Its first child, if any.  */
1121     struct die_info *sibling;   /* Its next sibling, if any.  */
1122     struct die_info *parent;    /* Its parent, if any.  */
1123
1124     /* An array of attributes, with NUM_ATTRS elements.  There may be
1125        zero, but it's not common and zero-sized arrays are not
1126        sufficiently portable C.  */
1127     struct attribute attrs[1];
1128   };
1129
1130 /* Get at parts of an attribute structure.  */
1131
1132 #define DW_STRING(attr)    ((attr)->u.str)
1133 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1134 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1135 #define DW_BLOCK(attr)     ((attr)->u.blk)
1136 #define DW_SND(attr)       ((attr)->u.snd)
1137 #define DW_ADDR(attr)      ((attr)->u.addr)
1138 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1139
1140 /* Blocks are a bunch of untyped bytes.  */
1141 struct dwarf_block
1142   {
1143     size_t size;
1144
1145     /* Valid only if SIZE is not zero.  */
1146     const gdb_byte *data;
1147   };
1148
1149 #ifndef ATTR_ALLOC_CHUNK
1150 #define ATTR_ALLOC_CHUNK 4
1151 #endif
1152
1153 /* Allocate fields for structs, unions and enums in this size.  */
1154 #ifndef DW_FIELD_ALLOC_CHUNK
1155 #define DW_FIELD_ALLOC_CHUNK 4
1156 #endif
1157
1158 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1159    but this would require a corresponding change in unpack_field_as_long
1160    and friends.  */
1161 static int bits_per_byte = 8;
1162
1163 /* The routines that read and process dies for a C struct or C++ class
1164    pass lists of data member fields and lists of member function fields
1165    in an instance of a field_info structure, as defined below.  */
1166 struct field_info
1167   {
1168     /* List of data member and baseclasses fields.  */
1169     struct nextfield
1170       {
1171         struct nextfield *next;
1172         int accessibility;
1173         int virtuality;
1174         struct field field;
1175       }
1176      *fields, *baseclasses;
1177
1178     /* Number of fields (including baseclasses).  */
1179     int nfields;
1180
1181     /* Number of baseclasses.  */
1182     int nbaseclasses;
1183
1184     /* Set if the accesibility of one of the fields is not public.  */
1185     int non_public_fields;
1186
1187     /* Member function fields array, entries are allocated in the order they
1188        are encountered in the object file.  */
1189     struct nextfnfield
1190       {
1191         struct nextfnfield *next;
1192         struct fn_field fnfield;
1193       }
1194      *fnfields;
1195
1196     /* Member function fieldlist array, contains name of possibly overloaded
1197        member function, number of overloaded member functions and a pointer
1198        to the head of the member function field chain.  */
1199     struct fnfieldlist
1200       {
1201         const char *name;
1202         int length;
1203         struct nextfnfield *head;
1204       }
1205      *fnfieldlists;
1206
1207     /* Number of entries in the fnfieldlists array.  */
1208     int nfnfields;
1209
1210     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1211        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1212     struct typedef_field_list
1213       {
1214         struct typedef_field field;
1215         struct typedef_field_list *next;
1216       }
1217     *typedef_field_list;
1218     unsigned typedef_field_list_count;
1219   };
1220
1221 /* One item on the queue of compilation units to read in full symbols
1222    for.  */
1223 struct dwarf2_queue_item
1224 {
1225   struct dwarf2_per_cu_data *per_cu;
1226   enum language pretend_language;
1227   struct dwarf2_queue_item *next;
1228 };
1229
1230 /* The current queue.  */
1231 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1232
1233 /* Loaded secondary compilation units are kept in memory until they
1234    have not been referenced for the processing of this many
1235    compilation units.  Set this to zero to disable caching.  Cache
1236    sizes of up to at least twenty will improve startup time for
1237    typical inter-CU-reference binaries, at an obvious memory cost.  */
1238 static int dwarf2_max_cache_age = 5;
1239 static void
1240 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1241                            struct cmd_list_element *c, const char *value)
1242 {
1243   fprintf_filtered (file, _("The upper bound on the age of cached "
1244                             "dwarf2 compilation units is %s.\n"),
1245                     value);
1246 }
1247 \f
1248 /* local function prototypes */
1249
1250 static const char *get_section_name (const struct dwarf2_section_info *);
1251
1252 static const char *get_section_file_name (const struct dwarf2_section_info *);
1253
1254 static void dwarf2_locate_sections (bfd *, asection *, void *);
1255
1256 static void dwarf2_find_base_address (struct die_info *die,
1257                                       struct dwarf2_cu *cu);
1258
1259 static struct partial_symtab *create_partial_symtab
1260   (struct dwarf2_per_cu_data *per_cu, const char *name);
1261
1262 static void dwarf2_build_psymtabs_hard (struct objfile *);
1263
1264 static void scan_partial_symbols (struct partial_die_info *,
1265                                   CORE_ADDR *, CORE_ADDR *,
1266                                   int, struct dwarf2_cu *);
1267
1268 static void add_partial_symbol (struct partial_die_info *,
1269                                 struct dwarf2_cu *);
1270
1271 static void add_partial_namespace (struct partial_die_info *pdi,
1272                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1273                                    int need_pc, struct dwarf2_cu *cu);
1274
1275 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1276                                 CORE_ADDR *highpc, int need_pc,
1277                                 struct dwarf2_cu *cu);
1278
1279 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1280                                      struct dwarf2_cu *cu);
1281
1282 static void add_partial_subprogram (struct partial_die_info *pdi,
1283                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1284                                     int need_pc, struct dwarf2_cu *cu);
1285
1286 static void dwarf2_read_symtab (struct partial_symtab *,
1287                                 struct objfile *);
1288
1289 static void psymtab_to_symtab_1 (struct partial_symtab *);
1290
1291 static struct abbrev_info *abbrev_table_lookup_abbrev
1292   (const struct abbrev_table *, unsigned int);
1293
1294 static struct abbrev_table *abbrev_table_read_table
1295   (struct dwarf2_section_info *, sect_offset);
1296
1297 static void abbrev_table_free (struct abbrev_table *);
1298
1299 static void abbrev_table_free_cleanup (void *);
1300
1301 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1302                                  struct dwarf2_section_info *);
1303
1304 static void dwarf2_free_abbrev_table (void *);
1305
1306 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1307
1308 static struct partial_die_info *load_partial_dies
1309   (const struct die_reader_specs *, const gdb_byte *, int);
1310
1311 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1312                                          struct partial_die_info *,
1313                                          struct abbrev_info *,
1314                                          unsigned int,
1315                                          const gdb_byte *);
1316
1317 static struct partial_die_info *find_partial_die (sect_offset, int,
1318                                                   struct dwarf2_cu *);
1319
1320 static void fixup_partial_die (struct partial_die_info *,
1321                                struct dwarf2_cu *);
1322
1323 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1324                                        struct attribute *, struct attr_abbrev *,
1325                                        const gdb_byte *);
1326
1327 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1328
1329 static int read_1_signed_byte (bfd *, const gdb_byte *);
1330
1331 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1332
1333 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1334
1335 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1336
1337 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1338                                unsigned int *);
1339
1340 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1341
1342 static LONGEST read_checked_initial_length_and_offset
1343   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1344    unsigned int *, unsigned int *);
1345
1346 static LONGEST read_offset (bfd *, const gdb_byte *,
1347                             const struct comp_unit_head *,
1348                             unsigned int *);
1349
1350 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1351
1352 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1353                                        sect_offset);
1354
1355 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1356
1357 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1358
1359 static const char *read_indirect_string (bfd *, const gdb_byte *,
1360                                          const struct comp_unit_head *,
1361                                          unsigned int *);
1362
1363 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1364
1365 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1366
1367 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1368
1369 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1370                                               const gdb_byte *,
1371                                               unsigned int *);
1372
1373 static const char *read_str_index (const struct die_reader_specs *reader,
1374                                    struct dwarf2_cu *cu, ULONGEST str_index);
1375
1376 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1377
1378 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1379                                       struct dwarf2_cu *);
1380
1381 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1382                                                 unsigned int);
1383
1384 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1385                                struct dwarf2_cu *cu);
1386
1387 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1388
1389 static struct die_info *die_specification (struct die_info *die,
1390                                            struct dwarf2_cu **);
1391
1392 static void free_line_header (struct line_header *lh);
1393
1394 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1395                                                      struct dwarf2_cu *cu);
1396
1397 static void dwarf_decode_lines (struct line_header *, const char *,
1398                                 struct dwarf2_cu *, struct partial_symtab *,
1399                                 int);
1400
1401 static void dwarf2_start_subfile (const char *, const char *, const char *);
1402
1403 static void dwarf2_start_symtab (struct dwarf2_cu *,
1404                                  const char *, const char *, CORE_ADDR);
1405
1406 static struct symbol *new_symbol (struct die_info *, struct type *,
1407                                   struct dwarf2_cu *);
1408
1409 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1410                                        struct dwarf2_cu *, struct symbol *);
1411
1412 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1413                                 struct dwarf2_cu *);
1414
1415 static void dwarf2_const_value_attr (const struct attribute *attr,
1416                                      struct type *type,
1417                                      const char *name,
1418                                      struct obstack *obstack,
1419                                      struct dwarf2_cu *cu, LONGEST *value,
1420                                      const gdb_byte **bytes,
1421                                      struct dwarf2_locexpr_baton **baton);
1422
1423 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1424
1425 static int need_gnat_info (struct dwarf2_cu *);
1426
1427 static struct type *die_descriptive_type (struct die_info *,
1428                                           struct dwarf2_cu *);
1429
1430 static void set_descriptive_type (struct type *, struct die_info *,
1431                                   struct dwarf2_cu *);
1432
1433 static struct type *die_containing_type (struct die_info *,
1434                                          struct dwarf2_cu *);
1435
1436 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1437                                      struct dwarf2_cu *);
1438
1439 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1440
1441 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1442
1443 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1444
1445 static char *typename_concat (struct obstack *obs, const char *prefix,
1446                               const char *suffix, int physname,
1447                               struct dwarf2_cu *cu);
1448
1449 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1450
1451 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1452
1453 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1454
1455 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1456
1457 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1458
1459 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1460                                struct dwarf2_cu *, struct partial_symtab *);
1461
1462 static int dwarf2_get_pc_bounds (struct die_info *,
1463                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1464                                  struct partial_symtab *);
1465
1466 static void get_scope_pc_bounds (struct die_info *,
1467                                  CORE_ADDR *, CORE_ADDR *,
1468                                  struct dwarf2_cu *);
1469
1470 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1471                                         CORE_ADDR, struct dwarf2_cu *);
1472
1473 static void dwarf2_add_field (struct field_info *, struct die_info *,
1474                               struct dwarf2_cu *);
1475
1476 static void dwarf2_attach_fields_to_type (struct field_info *,
1477                                           struct type *, struct dwarf2_cu *);
1478
1479 static void dwarf2_add_member_fn (struct field_info *,
1480                                   struct die_info *, struct type *,
1481                                   struct dwarf2_cu *);
1482
1483 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1484                                              struct type *,
1485                                              struct dwarf2_cu *);
1486
1487 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1488
1489 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1490
1491 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1492
1493 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1494
1495 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1496
1497 static struct type *read_module_type (struct die_info *die,
1498                                       struct dwarf2_cu *cu);
1499
1500 static const char *namespace_name (struct die_info *die,
1501                                    int *is_anonymous, struct dwarf2_cu *);
1502
1503 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1504
1505 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1506
1507 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1508                                                        struct dwarf2_cu *);
1509
1510 static struct die_info *read_die_and_siblings_1
1511   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1512    struct die_info *);
1513
1514 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1515                                                const gdb_byte *info_ptr,
1516                                                const gdb_byte **new_info_ptr,
1517                                                struct die_info *parent);
1518
1519 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1520                                         struct die_info **, const gdb_byte *,
1521                                         int *, int);
1522
1523 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1524                                       struct die_info **, const gdb_byte *,
1525                                       int *);
1526
1527 static void process_die (struct die_info *, struct dwarf2_cu *);
1528
1529 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1530                                              struct obstack *);
1531
1532 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1533
1534 static const char *dwarf2_full_name (const char *name,
1535                                      struct die_info *die,
1536                                      struct dwarf2_cu *cu);
1537
1538 static const char *dwarf2_physname (const char *name, struct die_info *die,
1539                                     struct dwarf2_cu *cu);
1540
1541 static struct die_info *dwarf2_extension (struct die_info *die,
1542                                           struct dwarf2_cu **);
1543
1544 static const char *dwarf_tag_name (unsigned int);
1545
1546 static const char *dwarf_attr_name (unsigned int);
1547
1548 static const char *dwarf_form_name (unsigned int);
1549
1550 static char *dwarf_bool_name (unsigned int);
1551
1552 static const char *dwarf_type_encoding_name (unsigned int);
1553
1554 static struct die_info *sibling_die (struct die_info *);
1555
1556 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1557
1558 static void dump_die_for_error (struct die_info *);
1559
1560 static void dump_die_1 (struct ui_file *, int level, int max_level,
1561                         struct die_info *);
1562
1563 /*static*/ void dump_die (struct die_info *, int max_level);
1564
1565 static void store_in_ref_table (struct die_info *,
1566                                 struct dwarf2_cu *);
1567
1568 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1569
1570 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1571
1572 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1573                                                const struct attribute *,
1574                                                struct dwarf2_cu **);
1575
1576 static struct die_info *follow_die_ref (struct die_info *,
1577                                         const struct attribute *,
1578                                         struct dwarf2_cu **);
1579
1580 static struct die_info *follow_die_sig (struct die_info *,
1581                                         const struct attribute *,
1582                                         struct dwarf2_cu **);
1583
1584 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1585                                          struct dwarf2_cu *);
1586
1587 static struct type *get_DW_AT_signature_type (struct die_info *,
1588                                               const struct attribute *,
1589                                               struct dwarf2_cu *);
1590
1591 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1592
1593 static void read_signatured_type (struct signatured_type *);
1594
1595 static struct type_unit_group *get_type_unit_group
1596     (struct dwarf2_cu *, const struct attribute *);
1597
1598 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1599
1600 /* memory allocation interface */
1601
1602 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1603
1604 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1605
1606 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1607                                  const char *, int);
1608
1609 static int attr_form_is_block (const struct attribute *);
1610
1611 static int attr_form_is_section_offset (const struct attribute *);
1612
1613 static int attr_form_is_constant (const struct attribute *);
1614
1615 static int attr_form_is_ref (const struct attribute *);
1616
1617 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1618                                    struct dwarf2_loclist_baton *baton,
1619                                    const struct attribute *attr);
1620
1621 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1622                                          struct symbol *sym,
1623                                          struct dwarf2_cu *cu,
1624                                          int is_block);
1625
1626 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1627                                      const gdb_byte *info_ptr,
1628                                      struct abbrev_info *abbrev);
1629
1630 static void free_stack_comp_unit (void *);
1631
1632 static hashval_t partial_die_hash (const void *item);
1633
1634 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1635
1636 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1637   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1638
1639 static void init_one_comp_unit (struct dwarf2_cu *cu,
1640                                 struct dwarf2_per_cu_data *per_cu);
1641
1642 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1643                                    struct die_info *comp_unit_die,
1644                                    enum language pretend_language);
1645
1646 static void free_heap_comp_unit (void *);
1647
1648 static void free_cached_comp_units (void *);
1649
1650 static void age_cached_comp_units (void);
1651
1652 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1653
1654 static struct type *set_die_type (struct die_info *, struct type *,
1655                                   struct dwarf2_cu *);
1656
1657 static void create_all_comp_units (struct objfile *);
1658
1659 static int create_all_type_units (struct objfile *);
1660
1661 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1662                                  enum language);
1663
1664 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1665                                     enum language);
1666
1667 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1668                                     enum language);
1669
1670 static void dwarf2_add_dependence (struct dwarf2_cu *,
1671                                    struct dwarf2_per_cu_data *);
1672
1673 static void dwarf2_mark (struct dwarf2_cu *);
1674
1675 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1676
1677 static struct type *get_die_type_at_offset (sect_offset,
1678                                             struct dwarf2_per_cu_data *);
1679
1680 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1681
1682 static void dwarf2_release_queue (void *dummy);
1683
1684 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1685                              enum language pretend_language);
1686
1687 static void process_queue (void);
1688
1689 static void find_file_and_directory (struct die_info *die,
1690                                      struct dwarf2_cu *cu,
1691                                      const char **name, const char **comp_dir);
1692
1693 static char *file_full_name (int file, struct line_header *lh,
1694                              const char *comp_dir);
1695
1696 static const gdb_byte *read_and_check_comp_unit_head
1697   (struct comp_unit_head *header,
1698    struct dwarf2_section_info *section,
1699    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1700    int is_debug_types_section);
1701
1702 static void init_cutu_and_read_dies
1703   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1704    int use_existing_cu, int keep,
1705    die_reader_func_ftype *die_reader_func, void *data);
1706
1707 static void init_cutu_and_read_dies_simple
1708   (struct dwarf2_per_cu_data *this_cu,
1709    die_reader_func_ftype *die_reader_func, void *data);
1710
1711 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1712
1713 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1714
1715 static struct dwo_unit *lookup_dwo_unit_in_dwp
1716   (struct dwp_file *dwp_file, const char *comp_dir,
1717    ULONGEST signature, int is_debug_types);
1718
1719 static struct dwp_file *get_dwp_file (void);
1720
1721 static struct dwo_unit *lookup_dwo_comp_unit
1722   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1723
1724 static struct dwo_unit *lookup_dwo_type_unit
1725   (struct signatured_type *, const char *, const char *);
1726
1727 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1728
1729 static void free_dwo_file_cleanup (void *);
1730
1731 static void process_cu_includes (void);
1732
1733 static void check_producer (struct dwarf2_cu *cu);
1734 \f
1735 /* Various complaints about symbol reading that don't abort the process.  */
1736
1737 static void
1738 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1739 {
1740   complaint (&symfile_complaints,
1741              _("statement list doesn't fit in .debug_line section"));
1742 }
1743
1744 static void
1745 dwarf2_debug_line_missing_file_complaint (void)
1746 {
1747   complaint (&symfile_complaints,
1748              _(".debug_line section has line data without a file"));
1749 }
1750
1751 static void
1752 dwarf2_debug_line_missing_end_sequence_complaint (void)
1753 {
1754   complaint (&symfile_complaints,
1755              _(".debug_line section has line "
1756                "program sequence without an end"));
1757 }
1758
1759 static void
1760 dwarf2_complex_location_expr_complaint (void)
1761 {
1762   complaint (&symfile_complaints, _("location expression too complex"));
1763 }
1764
1765 static void
1766 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1767                                               int arg3)
1768 {
1769   complaint (&symfile_complaints,
1770              _("const value length mismatch for '%s', got %d, expected %d"),
1771              arg1, arg2, arg3);
1772 }
1773
1774 static void
1775 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1776 {
1777   complaint (&symfile_complaints,
1778              _("debug info runs off end of %s section"
1779                " [in module %s]"),
1780              get_section_name (section),
1781              get_section_file_name (section));
1782 }
1783
1784 static void
1785 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1786 {
1787   complaint (&symfile_complaints,
1788              _("macro debug info contains a "
1789                "malformed macro definition:\n`%s'"),
1790              arg1);
1791 }
1792
1793 static void
1794 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1795 {
1796   complaint (&symfile_complaints,
1797              _("invalid attribute class or form for '%s' in '%s'"),
1798              arg1, arg2);
1799 }
1800 \f
1801 #if WORDS_BIGENDIAN
1802
1803 /* Convert VALUE between big- and little-endian.  */
1804 static offset_type
1805 byte_swap (offset_type value)
1806 {
1807   offset_type result;
1808
1809   result = (value & 0xff) << 24;
1810   result |= (value & 0xff00) << 8;
1811   result |= (value & 0xff0000) >> 8;
1812   result |= (value & 0xff000000) >> 24;
1813   return result;
1814 }
1815
1816 #define MAYBE_SWAP(V)  byte_swap (V)
1817
1818 #else
1819 #define MAYBE_SWAP(V) (V)
1820 #endif /* WORDS_BIGENDIAN */
1821
1822 /* The suffix for an index file.  */
1823 #define INDEX_SUFFIX ".gdb-index"
1824
1825 /* Try to locate the sections we need for DWARF 2 debugging
1826    information and return true if we have enough to do something.
1827    NAMES points to the dwarf2 section names, or is NULL if the standard
1828    ELF names are used.  */
1829
1830 int
1831 dwarf2_has_info (struct objfile *objfile,
1832                  const struct dwarf2_debug_sections *names)
1833 {
1834   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1835   if (!dwarf2_per_objfile)
1836     {
1837       /* Initialize per-objfile state.  */
1838       struct dwarf2_per_objfile *data
1839         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1840
1841       memset (data, 0, sizeof (*data));
1842       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1843       dwarf2_per_objfile = data;
1844
1845       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1846                              (void *) names);
1847       dwarf2_per_objfile->objfile = objfile;
1848     }
1849   return (dwarf2_per_objfile->info.asection != NULL
1850           && dwarf2_per_objfile->abbrev.asection != NULL);
1851 }
1852
1853 /* Return the bfd owner of SECTION.  */
1854
1855 static struct bfd *
1856 get_section_bfd_owner (const struct dwarf2_section_info *section)
1857 {
1858   return section->asection->owner;
1859 }
1860
1861 /* Return the bfd section of SECTION.
1862    Returns NULL if the section is not present.  */
1863
1864 static asection *
1865 get_section_bfd_section (const struct dwarf2_section_info *section)
1866 {
1867   return section->asection;
1868 }
1869
1870 /* Return the name of SECTION.  */
1871
1872 static const char *
1873 get_section_name (const struct dwarf2_section_info *section)
1874 {
1875   asection *sectp = get_section_bfd_section (section);
1876
1877   gdb_assert (sectp != NULL);
1878   return bfd_section_name (get_section_bfd_owner (section), sectp);
1879 }
1880
1881 /* Return the name of the file SECTION is in.  */
1882
1883 static const char *
1884 get_section_file_name (const struct dwarf2_section_info *section)
1885 {
1886   bfd *abfd = get_section_bfd_owner (section);
1887
1888   return bfd_get_filename (abfd);
1889 }
1890
1891 /* Return the id of SECTION.
1892    Returns 0 if SECTION doesn't exist.  */
1893
1894 static int
1895 get_section_id (const struct dwarf2_section_info *section)
1896 {
1897   asection *sectp = get_section_bfd_section (section);
1898
1899   if (sectp == NULL)
1900     return 0;
1901   return sectp->id;
1902 }
1903
1904 /* Return the flags of SECTION.
1905    SECTION must exist.  */
1906
1907 static int
1908 get_section_flags (const struct dwarf2_section_info *section)
1909 {
1910   asection *sectp = get_section_bfd_section (section);
1911
1912   gdb_assert (sectp != NULL);
1913   return bfd_get_section_flags (sectp->owner, sectp);
1914 }
1915
1916 /* When loading sections, we look either for uncompressed section or for
1917    compressed section names.  */
1918
1919 static int
1920 section_is_p (const char *section_name,
1921               const struct dwarf2_section_names *names)
1922 {
1923   if (names->normal != NULL
1924       && strcmp (section_name, names->normal) == 0)
1925     return 1;
1926   if (names->compressed != NULL
1927       && strcmp (section_name, names->compressed) == 0)
1928     return 1;
1929   return 0;
1930 }
1931
1932 /* This function is mapped across the sections and remembers the
1933    offset and size of each of the debugging sections we are interested
1934    in.  */
1935
1936 static void
1937 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1938 {
1939   const struct dwarf2_debug_sections *names;
1940   flagword aflag = bfd_get_section_flags (abfd, sectp);
1941
1942   if (vnames == NULL)
1943     names = &dwarf2_elf_names;
1944   else
1945     names = (const struct dwarf2_debug_sections *) vnames;
1946
1947   if ((aflag & SEC_HAS_CONTENTS) == 0)
1948     {
1949     }
1950   else if (section_is_p (sectp->name, &names->info))
1951     {
1952       dwarf2_per_objfile->info.asection = sectp;
1953       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1954     }
1955   else if (section_is_p (sectp->name, &names->abbrev))
1956     {
1957       dwarf2_per_objfile->abbrev.asection = sectp;
1958       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1959     }
1960   else if (section_is_p (sectp->name, &names->line))
1961     {
1962       dwarf2_per_objfile->line.asection = sectp;
1963       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1964     }
1965   else if (section_is_p (sectp->name, &names->loc))
1966     {
1967       dwarf2_per_objfile->loc.asection = sectp;
1968       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1969     }
1970   else if (section_is_p (sectp->name, &names->macinfo))
1971     {
1972       dwarf2_per_objfile->macinfo.asection = sectp;
1973       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1974     }
1975   else if (section_is_p (sectp->name, &names->macro))
1976     {
1977       dwarf2_per_objfile->macro.asection = sectp;
1978       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1979     }
1980   else if (section_is_p (sectp->name, &names->str))
1981     {
1982       dwarf2_per_objfile->str.asection = sectp;
1983       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1984     }
1985   else if (section_is_p (sectp->name, &names->addr))
1986     {
1987       dwarf2_per_objfile->addr.asection = sectp;
1988       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1989     }
1990   else if (section_is_p (sectp->name, &names->frame))
1991     {
1992       dwarf2_per_objfile->frame.asection = sectp;
1993       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1994     }
1995   else if (section_is_p (sectp->name, &names->eh_frame))
1996     {
1997       dwarf2_per_objfile->eh_frame.asection = sectp;
1998       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1999     }
2000   else if (section_is_p (sectp->name, &names->ranges))
2001     {
2002       dwarf2_per_objfile->ranges.asection = sectp;
2003       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2004     }
2005   else if (section_is_p (sectp->name, &names->types))
2006     {
2007       struct dwarf2_section_info type_section;
2008
2009       memset (&type_section, 0, sizeof (type_section));
2010       type_section.asection = sectp;
2011       type_section.size = bfd_get_section_size (sectp);
2012
2013       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2014                      &type_section);
2015     }
2016   else if (section_is_p (sectp->name, &names->gdb_index))
2017     {
2018       dwarf2_per_objfile->gdb_index.asection = sectp;
2019       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2020     }
2021
2022   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
2023       && bfd_section_vma (abfd, sectp) == 0)
2024     dwarf2_per_objfile->has_section_at_zero = 1;
2025 }
2026
2027 /* A helper function that decides whether a section is empty,
2028    or not present.  */
2029
2030 static int
2031 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2032 {
2033   return section->asection == NULL || section->size == 0;
2034 }
2035
2036 /* Read the contents of the section INFO.
2037    OBJFILE is the main object file, but not necessarily the file where
2038    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2039    of the DWO file.
2040    If the section is compressed, uncompress it before returning.  */
2041
2042 static void
2043 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2044 {
2045   asection *sectp;
2046   bfd *abfd;
2047   gdb_byte *buf, *retbuf;
2048
2049   if (info->readin)
2050     return;
2051   info->buffer = NULL;
2052   info->readin = 1;
2053
2054   if (dwarf2_section_empty_p (info))
2055     return;
2056
2057   sectp = get_section_bfd_section (info);
2058
2059   /* If the section has relocations, we must read it ourselves.
2060      Otherwise we attach it to the BFD.  */
2061   if ((sectp->flags & SEC_RELOC) == 0)
2062     {
2063       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2064       return;
2065     }
2066
2067   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
2068   info->buffer = buf;
2069
2070   /* When debugging .o files, we may need to apply relocations; see
2071      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2072      We never compress sections in .o files, so we only need to
2073      try this when the section is not compressed.  */
2074   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2075   if (retbuf != NULL)
2076     {
2077       info->buffer = retbuf;
2078       return;
2079     }
2080
2081   abfd = get_section_bfd_owner (info);
2082   gdb_assert (abfd != NULL);
2083
2084   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2085       || bfd_bread (buf, info->size, abfd) != info->size)
2086     {
2087       error (_("Dwarf Error: Can't read DWARF data"
2088                " in section %s [in module %s]"),
2089              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2090     }
2091 }
2092
2093 /* A helper function that returns the size of a section in a safe way.
2094    If you are positive that the section has been read before using the
2095    size, then it is safe to refer to the dwarf2_section_info object's
2096    "size" field directly.  In other cases, you must call this
2097    function, because for compressed sections the size field is not set
2098    correctly until the section has been read.  */
2099
2100 static bfd_size_type
2101 dwarf2_section_size (struct objfile *objfile,
2102                      struct dwarf2_section_info *info)
2103 {
2104   if (!info->readin)
2105     dwarf2_read_section (objfile, info);
2106   return info->size;
2107 }
2108
2109 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2110    SECTION_NAME.  */
2111
2112 void
2113 dwarf2_get_section_info (struct objfile *objfile,
2114                          enum dwarf2_section_enum sect,
2115                          asection **sectp, const gdb_byte **bufp,
2116                          bfd_size_type *sizep)
2117 {
2118   struct dwarf2_per_objfile *data
2119     = objfile_data (objfile, dwarf2_objfile_data_key);
2120   struct dwarf2_section_info *info;
2121
2122   /* We may see an objfile without any DWARF, in which case we just
2123      return nothing.  */
2124   if (data == NULL)
2125     {
2126       *sectp = NULL;
2127       *bufp = NULL;
2128       *sizep = 0;
2129       return;
2130     }
2131   switch (sect)
2132     {
2133     case DWARF2_DEBUG_FRAME:
2134       info = &data->frame;
2135       break;
2136     case DWARF2_EH_FRAME:
2137       info = &data->eh_frame;
2138       break;
2139     default:
2140       gdb_assert_not_reached ("unexpected section");
2141     }
2142
2143   dwarf2_read_section (objfile, info);
2144
2145   *sectp = get_section_bfd_section (info);
2146   *bufp = info->buffer;
2147   *sizep = info->size;
2148 }
2149
2150 /* A helper function to find the sections for a .dwz file.  */
2151
2152 static void
2153 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2154 {
2155   struct dwz_file *dwz_file = arg;
2156
2157   /* Note that we only support the standard ELF names, because .dwz
2158      is ELF-only (at the time of writing).  */
2159   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2160     {
2161       dwz_file->abbrev.asection = sectp;
2162       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2163     }
2164   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2165     {
2166       dwz_file->info.asection = sectp;
2167       dwz_file->info.size = bfd_get_section_size (sectp);
2168     }
2169   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2170     {
2171       dwz_file->str.asection = sectp;
2172       dwz_file->str.size = bfd_get_section_size (sectp);
2173     }
2174   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2175     {
2176       dwz_file->line.asection = sectp;
2177       dwz_file->line.size = bfd_get_section_size (sectp);
2178     }
2179   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2180     {
2181       dwz_file->macro.asection = sectp;
2182       dwz_file->macro.size = bfd_get_section_size (sectp);
2183     }
2184   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2185     {
2186       dwz_file->gdb_index.asection = sectp;
2187       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2188     }
2189 }
2190
2191 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2192    there is no .gnu_debugaltlink section in the file.  Error if there
2193    is such a section but the file cannot be found.  */
2194
2195 static struct dwz_file *
2196 dwarf2_get_dwz_file (void)
2197 {
2198   bfd *dwz_bfd;
2199   char *data;
2200   struct cleanup *cleanup;
2201   const char *filename;
2202   struct dwz_file *result;
2203   unsigned long buildid;
2204
2205   if (dwarf2_per_objfile->dwz_file != NULL)
2206     return dwarf2_per_objfile->dwz_file;
2207
2208   bfd_set_error (bfd_error_no_error);
2209   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2210                                       &buildid);
2211   if (data == NULL)
2212     {
2213       if (bfd_get_error () == bfd_error_no_error)
2214         return NULL;
2215       error (_("could not read '.gnu_debugaltlink' section: %s"),
2216              bfd_errmsg (bfd_get_error ()));
2217     }
2218   cleanup = make_cleanup (xfree, data);
2219
2220   filename = (const char *) data;
2221   if (!IS_ABSOLUTE_PATH (filename))
2222     {
2223       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2224       char *rel;
2225
2226       make_cleanup (xfree, abs);
2227       abs = ldirname (abs);
2228       make_cleanup (xfree, abs);
2229
2230       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2231       make_cleanup (xfree, rel);
2232       filename = rel;
2233     }
2234
2235   /* The format is just a NUL-terminated file name, followed by the
2236      build-id.  For now, though, we ignore the build-id.  */
2237   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2238   if (dwz_bfd == NULL)
2239     error (_("could not read '%s': %s"), filename,
2240            bfd_errmsg (bfd_get_error ()));
2241
2242   if (!bfd_check_format (dwz_bfd, bfd_object))
2243     {
2244       gdb_bfd_unref (dwz_bfd);
2245       error (_("file '%s' was not usable: %s"), filename,
2246              bfd_errmsg (bfd_get_error ()));
2247     }
2248
2249   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2250                            struct dwz_file);
2251   result->dwz_bfd = dwz_bfd;
2252
2253   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2254
2255   do_cleanups (cleanup);
2256
2257   dwarf2_per_objfile->dwz_file = result;
2258   return result;
2259 }
2260 \f
2261 /* DWARF quick_symbols_functions support.  */
2262
2263 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2264    unique line tables, so we maintain a separate table of all .debug_line
2265    derived entries to support the sharing.
2266    All the quick functions need is the list of file names.  We discard the
2267    line_header when we're done and don't need to record it here.  */
2268 struct quick_file_names
2269 {
2270   /* The data used to construct the hash key.  */
2271   struct stmt_list_hash hash;
2272
2273   /* The number of entries in file_names, real_names.  */
2274   unsigned int num_file_names;
2275
2276   /* The file names from the line table, after being run through
2277      file_full_name.  */
2278   const char **file_names;
2279
2280   /* The file names from the line table after being run through
2281      gdb_realpath.  These are computed lazily.  */
2282   const char **real_names;
2283 };
2284
2285 /* When using the index (and thus not using psymtabs), each CU has an
2286    object of this type.  This is used to hold information needed by
2287    the various "quick" methods.  */
2288 struct dwarf2_per_cu_quick_data
2289 {
2290   /* The file table.  This can be NULL if there was no file table
2291      or it's currently not read in.
2292      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2293   struct quick_file_names *file_names;
2294
2295   /* The corresponding symbol table.  This is NULL if symbols for this
2296      CU have not yet been read.  */
2297   struct symtab *symtab;
2298
2299   /* A temporary mark bit used when iterating over all CUs in
2300      expand_symtabs_matching.  */
2301   unsigned int mark : 1;
2302
2303   /* True if we've tried to read the file table and found there isn't one.
2304      There will be no point in trying to read it again next time.  */
2305   unsigned int no_file_data : 1;
2306 };
2307
2308 /* Utility hash function for a stmt_list_hash.  */
2309
2310 static hashval_t
2311 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2312 {
2313   hashval_t v = 0;
2314
2315   if (stmt_list_hash->dwo_unit != NULL)
2316     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2317   v += stmt_list_hash->line_offset.sect_off;
2318   return v;
2319 }
2320
2321 /* Utility equality function for a stmt_list_hash.  */
2322
2323 static int
2324 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2325                     const struct stmt_list_hash *rhs)
2326 {
2327   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2328     return 0;
2329   if (lhs->dwo_unit != NULL
2330       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2331     return 0;
2332
2333   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2334 }
2335
2336 /* Hash function for a quick_file_names.  */
2337
2338 static hashval_t
2339 hash_file_name_entry (const void *e)
2340 {
2341   const struct quick_file_names *file_data = e;
2342
2343   return hash_stmt_list_entry (&file_data->hash);
2344 }
2345
2346 /* Equality function for a quick_file_names.  */
2347
2348 static int
2349 eq_file_name_entry (const void *a, const void *b)
2350 {
2351   const struct quick_file_names *ea = a;
2352   const struct quick_file_names *eb = b;
2353
2354   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2355 }
2356
2357 /* Delete function for a quick_file_names.  */
2358
2359 static void
2360 delete_file_name_entry (void *e)
2361 {
2362   struct quick_file_names *file_data = e;
2363   int i;
2364
2365   for (i = 0; i < file_data->num_file_names; ++i)
2366     {
2367       xfree ((void*) file_data->file_names[i]);
2368       if (file_data->real_names)
2369         xfree ((void*) file_data->real_names[i]);
2370     }
2371
2372   /* The space for the struct itself lives on objfile_obstack,
2373      so we don't free it here.  */
2374 }
2375
2376 /* Create a quick_file_names hash table.  */
2377
2378 static htab_t
2379 create_quick_file_names_table (unsigned int nr_initial_entries)
2380 {
2381   return htab_create_alloc (nr_initial_entries,
2382                             hash_file_name_entry, eq_file_name_entry,
2383                             delete_file_name_entry, xcalloc, xfree);
2384 }
2385
2386 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2387    have to be created afterwards.  You should call age_cached_comp_units after
2388    processing PER_CU->CU.  dw2_setup must have been already called.  */
2389
2390 static void
2391 load_cu (struct dwarf2_per_cu_data *per_cu)
2392 {
2393   if (per_cu->is_debug_types)
2394     load_full_type_unit (per_cu);
2395   else
2396     load_full_comp_unit (per_cu, language_minimal);
2397
2398   gdb_assert (per_cu->cu != NULL);
2399
2400   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2401 }
2402
2403 /* Read in the symbols for PER_CU.  */
2404
2405 static void
2406 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2407 {
2408   struct cleanup *back_to;
2409
2410   /* Skip type_unit_groups, reading the type units they contain
2411      is handled elsewhere.  */
2412   if (IS_TYPE_UNIT_GROUP (per_cu))
2413     return;
2414
2415   back_to = make_cleanup (dwarf2_release_queue, NULL);
2416
2417   if (dwarf2_per_objfile->using_index
2418       ? per_cu->v.quick->symtab == NULL
2419       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2420     {
2421       queue_comp_unit (per_cu, language_minimal);
2422       load_cu (per_cu);
2423
2424       /* If we just loaded a CU from a DWO, and we're working with an index
2425          that may badly handle TUs, load all the TUs in that DWO as well.
2426          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2427       if (!per_cu->is_debug_types
2428           && per_cu->cu->dwo_unit != NULL
2429           && dwarf2_per_objfile->index_table != NULL
2430           && dwarf2_per_objfile->index_table->version <= 7
2431           /* DWP files aren't supported yet.  */
2432           && get_dwp_file () == NULL)
2433         queue_and_load_all_dwo_tus (per_cu);
2434     }
2435
2436   process_queue ();
2437
2438   /* Age the cache, releasing compilation units that have not
2439      been used recently.  */
2440   age_cached_comp_units ();
2441
2442   do_cleanups (back_to);
2443 }
2444
2445 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2446    the objfile from which this CU came.  Returns the resulting symbol
2447    table.  */
2448
2449 static struct symtab *
2450 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2451 {
2452   gdb_assert (dwarf2_per_objfile->using_index);
2453   if (!per_cu->v.quick->symtab)
2454     {
2455       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2456       increment_reading_symtab ();
2457       dw2_do_instantiate_symtab (per_cu);
2458       process_cu_includes ();
2459       do_cleanups (back_to);
2460     }
2461   return per_cu->v.quick->symtab;
2462 }
2463
2464 /* Return the CU given its index.
2465
2466    This is intended for loops like:
2467
2468    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2469                     + dwarf2_per_objfile->n_type_units); ++i)
2470      {
2471        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2472
2473        ...;
2474      }
2475 */
2476
2477 static struct dwarf2_per_cu_data *
2478 dw2_get_cu (int index)
2479 {
2480   if (index >= dwarf2_per_objfile->n_comp_units)
2481     {
2482       index -= dwarf2_per_objfile->n_comp_units;
2483       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2484       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2485     }
2486
2487   return dwarf2_per_objfile->all_comp_units[index];
2488 }
2489
2490 /* Return the primary CU given its index.
2491    The difference between this function and dw2_get_cu is in the handling
2492    of type units (TUs).  Here we return the type_unit_group object.
2493
2494    This is intended for loops like:
2495
2496    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2497                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2498      {
2499        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2500
2501        ...;
2502      }
2503 */
2504
2505 static struct dwarf2_per_cu_data *
2506 dw2_get_primary_cu (int index)
2507 {
2508   if (index >= dwarf2_per_objfile->n_comp_units)
2509     {
2510       index -= dwarf2_per_objfile->n_comp_units;
2511       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2512       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2513     }
2514
2515   return dwarf2_per_objfile->all_comp_units[index];
2516 }
2517
2518 /* A helper for create_cus_from_index that handles a given list of
2519    CUs.  */
2520
2521 static void
2522 create_cus_from_index_list (struct objfile *objfile,
2523                             const gdb_byte *cu_list, offset_type n_elements,
2524                             struct dwarf2_section_info *section,
2525                             int is_dwz,
2526                             int base_offset)
2527 {
2528   offset_type i;
2529
2530   for (i = 0; i < n_elements; i += 2)
2531     {
2532       struct dwarf2_per_cu_data *the_cu;
2533       ULONGEST offset, length;
2534
2535       gdb_static_assert (sizeof (ULONGEST) >= 8);
2536       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2537       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2538       cu_list += 2 * 8;
2539
2540       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2541                                struct dwarf2_per_cu_data);
2542       the_cu->offset.sect_off = offset;
2543       the_cu->length = length;
2544       the_cu->objfile = objfile;
2545       the_cu->section = section;
2546       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2547                                         struct dwarf2_per_cu_quick_data);
2548       the_cu->is_dwz = is_dwz;
2549       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2550     }
2551 }
2552
2553 /* Read the CU list from the mapped index, and use it to create all
2554    the CU objects for this objfile.  */
2555
2556 static void
2557 create_cus_from_index (struct objfile *objfile,
2558                        const gdb_byte *cu_list, offset_type cu_list_elements,
2559                        const gdb_byte *dwz_list, offset_type dwz_elements)
2560 {
2561   struct dwz_file *dwz;
2562
2563   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2564   dwarf2_per_objfile->all_comp_units
2565     = obstack_alloc (&objfile->objfile_obstack,
2566                      dwarf2_per_objfile->n_comp_units
2567                      * sizeof (struct dwarf2_per_cu_data *));
2568
2569   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2570                               &dwarf2_per_objfile->info, 0, 0);
2571
2572   if (dwz_elements == 0)
2573     return;
2574
2575   dwz = dwarf2_get_dwz_file ();
2576   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2577                               cu_list_elements / 2);
2578 }
2579
2580 /* Create the signatured type hash table from the index.  */
2581
2582 static void
2583 create_signatured_type_table_from_index (struct objfile *objfile,
2584                                          struct dwarf2_section_info *section,
2585                                          const gdb_byte *bytes,
2586                                          offset_type elements)
2587 {
2588   offset_type i;
2589   htab_t sig_types_hash;
2590
2591   dwarf2_per_objfile->n_type_units = elements / 3;
2592   dwarf2_per_objfile->all_type_units
2593     = xmalloc (dwarf2_per_objfile->n_type_units
2594                * sizeof (struct signatured_type *));
2595
2596   sig_types_hash = allocate_signatured_type_table (objfile);
2597
2598   for (i = 0; i < elements; i += 3)
2599     {
2600       struct signatured_type *sig_type;
2601       ULONGEST offset, type_offset_in_tu, signature;
2602       void **slot;
2603
2604       gdb_static_assert (sizeof (ULONGEST) >= 8);
2605       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2606       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2607                                                     BFD_ENDIAN_LITTLE);
2608       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2609       bytes += 3 * 8;
2610
2611       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2612                                  struct signatured_type);
2613       sig_type->signature = signature;
2614       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2615       sig_type->per_cu.is_debug_types = 1;
2616       sig_type->per_cu.section = section;
2617       sig_type->per_cu.offset.sect_off = offset;
2618       sig_type->per_cu.objfile = objfile;
2619       sig_type->per_cu.v.quick
2620         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2621                           struct dwarf2_per_cu_quick_data);
2622
2623       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2624       *slot = sig_type;
2625
2626       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2627     }
2628
2629   dwarf2_per_objfile->signatured_types = sig_types_hash;
2630 }
2631
2632 /* Read the address map data from the mapped index, and use it to
2633    populate the objfile's psymtabs_addrmap.  */
2634
2635 static void
2636 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2637 {
2638   const gdb_byte *iter, *end;
2639   struct obstack temp_obstack;
2640   struct addrmap *mutable_map;
2641   struct cleanup *cleanup;
2642   CORE_ADDR baseaddr;
2643
2644   obstack_init (&temp_obstack);
2645   cleanup = make_cleanup_obstack_free (&temp_obstack);
2646   mutable_map = addrmap_create_mutable (&temp_obstack);
2647
2648   iter = index->address_table;
2649   end = iter + index->address_table_size;
2650
2651   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2652
2653   while (iter < end)
2654     {
2655       ULONGEST hi, lo, cu_index;
2656       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2657       iter += 8;
2658       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2659       iter += 8;
2660       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2661       iter += 4;
2662
2663       if (lo > hi)
2664         {
2665           complaint (&symfile_complaints,
2666                      _(".gdb_index address table has invalid range (%s - %s)"),
2667                      hex_string (lo), hex_string (hi));
2668           continue;
2669         }
2670
2671       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2672         {
2673           complaint (&symfile_complaints,
2674                      _(".gdb_index address table has invalid CU number %u"),
2675                      (unsigned) cu_index);
2676           continue;
2677         }
2678
2679       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2680                          dw2_get_cu (cu_index));
2681     }
2682
2683   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2684                                                     &objfile->objfile_obstack);
2685   do_cleanups (cleanup);
2686 }
2687
2688 /* The hash function for strings in the mapped index.  This is the same as
2689    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2690    implementation.  This is necessary because the hash function is tied to the
2691    format of the mapped index file.  The hash values do not have to match with
2692    SYMBOL_HASH_NEXT.
2693    
2694    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2695
2696 static hashval_t
2697 mapped_index_string_hash (int index_version, const void *p)
2698 {
2699   const unsigned char *str = (const unsigned char *) p;
2700   hashval_t r = 0;
2701   unsigned char c;
2702
2703   while ((c = *str++) != 0)
2704     {
2705       if (index_version >= 5)
2706         c = tolower (c);
2707       r = r * 67 + c - 113;
2708     }
2709
2710   return r;
2711 }
2712
2713 /* Find a slot in the mapped index INDEX for the object named NAME.
2714    If NAME is found, set *VEC_OUT to point to the CU vector in the
2715    constant pool and return 1.  If NAME cannot be found, return 0.  */
2716
2717 static int
2718 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2719                           offset_type **vec_out)
2720 {
2721   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2722   offset_type hash;
2723   offset_type slot, step;
2724   int (*cmp) (const char *, const char *);
2725
2726   if (current_language->la_language == language_cplus
2727       || current_language->la_language == language_java
2728       || current_language->la_language == language_fortran)
2729     {
2730       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2731          not contain any.  */
2732       const char *paren = strchr (name, '(');
2733
2734       if (paren)
2735         {
2736           char *dup;
2737
2738           dup = xmalloc (paren - name + 1);
2739           memcpy (dup, name, paren - name);
2740           dup[paren - name] = 0;
2741
2742           make_cleanup (xfree, dup);
2743           name = dup;
2744         }
2745     }
2746
2747   /* Index version 4 did not support case insensitive searches.  But the
2748      indices for case insensitive languages are built in lowercase, therefore
2749      simulate our NAME being searched is also lowercased.  */
2750   hash = mapped_index_string_hash ((index->version == 4
2751                                     && case_sensitivity == case_sensitive_off
2752                                     ? 5 : index->version),
2753                                    name);
2754
2755   slot = hash & (index->symbol_table_slots - 1);
2756   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2757   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2758
2759   for (;;)
2760     {
2761       /* Convert a slot number to an offset into the table.  */
2762       offset_type i = 2 * slot;
2763       const char *str;
2764       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2765         {
2766           do_cleanups (back_to);
2767           return 0;
2768         }
2769
2770       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2771       if (!cmp (name, str))
2772         {
2773           *vec_out = (offset_type *) (index->constant_pool
2774                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2775           do_cleanups (back_to);
2776           return 1;
2777         }
2778
2779       slot = (slot + step) & (index->symbol_table_slots - 1);
2780     }
2781 }
2782
2783 /* A helper function that reads the .gdb_index from SECTION and fills
2784    in MAP.  FILENAME is the name of the file containing the section;
2785    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2786    ok to use deprecated sections.
2787
2788    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2789    out parameters that are filled in with information about the CU and
2790    TU lists in the section.
2791
2792    Returns 1 if all went well, 0 otherwise.  */
2793
2794 static int
2795 read_index_from_section (struct objfile *objfile,
2796                          const char *filename,
2797                          int deprecated_ok,
2798                          struct dwarf2_section_info *section,
2799                          struct mapped_index *map,
2800                          const gdb_byte **cu_list,
2801                          offset_type *cu_list_elements,
2802                          const gdb_byte **types_list,
2803                          offset_type *types_list_elements)
2804 {
2805   const gdb_byte *addr;
2806   offset_type version;
2807   offset_type *metadata;
2808   int i;
2809
2810   if (dwarf2_section_empty_p (section))
2811     return 0;
2812
2813   /* Older elfutils strip versions could keep the section in the main
2814      executable while splitting it for the separate debug info file.  */
2815   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
2816     return 0;
2817
2818   dwarf2_read_section (objfile, section);
2819
2820   addr = section->buffer;
2821   /* Version check.  */
2822   version = MAYBE_SWAP (*(offset_type *) addr);
2823   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2824      causes the index to behave very poorly for certain requests.  Version 3
2825      contained incomplete addrmap.  So, it seems better to just ignore such
2826      indices.  */
2827   if (version < 4)
2828     {
2829       static int warning_printed = 0;
2830       if (!warning_printed)
2831         {
2832           warning (_("Skipping obsolete .gdb_index section in %s."),
2833                    filename);
2834           warning_printed = 1;
2835         }
2836       return 0;
2837     }
2838   /* Index version 4 uses a different hash function than index version
2839      5 and later.
2840
2841      Versions earlier than 6 did not emit psymbols for inlined
2842      functions.  Using these files will cause GDB not to be able to
2843      set breakpoints on inlined functions by name, so we ignore these
2844      indices unless the user has done
2845      "set use-deprecated-index-sections on".  */
2846   if (version < 6 && !deprecated_ok)
2847     {
2848       static int warning_printed = 0;
2849       if (!warning_printed)
2850         {
2851           warning (_("\
2852 Skipping deprecated .gdb_index section in %s.\n\
2853 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2854 to use the section anyway."),
2855                    filename);
2856           warning_printed = 1;
2857         }
2858       return 0;
2859     }
2860   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2861      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2862      we can't distinguish gdb-generated indices from gold-generated ones, so
2863      nothing to do here.  */
2864
2865   /* Indexes with higher version than the one supported by GDB may be no
2866      longer backward compatible.  */
2867   if (version > 8)
2868     return 0;
2869
2870   map->version = version;
2871   map->total_size = section->size;
2872
2873   metadata = (offset_type *) (addr + sizeof (offset_type));
2874
2875   i = 0;
2876   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2877   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2878                        / 8);
2879   ++i;
2880
2881   *types_list = addr + MAYBE_SWAP (metadata[i]);
2882   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2883                            - MAYBE_SWAP (metadata[i]))
2884                           / 8);
2885   ++i;
2886
2887   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2888   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2889                              - MAYBE_SWAP (metadata[i]));
2890   ++i;
2891
2892   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2893   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2894                               - MAYBE_SWAP (metadata[i]))
2895                              / (2 * sizeof (offset_type)));
2896   ++i;
2897
2898   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2899
2900   return 1;
2901 }
2902
2903
2904 /* Read the index file.  If everything went ok, initialize the "quick"
2905    elements of all the CUs and return 1.  Otherwise, return 0.  */
2906
2907 static int
2908 dwarf2_read_index (struct objfile *objfile)
2909 {
2910   struct mapped_index local_map, *map;
2911   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2912   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2913   struct dwz_file *dwz;
2914
2915   if (!read_index_from_section (objfile, objfile_name (objfile),
2916                                 use_deprecated_index_sections,
2917                                 &dwarf2_per_objfile->gdb_index, &local_map,
2918                                 &cu_list, &cu_list_elements,
2919                                 &types_list, &types_list_elements))
2920     return 0;
2921
2922   /* Don't use the index if it's empty.  */
2923   if (local_map.symbol_table_slots == 0)
2924     return 0;
2925
2926   /* If there is a .dwz file, read it so we can get its CU list as
2927      well.  */
2928   dwz = dwarf2_get_dwz_file ();
2929   if (dwz != NULL)
2930     {
2931       struct mapped_index dwz_map;
2932       const gdb_byte *dwz_types_ignore;
2933       offset_type dwz_types_elements_ignore;
2934
2935       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2936                                     1,
2937                                     &dwz->gdb_index, &dwz_map,
2938                                     &dwz_list, &dwz_list_elements,
2939                                     &dwz_types_ignore,
2940                                     &dwz_types_elements_ignore))
2941         {
2942           warning (_("could not read '.gdb_index' section from %s; skipping"),
2943                    bfd_get_filename (dwz->dwz_bfd));
2944           return 0;
2945         }
2946     }
2947
2948   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2949                          dwz_list_elements);
2950
2951   if (types_list_elements)
2952     {
2953       struct dwarf2_section_info *section;
2954
2955       /* We can only handle a single .debug_types when we have an
2956          index.  */
2957       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2958         return 0;
2959
2960       section = VEC_index (dwarf2_section_info_def,
2961                            dwarf2_per_objfile->types, 0);
2962
2963       create_signatured_type_table_from_index (objfile, section, types_list,
2964                                                types_list_elements);
2965     }
2966
2967   create_addrmap_from_index (objfile, &local_map);
2968
2969   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2970   *map = local_map;
2971
2972   dwarf2_per_objfile->index_table = map;
2973   dwarf2_per_objfile->using_index = 1;
2974   dwarf2_per_objfile->quick_file_names_table =
2975     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2976
2977   return 1;
2978 }
2979
2980 /* A helper for the "quick" functions which sets the global
2981    dwarf2_per_objfile according to OBJFILE.  */
2982
2983 static void
2984 dw2_setup (struct objfile *objfile)
2985 {
2986   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2987   gdb_assert (dwarf2_per_objfile);
2988 }
2989
2990 /* die_reader_func for dw2_get_file_names.  */
2991
2992 static void
2993 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2994                            const gdb_byte *info_ptr,
2995                            struct die_info *comp_unit_die,
2996                            int has_children,
2997                            void *data)
2998 {
2999   struct dwarf2_cu *cu = reader->cu;
3000   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3001   struct objfile *objfile = dwarf2_per_objfile->objfile;
3002   struct dwarf2_per_cu_data *lh_cu;
3003   struct line_header *lh;
3004   struct attribute *attr;
3005   int i;
3006   const char *name, *comp_dir;
3007   void **slot;
3008   struct quick_file_names *qfn;
3009   unsigned int line_offset;
3010
3011   gdb_assert (! this_cu->is_debug_types);
3012
3013   /* Our callers never want to match partial units -- instead they
3014      will match the enclosing full CU.  */
3015   if (comp_unit_die->tag == DW_TAG_partial_unit)
3016     {
3017       this_cu->v.quick->no_file_data = 1;
3018       return;
3019     }
3020
3021   lh_cu = this_cu;
3022   lh = NULL;
3023   slot = NULL;
3024   line_offset = 0;
3025
3026   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3027   if (attr)
3028     {
3029       struct quick_file_names find_entry;
3030
3031       line_offset = DW_UNSND (attr);
3032
3033       /* We may have already read in this line header (TU line header sharing).
3034          If we have we're done.  */
3035       find_entry.hash.dwo_unit = cu->dwo_unit;
3036       find_entry.hash.line_offset.sect_off = line_offset;
3037       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3038                              &find_entry, INSERT);
3039       if (*slot != NULL)
3040         {
3041           lh_cu->v.quick->file_names = *slot;
3042           return;
3043         }
3044
3045       lh = dwarf_decode_line_header (line_offset, cu);
3046     }
3047   if (lh == NULL)
3048     {
3049       lh_cu->v.quick->no_file_data = 1;
3050       return;
3051     }
3052
3053   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
3054   qfn->hash.dwo_unit = cu->dwo_unit;
3055   qfn->hash.line_offset.sect_off = line_offset;
3056   gdb_assert (slot != NULL);
3057   *slot = qfn;
3058
3059   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
3060
3061   qfn->num_file_names = lh->num_file_names;
3062   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
3063                                    lh->num_file_names * sizeof (char *));
3064   for (i = 0; i < lh->num_file_names; ++i)
3065     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
3066   qfn->real_names = NULL;
3067
3068   free_line_header (lh);
3069
3070   lh_cu->v.quick->file_names = qfn;
3071 }
3072
3073 /* A helper for the "quick" functions which attempts to read the line
3074    table for THIS_CU.  */
3075
3076 static struct quick_file_names *
3077 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3078 {
3079   /* This should never be called for TUs.  */
3080   gdb_assert (! this_cu->is_debug_types);
3081   /* Nor type unit groups.  */
3082   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3083
3084   if (this_cu->v.quick->file_names != NULL)
3085     return this_cu->v.quick->file_names;
3086   /* If we know there is no line data, no point in looking again.  */
3087   if (this_cu->v.quick->no_file_data)
3088     return NULL;
3089
3090   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3091
3092   if (this_cu->v.quick->no_file_data)
3093     return NULL;
3094   return this_cu->v.quick->file_names;
3095 }
3096
3097 /* A helper for the "quick" functions which computes and caches the
3098    real path for a given file name from the line table.  */
3099
3100 static const char *
3101 dw2_get_real_path (struct objfile *objfile,
3102                    struct quick_file_names *qfn, int index)
3103 {
3104   if (qfn->real_names == NULL)
3105     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3106                                       qfn->num_file_names, sizeof (char *));
3107
3108   if (qfn->real_names[index] == NULL)
3109     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3110
3111   return qfn->real_names[index];
3112 }
3113
3114 static struct symtab *
3115 dw2_find_last_source_symtab (struct objfile *objfile)
3116 {
3117   int index;
3118
3119   dw2_setup (objfile);
3120   index = dwarf2_per_objfile->n_comp_units - 1;
3121   return dw2_instantiate_symtab (dw2_get_cu (index));
3122 }
3123
3124 /* Traversal function for dw2_forget_cached_source_info.  */
3125
3126 static int
3127 dw2_free_cached_file_names (void **slot, void *info)
3128 {
3129   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3130
3131   if (file_data->real_names)
3132     {
3133       int i;
3134
3135       for (i = 0; i < file_data->num_file_names; ++i)
3136         {
3137           xfree ((void*) file_data->real_names[i]);
3138           file_data->real_names[i] = NULL;
3139         }
3140     }
3141
3142   return 1;
3143 }
3144
3145 static void
3146 dw2_forget_cached_source_info (struct objfile *objfile)
3147 {
3148   dw2_setup (objfile);
3149
3150   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3151                           dw2_free_cached_file_names, NULL);
3152 }
3153
3154 /* Helper function for dw2_map_symtabs_matching_filename that expands
3155    the symtabs and calls the iterator.  */
3156
3157 static int
3158 dw2_map_expand_apply (struct objfile *objfile,
3159                       struct dwarf2_per_cu_data *per_cu,
3160                       const char *name, const char *real_path,
3161                       int (*callback) (struct symtab *, void *),
3162                       void *data)
3163 {
3164   struct symtab *last_made = objfile->symtabs;
3165
3166   /* Don't visit already-expanded CUs.  */
3167   if (per_cu->v.quick->symtab)
3168     return 0;
3169
3170   /* This may expand more than one symtab, and we want to iterate over
3171      all of them.  */
3172   dw2_instantiate_symtab (per_cu);
3173
3174   return iterate_over_some_symtabs (name, real_path, callback, data,
3175                                     objfile->symtabs, last_made);
3176 }
3177
3178 /* Implementation of the map_symtabs_matching_filename method.  */
3179
3180 static int
3181 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3182                                    const char *real_path,
3183                                    int (*callback) (struct symtab *, void *),
3184                                    void *data)
3185 {
3186   int i;
3187   const char *name_basename = lbasename (name);
3188
3189   dw2_setup (objfile);
3190
3191   /* The rule is CUs specify all the files, including those used by
3192      any TU, so there's no need to scan TUs here.  */
3193
3194   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3195     {
3196       int j;
3197       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3198       struct quick_file_names *file_data;
3199
3200       /* We only need to look at symtabs not already expanded.  */
3201       if (per_cu->v.quick->symtab)
3202         continue;
3203
3204       file_data = dw2_get_file_names (per_cu);
3205       if (file_data == NULL)
3206         continue;
3207
3208       for (j = 0; j < file_data->num_file_names; ++j)
3209         {
3210           const char *this_name = file_data->file_names[j];
3211           const char *this_real_name;
3212
3213           if (compare_filenames_for_search (this_name, name))
3214             {
3215               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3216                                         callback, data))
3217                 return 1;
3218               continue;
3219             }
3220
3221           /* Before we invoke realpath, which can get expensive when many
3222              files are involved, do a quick comparison of the basenames.  */
3223           if (! basenames_may_differ
3224               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3225             continue;
3226
3227           this_real_name = dw2_get_real_path (objfile, file_data, j);
3228           if (compare_filenames_for_search (this_real_name, name))
3229             {
3230               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3231                                         callback, data))
3232                 return 1;
3233               continue;
3234             }
3235
3236           if (real_path != NULL)
3237             {
3238               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3239               gdb_assert (IS_ABSOLUTE_PATH (name));
3240               if (this_real_name != NULL
3241                   && FILENAME_CMP (real_path, this_real_name) == 0)
3242                 {
3243                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3244                                             callback, data))
3245                     return 1;
3246                   continue;
3247                 }
3248             }
3249         }
3250     }
3251
3252   return 0;
3253 }
3254
3255 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3256
3257 struct dw2_symtab_iterator
3258 {
3259   /* The internalized form of .gdb_index.  */
3260   struct mapped_index *index;
3261   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3262   int want_specific_block;
3263   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3264      Unused if !WANT_SPECIFIC_BLOCK.  */
3265   int block_index;
3266   /* The kind of symbol we're looking for.  */
3267   domain_enum domain;
3268   /* The list of CUs from the index entry of the symbol,
3269      or NULL if not found.  */
3270   offset_type *vec;
3271   /* The next element in VEC to look at.  */
3272   int next;
3273   /* The number of elements in VEC, or zero if there is no match.  */
3274   int length;
3275 };
3276
3277 /* Initialize the index symtab iterator ITER.
3278    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3279    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3280
3281 static void
3282 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3283                       struct mapped_index *index,
3284                       int want_specific_block,
3285                       int block_index,
3286                       domain_enum domain,
3287                       const char *name)
3288 {
3289   iter->index = index;
3290   iter->want_specific_block = want_specific_block;
3291   iter->block_index = block_index;
3292   iter->domain = domain;
3293   iter->next = 0;
3294
3295   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3296     iter->length = MAYBE_SWAP (*iter->vec);
3297   else
3298     {
3299       iter->vec = NULL;
3300       iter->length = 0;
3301     }
3302 }
3303
3304 /* Return the next matching CU or NULL if there are no more.  */
3305
3306 static struct dwarf2_per_cu_data *
3307 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3308 {
3309   for ( ; iter->next < iter->length; ++iter->next)
3310     {
3311       offset_type cu_index_and_attrs =
3312         MAYBE_SWAP (iter->vec[iter->next + 1]);
3313       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3314       struct dwarf2_per_cu_data *per_cu;
3315       int want_static = iter->block_index != GLOBAL_BLOCK;
3316       /* This value is only valid for index versions >= 7.  */
3317       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3318       gdb_index_symbol_kind symbol_kind =
3319         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3320       /* Only check the symbol attributes if they're present.
3321          Indices prior to version 7 don't record them,
3322          and indices >= 7 may elide them for certain symbols
3323          (gold does this).  */
3324       int attrs_valid =
3325         (iter->index->version >= 7
3326          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3327
3328       /* Don't crash on bad data.  */
3329       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3330                        + dwarf2_per_objfile->n_type_units))
3331         {
3332           complaint (&symfile_complaints,
3333                      _(".gdb_index entry has bad CU index"
3334                        " [in module %s]"),
3335                      objfile_name (dwarf2_per_objfile->objfile));
3336           continue;
3337         }
3338
3339       per_cu = dw2_get_cu (cu_index);
3340
3341       /* Skip if already read in.  */
3342       if (per_cu->v.quick->symtab)
3343         continue;
3344
3345       if (attrs_valid
3346           && iter->want_specific_block
3347           && want_static != is_static)
3348         continue;
3349
3350       /* Only check the symbol's kind if it has one.  */
3351       if (attrs_valid)
3352         {
3353           switch (iter->domain)
3354             {
3355             case VAR_DOMAIN:
3356               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3357                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3358                   /* Some types are also in VAR_DOMAIN.  */
3359                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3360                 continue;
3361               break;
3362             case STRUCT_DOMAIN:
3363               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3364                 continue;
3365               break;
3366             case LABEL_DOMAIN:
3367               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3368                 continue;
3369               break;
3370             default:
3371               break;
3372             }
3373         }
3374
3375       ++iter->next;
3376       return per_cu;
3377     }
3378
3379   return NULL;
3380 }
3381
3382 static struct symtab *
3383 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3384                    const char *name, domain_enum domain)
3385 {
3386   struct symtab *stab_best = NULL;
3387   struct mapped_index *index;
3388
3389   dw2_setup (objfile);
3390
3391   index = dwarf2_per_objfile->index_table;
3392
3393   /* index is NULL if OBJF_READNOW.  */
3394   if (index)
3395     {
3396       struct dw2_symtab_iterator iter;
3397       struct dwarf2_per_cu_data *per_cu;
3398
3399       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3400
3401       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3402         {
3403           struct symbol *sym = NULL;
3404           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3405
3406           /* Some caution must be observed with overloaded functions
3407              and methods, since the index will not contain any overload
3408              information (but NAME might contain it).  */
3409           if (stab->primary)
3410             {
3411               struct blockvector *bv = BLOCKVECTOR (stab);
3412               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3413
3414               sym = lookup_block_symbol (block, name, domain);
3415             }
3416
3417           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3418             {
3419               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3420                 return stab;
3421
3422               stab_best = stab;
3423             }
3424
3425           /* Keep looking through other CUs.  */
3426         }
3427     }
3428
3429   return stab_best;
3430 }
3431
3432 static void
3433 dw2_print_stats (struct objfile *objfile)
3434 {
3435   int i, total, count;
3436
3437   dw2_setup (objfile);
3438   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3439   count = 0;
3440   for (i = 0; i < total; ++i)
3441     {
3442       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3443
3444       if (!per_cu->v.quick->symtab)
3445         ++count;
3446     }
3447   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3448   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3449 }
3450
3451 /* This dumps minimal information about the index.
3452    It is called via "mt print objfiles".
3453    One use is to verify .gdb_index has been loaded by the
3454    gdb.dwarf2/gdb-index.exp testcase.  */
3455
3456 static void
3457 dw2_dump (struct objfile *objfile)
3458 {
3459   dw2_setup (objfile);
3460   gdb_assert (dwarf2_per_objfile->using_index);
3461   printf_filtered (".gdb_index:");
3462   if (dwarf2_per_objfile->index_table != NULL)
3463     {
3464       printf_filtered (" version %d\n",
3465                        dwarf2_per_objfile->index_table->version);
3466     }
3467   else
3468     printf_filtered (" faked for \"readnow\"\n");
3469   printf_filtered ("\n");
3470 }
3471
3472 static void
3473 dw2_relocate (struct objfile *objfile,
3474               const struct section_offsets *new_offsets,
3475               const struct section_offsets *delta)
3476 {
3477   /* There's nothing to relocate here.  */
3478 }
3479
3480 static void
3481 dw2_expand_symtabs_for_function (struct objfile *objfile,
3482                                  const char *func_name)
3483 {
3484   struct mapped_index *index;
3485
3486   dw2_setup (objfile);
3487
3488   index = dwarf2_per_objfile->index_table;
3489
3490   /* index is NULL if OBJF_READNOW.  */
3491   if (index)
3492     {
3493       struct dw2_symtab_iterator iter;
3494       struct dwarf2_per_cu_data *per_cu;
3495
3496       /* Note: It doesn't matter what we pass for block_index here.  */
3497       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3498                             func_name);
3499
3500       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3501         dw2_instantiate_symtab (per_cu);
3502     }
3503 }
3504
3505 static void
3506 dw2_expand_all_symtabs (struct objfile *objfile)
3507 {
3508   int i;
3509
3510   dw2_setup (objfile);
3511
3512   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3513                    + dwarf2_per_objfile->n_type_units); ++i)
3514     {
3515       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3516
3517       dw2_instantiate_symtab (per_cu);
3518     }
3519 }
3520
3521 static void
3522 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3523                                   const char *fullname)
3524 {
3525   int i;
3526
3527   dw2_setup (objfile);
3528
3529   /* We don't need to consider type units here.
3530      This is only called for examining code, e.g. expand_line_sal.
3531      There can be an order of magnitude (or more) more type units
3532      than comp units, and we avoid them if we can.  */
3533
3534   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3535     {
3536       int j;
3537       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3538       struct quick_file_names *file_data;
3539
3540       /* We only need to look at symtabs not already expanded.  */
3541       if (per_cu->v.quick->symtab)
3542         continue;
3543
3544       file_data = dw2_get_file_names (per_cu);
3545       if (file_data == NULL)
3546         continue;
3547
3548       for (j = 0; j < file_data->num_file_names; ++j)
3549         {
3550           const char *this_fullname = file_data->file_names[j];
3551
3552           if (filename_cmp (this_fullname, fullname) == 0)
3553             {
3554               dw2_instantiate_symtab (per_cu);
3555               break;
3556             }
3557         }
3558     }
3559 }
3560
3561 static void
3562 dw2_map_matching_symbols (struct objfile *objfile,
3563                           const char * name, domain_enum namespace,
3564                           int global,
3565                           int (*callback) (struct block *,
3566                                            struct symbol *, void *),
3567                           void *data, symbol_compare_ftype *match,
3568                           symbol_compare_ftype *ordered_compare)
3569 {
3570   /* Currently unimplemented; used for Ada.  The function can be called if the
3571      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3572      does not look for non-Ada symbols this function should just return.  */
3573 }
3574
3575 static void
3576 dw2_expand_symtabs_matching
3577   (struct objfile *objfile,
3578    int (*file_matcher) (const char *, void *, int basenames),
3579    int (*name_matcher) (const char *, void *),
3580    enum search_domain kind,
3581    void *data)
3582 {
3583   int i;
3584   offset_type iter;
3585   struct mapped_index *index;
3586
3587   dw2_setup (objfile);
3588
3589   /* index_table is NULL if OBJF_READNOW.  */
3590   if (!dwarf2_per_objfile->index_table)
3591     return;
3592   index = dwarf2_per_objfile->index_table;
3593
3594   if (file_matcher != NULL)
3595     {
3596       struct cleanup *cleanup;
3597       htab_t visited_found, visited_not_found;
3598
3599       visited_found = htab_create_alloc (10,
3600                                          htab_hash_pointer, htab_eq_pointer,
3601                                          NULL, xcalloc, xfree);
3602       cleanup = make_cleanup_htab_delete (visited_found);
3603       visited_not_found = htab_create_alloc (10,
3604                                              htab_hash_pointer, htab_eq_pointer,
3605                                              NULL, xcalloc, xfree);
3606       make_cleanup_htab_delete (visited_not_found);
3607
3608       /* The rule is CUs specify all the files, including those used by
3609          any TU, so there's no need to scan TUs here.  */
3610
3611       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3612         {
3613           int j;
3614           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3615           struct quick_file_names *file_data;
3616           void **slot;
3617
3618           per_cu->v.quick->mark = 0;
3619
3620           /* We only need to look at symtabs not already expanded.  */
3621           if (per_cu->v.quick->symtab)
3622             continue;
3623
3624           file_data = dw2_get_file_names (per_cu);
3625           if (file_data == NULL)
3626             continue;
3627
3628           if (htab_find (visited_not_found, file_data) != NULL)
3629             continue;
3630           else if (htab_find (visited_found, file_data) != NULL)
3631             {
3632               per_cu->v.quick->mark = 1;
3633               continue;
3634             }
3635
3636           for (j = 0; j < file_data->num_file_names; ++j)
3637             {
3638               const char *this_real_name;
3639
3640               if (file_matcher (file_data->file_names[j], data, 0))
3641                 {
3642                   per_cu->v.quick->mark = 1;
3643                   break;
3644                 }
3645
3646               /* Before we invoke realpath, which can get expensive when many
3647                  files are involved, do a quick comparison of the basenames.  */
3648               if (!basenames_may_differ
3649                   && !file_matcher (lbasename (file_data->file_names[j]),
3650                                     data, 1))
3651                 continue;
3652
3653               this_real_name = dw2_get_real_path (objfile, file_data, j);
3654               if (file_matcher (this_real_name, data, 0))
3655                 {
3656                   per_cu->v.quick->mark = 1;
3657                   break;
3658                 }
3659             }
3660
3661           slot = htab_find_slot (per_cu->v.quick->mark
3662                                  ? visited_found
3663                                  : visited_not_found,
3664                                  file_data, INSERT);
3665           *slot = file_data;
3666         }
3667
3668       do_cleanups (cleanup);
3669     }
3670
3671   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3672     {
3673       offset_type idx = 2 * iter;
3674       const char *name;
3675       offset_type *vec, vec_len, vec_idx;
3676
3677       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3678         continue;
3679
3680       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3681
3682       if (! (*name_matcher) (name, data))
3683         continue;
3684
3685       /* The name was matched, now expand corresponding CUs that were
3686          marked.  */
3687       vec = (offset_type *) (index->constant_pool
3688                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3689       vec_len = MAYBE_SWAP (vec[0]);
3690       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3691         {
3692           struct dwarf2_per_cu_data *per_cu;
3693           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3694           gdb_index_symbol_kind symbol_kind =
3695             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3696           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3697           /* Only check the symbol attributes if they're present.
3698              Indices prior to version 7 don't record them,
3699              and indices >= 7 may elide them for certain symbols
3700              (gold does this).  */
3701           int attrs_valid =
3702             (index->version >= 7
3703              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3704
3705           /* Only check the symbol's kind if it has one.  */
3706           if (attrs_valid)
3707             {
3708               switch (kind)
3709                 {
3710                 case VARIABLES_DOMAIN:
3711                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3712                     continue;
3713                   break;
3714                 case FUNCTIONS_DOMAIN:
3715                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3716                     continue;
3717                   break;
3718                 case TYPES_DOMAIN:
3719                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3720                     continue;
3721                   break;
3722                 default:
3723                   break;
3724                 }
3725             }
3726
3727           /* Don't crash on bad data.  */
3728           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3729                            + dwarf2_per_objfile->n_type_units))
3730             {
3731               complaint (&symfile_complaints,
3732                          _(".gdb_index entry has bad CU index"
3733                            " [in module %s]"), objfile_name (objfile));
3734               continue;
3735             }
3736
3737           per_cu = dw2_get_cu (cu_index);
3738           if (file_matcher == NULL || per_cu->v.quick->mark)
3739             dw2_instantiate_symtab (per_cu);
3740         }
3741     }
3742 }
3743
3744 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3745    symtab.  */
3746
3747 static struct symtab *
3748 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3749 {
3750   int i;
3751
3752   if (BLOCKVECTOR (symtab) != NULL
3753       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3754     return symtab;
3755
3756   if (symtab->includes == NULL)
3757     return NULL;
3758
3759   for (i = 0; symtab->includes[i]; ++i)
3760     {
3761       struct symtab *s = symtab->includes[i];
3762
3763       s = recursively_find_pc_sect_symtab (s, pc);
3764       if (s != NULL)
3765         return s;
3766     }
3767
3768   return NULL;
3769 }
3770
3771 static struct symtab *
3772 dw2_find_pc_sect_symtab (struct objfile *objfile,
3773                          struct minimal_symbol *msymbol,
3774                          CORE_ADDR pc,
3775                          struct obj_section *section,
3776                          int warn_if_readin)
3777 {
3778   struct dwarf2_per_cu_data *data;
3779   struct symtab *result;
3780
3781   dw2_setup (objfile);
3782
3783   if (!objfile->psymtabs_addrmap)
3784     return NULL;
3785
3786   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3787   if (!data)
3788     return NULL;
3789
3790   if (warn_if_readin && data->v.quick->symtab)
3791     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3792              paddress (get_objfile_arch (objfile), pc));
3793
3794   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3795   gdb_assert (result != NULL);
3796   return result;
3797 }
3798
3799 static void
3800 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3801                           void *data, int need_fullname)
3802 {
3803   int i;
3804   struct cleanup *cleanup;
3805   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3806                                       NULL, xcalloc, xfree);
3807
3808   cleanup = make_cleanup_htab_delete (visited);
3809   dw2_setup (objfile);
3810
3811   /* The rule is CUs specify all the files, including those used by
3812      any TU, so there's no need to scan TUs here.
3813      We can ignore file names coming from already-expanded CUs.  */
3814
3815   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3816     {
3817       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3818
3819       if (per_cu->v.quick->symtab)
3820         {
3821           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3822                                         INSERT);
3823
3824           *slot = per_cu->v.quick->file_names;
3825         }
3826     }
3827
3828   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3829     {
3830       int j;
3831       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3832       struct quick_file_names *file_data;
3833       void **slot;
3834
3835       /* We only need to look at symtabs not already expanded.  */
3836       if (per_cu->v.quick->symtab)
3837         continue;
3838
3839       file_data = dw2_get_file_names (per_cu);
3840       if (file_data == NULL)
3841         continue;
3842
3843       slot = htab_find_slot (visited, file_data, INSERT);
3844       if (*slot)
3845         {
3846           /* Already visited.  */
3847           continue;
3848         }
3849       *slot = file_data;
3850
3851       for (j = 0; j < file_data->num_file_names; ++j)
3852         {
3853           const char *this_real_name;
3854
3855           if (need_fullname)
3856             this_real_name = dw2_get_real_path (objfile, file_data, j);
3857           else
3858             this_real_name = NULL;
3859           (*fun) (file_data->file_names[j], this_real_name, data);
3860         }
3861     }
3862
3863   do_cleanups (cleanup);
3864 }
3865
3866 static int
3867 dw2_has_symbols (struct objfile *objfile)
3868 {
3869   return 1;
3870 }
3871
3872 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3873 {
3874   dw2_has_symbols,
3875   dw2_find_last_source_symtab,
3876   dw2_forget_cached_source_info,
3877   dw2_map_symtabs_matching_filename,
3878   dw2_lookup_symbol,
3879   dw2_print_stats,
3880   dw2_dump,
3881   dw2_relocate,
3882   dw2_expand_symtabs_for_function,
3883   dw2_expand_all_symtabs,
3884   dw2_expand_symtabs_with_fullname,
3885   dw2_map_matching_symbols,
3886   dw2_expand_symtabs_matching,
3887   dw2_find_pc_sect_symtab,
3888   dw2_map_symbol_filenames
3889 };
3890
3891 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3892    file will use psymtabs, or 1 if using the GNU index.  */
3893
3894 int
3895 dwarf2_initialize_objfile (struct objfile *objfile)
3896 {
3897   /* If we're about to read full symbols, don't bother with the
3898      indices.  In this case we also don't care if some other debug
3899      format is making psymtabs, because they are all about to be
3900      expanded anyway.  */
3901   if ((objfile->flags & OBJF_READNOW))
3902     {
3903       int i;
3904
3905       dwarf2_per_objfile->using_index = 1;
3906       create_all_comp_units (objfile);
3907       create_all_type_units (objfile);
3908       dwarf2_per_objfile->quick_file_names_table =
3909         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3910
3911       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3912                        + dwarf2_per_objfile->n_type_units); ++i)
3913         {
3914           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3915
3916           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3917                                             struct dwarf2_per_cu_quick_data);
3918         }
3919
3920       /* Return 1 so that gdb sees the "quick" functions.  However,
3921          these functions will be no-ops because we will have expanded
3922          all symtabs.  */
3923       return 1;
3924     }
3925
3926   if (dwarf2_read_index (objfile))
3927     return 1;
3928
3929   return 0;
3930 }
3931
3932 \f
3933
3934 /* Build a partial symbol table.  */
3935
3936 void
3937 dwarf2_build_psymtabs (struct objfile *objfile)
3938 {
3939   volatile struct gdb_exception except;
3940
3941   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3942     {
3943       init_psymbol_list (objfile, 1024);
3944     }
3945
3946   TRY_CATCH (except, RETURN_MASK_ERROR)
3947     {
3948       /* This isn't really ideal: all the data we allocate on the
3949          objfile's obstack is still uselessly kept around.  However,
3950          freeing it seems unsafe.  */
3951       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3952
3953       dwarf2_build_psymtabs_hard (objfile);
3954       discard_cleanups (cleanups);
3955     }
3956   if (except.reason < 0)
3957     exception_print (gdb_stderr, except);
3958 }
3959
3960 /* Return the total length of the CU described by HEADER.  */
3961
3962 static unsigned int
3963 get_cu_length (const struct comp_unit_head *header)
3964 {
3965   return header->initial_length_size + header->length;
3966 }
3967
3968 /* Return TRUE if OFFSET is within CU_HEADER.  */
3969
3970 static inline int
3971 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3972 {
3973   sect_offset bottom = { cu_header->offset.sect_off };
3974   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3975
3976   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3977 }
3978
3979 /* Find the base address of the compilation unit for range lists and
3980    location lists.  It will normally be specified by DW_AT_low_pc.
3981    In DWARF-3 draft 4, the base address could be overridden by
3982    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3983    compilation units with discontinuous ranges.  */
3984
3985 static void
3986 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3987 {
3988   struct attribute *attr;
3989
3990   cu->base_known = 0;
3991   cu->base_address = 0;
3992
3993   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3994   if (attr)
3995     {
3996       cu->base_address = DW_ADDR (attr);
3997       cu->base_known = 1;
3998     }
3999   else
4000     {
4001       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4002       if (attr)
4003         {
4004           cu->base_address = DW_ADDR (attr);
4005           cu->base_known = 1;
4006         }
4007     }
4008 }
4009
4010 /* Read in the comp unit header information from the debug_info at info_ptr.
4011    NOTE: This leaves members offset, first_die_offset to be filled in
4012    by the caller.  */
4013
4014 static const gdb_byte *
4015 read_comp_unit_head (struct comp_unit_head *cu_header,
4016                      const gdb_byte *info_ptr, bfd *abfd)
4017 {
4018   int signed_addr;
4019   unsigned int bytes_read;
4020
4021   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4022   cu_header->initial_length_size = bytes_read;
4023   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4024   info_ptr += bytes_read;
4025   cu_header->version = read_2_bytes (abfd, info_ptr);
4026   info_ptr += 2;
4027   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4028                                              &bytes_read);
4029   info_ptr += bytes_read;
4030   cu_header->addr_size = read_1_byte (abfd, info_ptr);
4031   info_ptr += 1;
4032   signed_addr = bfd_get_sign_extend_vma (abfd);
4033   if (signed_addr < 0)
4034     internal_error (__FILE__, __LINE__,
4035                     _("read_comp_unit_head: dwarf from non elf file"));
4036   cu_header->signed_addr_p = signed_addr;
4037
4038   return info_ptr;
4039 }
4040
4041 /* Helper function that returns the proper abbrev section for
4042    THIS_CU.  */
4043
4044 static struct dwarf2_section_info *
4045 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4046 {
4047   struct dwarf2_section_info *abbrev;
4048
4049   if (this_cu->is_dwz)
4050     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4051   else
4052     abbrev = &dwarf2_per_objfile->abbrev;
4053
4054   return abbrev;
4055 }
4056
4057 /* Subroutine of read_and_check_comp_unit_head and
4058    read_and_check_type_unit_head to simplify them.
4059    Perform various error checking on the header.  */
4060
4061 static void
4062 error_check_comp_unit_head (struct comp_unit_head *header,
4063                             struct dwarf2_section_info *section,
4064                             struct dwarf2_section_info *abbrev_section)
4065 {
4066   bfd *abfd = get_section_bfd_owner (section);
4067   const char *filename = get_section_file_name (section);
4068
4069   if (header->version != 2 && header->version != 3 && header->version != 4)
4070     error (_("Dwarf Error: wrong version in compilation unit header "
4071            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4072            filename);
4073
4074   if (header->abbrev_offset.sect_off
4075       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4076     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4077            "(offset 0x%lx + 6) [in module %s]"),
4078            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4079            filename);
4080
4081   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4082      avoid potential 32-bit overflow.  */
4083   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4084       > section->size)
4085     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4086            "(offset 0x%lx + 0) [in module %s]"),
4087            (long) header->length, (long) header->offset.sect_off,
4088            filename);
4089 }
4090
4091 /* Read in a CU/TU header and perform some basic error checking.
4092    The contents of the header are stored in HEADER.
4093    The result is a pointer to the start of the first DIE.  */
4094
4095 static const gdb_byte *
4096 read_and_check_comp_unit_head (struct comp_unit_head *header,
4097                                struct dwarf2_section_info *section,
4098                                struct dwarf2_section_info *abbrev_section,
4099                                const gdb_byte *info_ptr,
4100                                int is_debug_types_section)
4101 {
4102   const gdb_byte *beg_of_comp_unit = info_ptr;
4103   bfd *abfd = get_section_bfd_owner (section);
4104
4105   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4106
4107   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4108
4109   /* If we're reading a type unit, skip over the signature and
4110      type_offset fields.  */
4111   if (is_debug_types_section)
4112     info_ptr += 8 /*signature*/ + header->offset_size;
4113
4114   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4115
4116   error_check_comp_unit_head (header, section, abbrev_section);
4117
4118   return info_ptr;
4119 }
4120
4121 /* Read in the types comp unit header information from .debug_types entry at
4122    types_ptr.  The result is a pointer to one past the end of the header.  */
4123
4124 static const gdb_byte *
4125 read_and_check_type_unit_head (struct comp_unit_head *header,
4126                                struct dwarf2_section_info *section,
4127                                struct dwarf2_section_info *abbrev_section,
4128                                const gdb_byte *info_ptr,
4129                                ULONGEST *signature,
4130                                cu_offset *type_offset_in_tu)
4131 {
4132   const gdb_byte *beg_of_comp_unit = info_ptr;
4133   bfd *abfd = get_section_bfd_owner (section);
4134
4135   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4136
4137   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4138
4139   /* If we're reading a type unit, skip over the signature and
4140      type_offset fields.  */
4141   if (signature != NULL)
4142     *signature = read_8_bytes (abfd, info_ptr);
4143   info_ptr += 8;
4144   if (type_offset_in_tu != NULL)
4145     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4146                                                header->offset_size);
4147   info_ptr += header->offset_size;
4148
4149   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4150
4151   error_check_comp_unit_head (header, section, abbrev_section);
4152
4153   return info_ptr;
4154 }
4155
4156 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4157
4158 static sect_offset
4159 read_abbrev_offset (struct dwarf2_section_info *section,
4160                     sect_offset offset)
4161 {
4162   bfd *abfd = get_section_bfd_owner (section);
4163   const gdb_byte *info_ptr;
4164   unsigned int length, initial_length_size, offset_size;
4165   sect_offset abbrev_offset;
4166
4167   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4168   info_ptr = section->buffer + offset.sect_off;
4169   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4170   offset_size = initial_length_size == 4 ? 4 : 8;
4171   info_ptr += initial_length_size + 2 /*version*/;
4172   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4173   return abbrev_offset;
4174 }
4175
4176 /* Allocate a new partial symtab for file named NAME and mark this new
4177    partial symtab as being an include of PST.  */
4178
4179 static void
4180 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4181                                struct objfile *objfile)
4182 {
4183   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4184
4185   if (!IS_ABSOLUTE_PATH (subpst->filename))
4186     {
4187       /* It shares objfile->objfile_obstack.  */
4188       subpst->dirname = pst->dirname;
4189     }
4190
4191   subpst->section_offsets = pst->section_offsets;
4192   subpst->textlow = 0;
4193   subpst->texthigh = 0;
4194
4195   subpst->dependencies = (struct partial_symtab **)
4196     obstack_alloc (&objfile->objfile_obstack,
4197                    sizeof (struct partial_symtab *));
4198   subpst->dependencies[0] = pst;
4199   subpst->number_of_dependencies = 1;
4200
4201   subpst->globals_offset = 0;
4202   subpst->n_global_syms = 0;
4203   subpst->statics_offset = 0;
4204   subpst->n_static_syms = 0;
4205   subpst->symtab = NULL;
4206   subpst->read_symtab = pst->read_symtab;
4207   subpst->readin = 0;
4208
4209   /* No private part is necessary for include psymtabs.  This property
4210      can be used to differentiate between such include psymtabs and
4211      the regular ones.  */
4212   subpst->read_symtab_private = NULL;
4213 }
4214
4215 /* Read the Line Number Program data and extract the list of files
4216    included by the source file represented by PST.  Build an include
4217    partial symtab for each of these included files.  */
4218
4219 static void
4220 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4221                                struct die_info *die,
4222                                struct partial_symtab *pst)
4223 {
4224   struct line_header *lh = NULL;
4225   struct attribute *attr;
4226
4227   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4228   if (attr)
4229     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4230   if (lh == NULL)
4231     return;  /* No linetable, so no includes.  */
4232
4233   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4234   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4235
4236   free_line_header (lh);
4237 }
4238
4239 static hashval_t
4240 hash_signatured_type (const void *item)
4241 {
4242   const struct signatured_type *sig_type = item;
4243
4244   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4245   return sig_type->signature;
4246 }
4247
4248 static int
4249 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4250 {
4251   const struct signatured_type *lhs = item_lhs;
4252   const struct signatured_type *rhs = item_rhs;
4253
4254   return lhs->signature == rhs->signature;
4255 }
4256
4257 /* Allocate a hash table for signatured types.  */
4258
4259 static htab_t
4260 allocate_signatured_type_table (struct objfile *objfile)
4261 {
4262   return htab_create_alloc_ex (41,
4263                                hash_signatured_type,
4264                                eq_signatured_type,
4265                                NULL,
4266                                &objfile->objfile_obstack,
4267                                hashtab_obstack_allocate,
4268                                dummy_obstack_deallocate);
4269 }
4270
4271 /* A helper function to add a signatured type CU to a table.  */
4272
4273 static int
4274 add_signatured_type_cu_to_table (void **slot, void *datum)
4275 {
4276   struct signatured_type *sigt = *slot;
4277   struct signatured_type ***datap = datum;
4278
4279   **datap = sigt;
4280   ++*datap;
4281
4282   return 1;
4283 }
4284
4285 /* Create the hash table of all entries in the .debug_types
4286    (or .debug_types.dwo) section(s).
4287    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4288    otherwise it is NULL.
4289
4290    The result is a pointer to the hash table or NULL if there are no types.
4291
4292    Note: This function processes DWO files only, not DWP files.  */
4293
4294 static htab_t
4295 create_debug_types_hash_table (struct dwo_file *dwo_file,
4296                                VEC (dwarf2_section_info_def) *types)
4297 {
4298   struct objfile *objfile = dwarf2_per_objfile->objfile;
4299   htab_t types_htab = NULL;
4300   int ix;
4301   struct dwarf2_section_info *section;
4302   struct dwarf2_section_info *abbrev_section;
4303
4304   if (VEC_empty (dwarf2_section_info_def, types))
4305     return NULL;
4306
4307   abbrev_section = (dwo_file != NULL
4308                     ? &dwo_file->sections.abbrev
4309                     : &dwarf2_per_objfile->abbrev);
4310
4311   if (dwarf2_read_debug)
4312     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4313                         dwo_file ? ".dwo" : "",
4314                         get_section_file_name (abbrev_section));
4315
4316   for (ix = 0;
4317        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4318        ++ix)
4319     {
4320       bfd *abfd;
4321       const gdb_byte *info_ptr, *end_ptr;
4322
4323       dwarf2_read_section (objfile, section);
4324       info_ptr = section->buffer;
4325
4326       if (info_ptr == NULL)
4327         continue;
4328
4329       /* We can't set abfd until now because the section may be empty or
4330          not present, in which case the bfd is unknown.  */
4331       abfd = get_section_bfd_owner (section);
4332
4333       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4334          because we don't need to read any dies: the signature is in the
4335          header.  */
4336
4337       end_ptr = info_ptr + section->size;
4338       while (info_ptr < end_ptr)
4339         {
4340           sect_offset offset;
4341           cu_offset type_offset_in_tu;
4342           ULONGEST signature;
4343           struct signatured_type *sig_type;
4344           struct dwo_unit *dwo_tu;
4345           void **slot;
4346           const gdb_byte *ptr = info_ptr;
4347           struct comp_unit_head header;
4348           unsigned int length;
4349
4350           offset.sect_off = ptr - section->buffer;
4351
4352           /* We need to read the type's signature in order to build the hash
4353              table, but we don't need anything else just yet.  */
4354
4355           ptr = read_and_check_type_unit_head (&header, section,
4356                                                abbrev_section, ptr,
4357                                                &signature, &type_offset_in_tu);
4358
4359           length = get_cu_length (&header);
4360
4361           /* Skip dummy type units.  */
4362           if (ptr >= info_ptr + length
4363               || peek_abbrev_code (abfd, ptr) == 0)
4364             {
4365               info_ptr += length;
4366               continue;
4367             }
4368
4369           if (types_htab == NULL)
4370             {
4371               if (dwo_file)
4372                 types_htab = allocate_dwo_unit_table (objfile);
4373               else
4374                 types_htab = allocate_signatured_type_table (objfile);
4375             }
4376
4377           if (dwo_file)
4378             {
4379               sig_type = NULL;
4380               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4381                                        struct dwo_unit);
4382               dwo_tu->dwo_file = dwo_file;
4383               dwo_tu->signature = signature;
4384               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4385               dwo_tu->section = section;
4386               dwo_tu->offset = offset;
4387               dwo_tu->length = length;
4388             }
4389           else
4390             {
4391               /* N.B.: type_offset is not usable if this type uses a DWO file.
4392                  The real type_offset is in the DWO file.  */
4393               dwo_tu = NULL;
4394               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4395                                          struct signatured_type);
4396               sig_type->signature = signature;
4397               sig_type->type_offset_in_tu = type_offset_in_tu;
4398               sig_type->per_cu.objfile = objfile;
4399               sig_type->per_cu.is_debug_types = 1;
4400               sig_type->per_cu.section = section;
4401               sig_type->per_cu.offset = offset;
4402               sig_type->per_cu.length = length;
4403             }
4404
4405           slot = htab_find_slot (types_htab,
4406                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4407                                  INSERT);
4408           gdb_assert (slot != NULL);
4409           if (*slot != NULL)
4410             {
4411               sect_offset dup_offset;
4412
4413               if (dwo_file)
4414                 {
4415                   const struct dwo_unit *dup_tu = *slot;
4416
4417                   dup_offset = dup_tu->offset;
4418                 }
4419               else
4420                 {
4421                   const struct signatured_type *dup_tu = *slot;
4422
4423                   dup_offset = dup_tu->per_cu.offset;
4424                 }
4425
4426               complaint (&symfile_complaints,
4427                          _("debug type entry at offset 0x%x is duplicate to"
4428                            " the entry at offset 0x%x, signature %s"),
4429                          offset.sect_off, dup_offset.sect_off,
4430                          hex_string (signature));
4431             }
4432           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4433
4434           if (dwarf2_read_debug)
4435             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4436                                 offset.sect_off,
4437                                 hex_string (signature));
4438
4439           info_ptr += length;
4440         }
4441     }
4442
4443   return types_htab;
4444 }
4445
4446 /* Create the hash table of all entries in the .debug_types section,
4447    and initialize all_type_units.
4448    The result is zero if there is an error (e.g. missing .debug_types section),
4449    otherwise non-zero.  */
4450
4451 static int
4452 create_all_type_units (struct objfile *objfile)
4453 {
4454   htab_t types_htab;
4455   struct signatured_type **iter;
4456
4457   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4458   if (types_htab == NULL)
4459     {
4460       dwarf2_per_objfile->signatured_types = NULL;
4461       return 0;
4462     }
4463
4464   dwarf2_per_objfile->signatured_types = types_htab;
4465
4466   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4467   dwarf2_per_objfile->all_type_units
4468     = xmalloc (dwarf2_per_objfile->n_type_units
4469                * sizeof (struct signatured_type *));
4470   iter = &dwarf2_per_objfile->all_type_units[0];
4471   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4472   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4473               == dwarf2_per_objfile->n_type_units);
4474
4475   return 1;
4476 }
4477
4478 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4479    Fill in SIG_ENTRY with DWO_ENTRY.  */
4480
4481 static void
4482 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4483                                   struct signatured_type *sig_entry,
4484                                   struct dwo_unit *dwo_entry)
4485 {
4486   /* Make sure we're not clobbering something we don't expect to.  */
4487   gdb_assert (! sig_entry->per_cu.queued);
4488   gdb_assert (sig_entry->per_cu.cu == NULL);
4489   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4490   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4491   gdb_assert (sig_entry->signature == dwo_entry->signature);
4492   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4493   gdb_assert (sig_entry->type_unit_group == NULL);
4494   gdb_assert (sig_entry->dwo_unit == NULL);
4495
4496   sig_entry->per_cu.section = dwo_entry->section;
4497   sig_entry->per_cu.offset = dwo_entry->offset;
4498   sig_entry->per_cu.length = dwo_entry->length;
4499   sig_entry->per_cu.reading_dwo_directly = 1;
4500   sig_entry->per_cu.objfile = objfile;
4501   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4502   sig_entry->dwo_unit = dwo_entry;
4503 }
4504
4505 /* Subroutine of lookup_signatured_type.
4506    If we haven't read the TU yet, create the signatured_type data structure
4507    for a TU to be read in directly from a DWO file, bypassing the stub.
4508    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4509    using .gdb_index, then when reading a CU we want to stay in the DWO file
4510    containing that CU.  Otherwise we could end up reading several other DWO
4511    files (due to comdat folding) to process the transitive closure of all the
4512    mentioned TUs, and that can be slow.  The current DWO file will have every
4513    type signature that it needs.
4514    We only do this for .gdb_index because in the psymtab case we already have
4515    to read all the DWOs to build the type unit groups.  */
4516
4517 static struct signatured_type *
4518 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4519 {
4520   struct objfile *objfile = dwarf2_per_objfile->objfile;
4521   struct dwo_file *dwo_file;
4522   struct dwo_unit find_dwo_entry, *dwo_entry;
4523   struct signatured_type find_sig_entry, *sig_entry;
4524
4525   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4526
4527   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4528      dwo_unit of the TU itself.  */
4529   dwo_file = cu->dwo_unit->dwo_file;
4530
4531   /* We only ever need to read in one copy of a signatured type.
4532      Just use the global signatured_types array.  If this is the first time
4533      we're reading this type, replace the recorded data from .gdb_index with
4534      this TU.  */
4535
4536   if (dwarf2_per_objfile->signatured_types == NULL)
4537     return NULL;
4538   find_sig_entry.signature = sig;
4539   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4540   if (sig_entry == NULL)
4541     return NULL;
4542
4543   /* We can get here with the TU already read, *or* in the process of being
4544      read.  Don't reassign it if that's the case.  Also note that if the TU is
4545      already being read, it may not have come from a DWO, the program may be
4546      a mix of Fission-compiled code and non-Fission-compiled code.  */
4547   /* Have we already tried to read this TU?  */
4548   if (sig_entry->per_cu.tu_read)
4549     return sig_entry;
4550
4551   /* Ok, this is the first time we're reading this TU.  */
4552   if (dwo_file->tus == NULL)
4553     return NULL;
4554   find_dwo_entry.signature = sig;
4555   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4556   if (dwo_entry == NULL)
4557     return NULL;
4558
4559   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4560   sig_entry->per_cu.tu_read = 1;
4561   return sig_entry;
4562 }
4563
4564 /* Subroutine of lookup_dwp_signatured_type.
4565    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4566
4567 static struct signatured_type *
4568 add_type_unit (ULONGEST sig)
4569 {
4570   struct objfile *objfile = dwarf2_per_objfile->objfile;
4571   int n_type_units = dwarf2_per_objfile->n_type_units;
4572   struct signatured_type *sig_type;
4573   void **slot;
4574
4575   ++n_type_units;
4576   dwarf2_per_objfile->all_type_units =
4577     xrealloc (dwarf2_per_objfile->all_type_units,
4578               n_type_units * sizeof (struct signatured_type *));
4579   dwarf2_per_objfile->n_type_units = n_type_units;
4580   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4581                              struct signatured_type);
4582   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4583   sig_type->signature = sig;
4584   sig_type->per_cu.is_debug_types = 1;
4585   sig_type->per_cu.v.quick =
4586     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4587                     struct dwarf2_per_cu_quick_data);
4588   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4589                          sig_type, INSERT);
4590   gdb_assert (*slot == NULL);
4591   *slot = sig_type;
4592   /* The rest of sig_type must be filled in by the caller.  */
4593   return sig_type;
4594 }
4595
4596 /* Subroutine of lookup_signatured_type.
4597    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4598    then try the DWP file.
4599    Normally this "can't happen", but if there's a bug in signature
4600    generation and/or the DWP file is built incorrectly, it can happen.
4601    Using the type directly from the DWP file means we don't have the stub
4602    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4603    not critical.  [Eventually the stub may go away for type units anyway.]  */
4604
4605 static struct signatured_type *
4606 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4607 {
4608   struct objfile *objfile = dwarf2_per_objfile->objfile;
4609   struct dwp_file *dwp_file = get_dwp_file ();
4610   struct dwo_unit *dwo_entry;
4611   struct signatured_type find_sig_entry, *sig_entry;
4612
4613   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4614   gdb_assert (dwp_file != NULL);
4615
4616   if (dwarf2_per_objfile->signatured_types != NULL)
4617     {
4618       find_sig_entry.signature = sig;
4619       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4620                              &find_sig_entry);
4621       if (sig_entry != NULL)
4622         return sig_entry;
4623     }
4624
4625   /* This is the "shouldn't happen" case.
4626      Try the DWP file and hope for the best.  */
4627   if (dwp_file->tus == NULL)
4628     return NULL;
4629   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
4630                                       sig, 1 /* is_debug_types */);
4631   if (dwo_entry == NULL)
4632     return NULL;
4633
4634   sig_entry = add_type_unit (sig);
4635   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4636
4637   /* The caller will signal a complaint if we return NULL.
4638      Here we don't return NULL but we still want to complain.  */
4639   complaint (&symfile_complaints,
4640              _("Bad type signature %s referenced by %s at 0x%x,"
4641                " coping by using copy in DWP [in module %s]"),
4642              hex_string (sig),
4643              cu->per_cu->is_debug_types ? "TU" : "CU",
4644              cu->per_cu->offset.sect_off,
4645              objfile_name (objfile));
4646
4647   return sig_entry;
4648 }
4649
4650 /* Lookup a signature based type for DW_FORM_ref_sig8.
4651    Returns NULL if signature SIG is not present in the table.
4652    It is up to the caller to complain about this.  */
4653
4654 static struct signatured_type *
4655 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4656 {
4657   if (cu->dwo_unit
4658       && dwarf2_per_objfile->using_index)
4659     {
4660       /* We're in a DWO/DWP file, and we're using .gdb_index.
4661          These cases require special processing.  */
4662       if (get_dwp_file () == NULL)
4663         return lookup_dwo_signatured_type (cu, sig);
4664       else
4665         return lookup_dwp_signatured_type (cu, sig);
4666     }
4667   else
4668     {
4669       struct signatured_type find_entry, *entry;
4670
4671       if (dwarf2_per_objfile->signatured_types == NULL)
4672         return NULL;
4673       find_entry.signature = sig;
4674       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4675       return entry;
4676     }
4677 }
4678 \f
4679 /* Low level DIE reading support.  */
4680
4681 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4682
4683 static void
4684 init_cu_die_reader (struct die_reader_specs *reader,
4685                     struct dwarf2_cu *cu,
4686                     struct dwarf2_section_info *section,
4687                     struct dwo_file *dwo_file)
4688 {
4689   gdb_assert (section->readin && section->buffer != NULL);
4690   reader->abfd = get_section_bfd_owner (section);
4691   reader->cu = cu;
4692   reader->dwo_file = dwo_file;
4693   reader->die_section = section;
4694   reader->buffer = section->buffer;
4695   reader->buffer_end = section->buffer + section->size;
4696   reader->comp_dir = NULL;
4697 }
4698
4699 /* Subroutine of init_cutu_and_read_dies to simplify it.
4700    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4701    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4702    already.
4703
4704    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4705    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4706    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4707    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4708    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4709    COMP_DIR must be non-NULL.
4710    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4711    are filled in with the info of the DIE from the DWO file.
4712    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4713    provided an abbrev table to use.
4714    The result is non-zero if a valid (non-dummy) DIE was found.  */
4715
4716 static int
4717 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4718                         struct dwo_unit *dwo_unit,
4719                         int abbrev_table_provided,
4720                         struct die_info *stub_comp_unit_die,
4721                         const char *stub_comp_dir,
4722                         struct die_reader_specs *result_reader,
4723                         const gdb_byte **result_info_ptr,
4724                         struct die_info **result_comp_unit_die,
4725                         int *result_has_children)
4726 {
4727   struct objfile *objfile = dwarf2_per_objfile->objfile;
4728   struct dwarf2_cu *cu = this_cu->cu;
4729   struct dwarf2_section_info *section;
4730   bfd *abfd;
4731   const gdb_byte *begin_info_ptr, *info_ptr;
4732   const char *comp_dir_string;
4733   ULONGEST signature; /* Or dwo_id.  */
4734   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4735   int i,num_extra_attrs;
4736   struct dwarf2_section_info *dwo_abbrev_section;
4737   struct attribute *attr;
4738   struct attribute comp_dir_attr;
4739   struct die_info *comp_unit_die;
4740
4741   /* Both can't be provided.  */
4742   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4743
4744   /* These attributes aren't processed until later:
4745      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4746      However, the attribute is found in the stub which we won't have later.
4747      In order to not impose this complication on the rest of the code,
4748      we read them here and copy them to the DWO CU/TU die.  */
4749
4750   stmt_list = NULL;
4751   low_pc = NULL;
4752   high_pc = NULL;
4753   ranges = NULL;
4754   comp_dir = NULL;
4755
4756   if (stub_comp_unit_die != NULL)
4757     {
4758       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4759          DWO file.  */
4760       if (! this_cu->is_debug_types)
4761         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4762       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4763       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4764       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4765       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4766
4767       /* There should be a DW_AT_addr_base attribute here (if needed).
4768          We need the value before we can process DW_FORM_GNU_addr_index.  */
4769       cu->addr_base = 0;
4770       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4771       if (attr)
4772         cu->addr_base = DW_UNSND (attr);
4773
4774       /* There should be a DW_AT_ranges_base attribute here (if needed).
4775          We need the value before we can process DW_AT_ranges.  */
4776       cu->ranges_base = 0;
4777       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4778       if (attr)
4779         cu->ranges_base = DW_UNSND (attr);
4780     }
4781   else if (stub_comp_dir != NULL)
4782     {
4783       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4784       comp_dir = (struct attribute *)
4785         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4786       comp_dir->name = DW_AT_comp_dir;
4787       comp_dir->form = DW_FORM_string;
4788       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4789       DW_STRING (comp_dir) = stub_comp_dir;
4790     }
4791
4792   /* Set up for reading the DWO CU/TU.  */
4793   cu->dwo_unit = dwo_unit;
4794   section = dwo_unit->section;
4795   dwarf2_read_section (objfile, section);
4796   abfd = get_section_bfd_owner (section);
4797   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4798   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4799   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4800
4801   if (this_cu->is_debug_types)
4802     {
4803       ULONGEST header_signature;
4804       cu_offset type_offset_in_tu;
4805       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4806
4807       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4808                                                 dwo_abbrev_section,
4809                                                 info_ptr,
4810                                                 &header_signature,
4811                                                 &type_offset_in_tu);
4812       /* This is not an assert because it can be caused by bad debug info.  */
4813       if (sig_type->signature != header_signature)
4814         {
4815           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4816                    " TU at offset 0x%x [in module %s]"),
4817                  hex_string (sig_type->signature),
4818                  hex_string (header_signature),
4819                  dwo_unit->offset.sect_off,
4820                  bfd_get_filename (abfd));
4821         }
4822       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4823       /* For DWOs coming from DWP files, we don't know the CU length
4824          nor the type's offset in the TU until now.  */
4825       dwo_unit->length = get_cu_length (&cu->header);
4826       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4827
4828       /* Establish the type offset that can be used to lookup the type.
4829          For DWO files, we don't know it until now.  */
4830       sig_type->type_offset_in_section.sect_off =
4831         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4832     }
4833   else
4834     {
4835       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4836                                                 dwo_abbrev_section,
4837                                                 info_ptr, 0);
4838       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4839       /* For DWOs coming from DWP files, we don't know the CU length
4840          until now.  */
4841       dwo_unit->length = get_cu_length (&cu->header);
4842     }
4843
4844   /* Replace the CU's original abbrev table with the DWO's.
4845      Reminder: We can't read the abbrev table until we've read the header.  */
4846   if (abbrev_table_provided)
4847     {
4848       /* Don't free the provided abbrev table, the caller of
4849          init_cutu_and_read_dies owns it.  */
4850       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4851       /* Ensure the DWO abbrev table gets freed.  */
4852       make_cleanup (dwarf2_free_abbrev_table, cu);
4853     }
4854   else
4855     {
4856       dwarf2_free_abbrev_table (cu);
4857       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4858       /* Leave any existing abbrev table cleanup as is.  */
4859     }
4860
4861   /* Read in the die, but leave space to copy over the attributes
4862      from the stub.  This has the benefit of simplifying the rest of
4863      the code - all the work to maintain the illusion of a single
4864      DW_TAG_{compile,type}_unit DIE is done here.  */
4865   num_extra_attrs = ((stmt_list != NULL)
4866                      + (low_pc != NULL)
4867                      + (high_pc != NULL)
4868                      + (ranges != NULL)
4869                      + (comp_dir != NULL));
4870   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4871                               result_has_children, num_extra_attrs);
4872
4873   /* Copy over the attributes from the stub to the DIE we just read in.  */
4874   comp_unit_die = *result_comp_unit_die;
4875   i = comp_unit_die->num_attrs;
4876   if (stmt_list != NULL)
4877     comp_unit_die->attrs[i++] = *stmt_list;
4878   if (low_pc != NULL)
4879     comp_unit_die->attrs[i++] = *low_pc;
4880   if (high_pc != NULL)
4881     comp_unit_die->attrs[i++] = *high_pc;
4882   if (ranges != NULL)
4883     comp_unit_die->attrs[i++] = *ranges;
4884   if (comp_dir != NULL)
4885     comp_unit_die->attrs[i++] = *comp_dir;
4886   comp_unit_die->num_attrs += num_extra_attrs;
4887
4888   if (dwarf2_die_debug)
4889     {
4890       fprintf_unfiltered (gdb_stdlog,
4891                           "Read die from %s@0x%x of %s:\n",
4892                           get_section_name (section),
4893                           (unsigned) (begin_info_ptr - section->buffer),
4894                           bfd_get_filename (abfd));
4895       dump_die (comp_unit_die, dwarf2_die_debug);
4896     }
4897
4898   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4899      TUs by skipping the stub and going directly to the entry in the DWO file.
4900      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4901      to get it via circuitous means.  Blech.  */
4902   if (comp_dir != NULL)
4903     result_reader->comp_dir = DW_STRING (comp_dir);
4904
4905   /* Skip dummy compilation units.  */
4906   if (info_ptr >= begin_info_ptr + dwo_unit->length
4907       || peek_abbrev_code (abfd, info_ptr) == 0)
4908     return 0;
4909
4910   *result_info_ptr = info_ptr;
4911   return 1;
4912 }
4913
4914 /* Subroutine of init_cutu_and_read_dies to simplify it.
4915    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4916    Returns NULL if the specified DWO unit cannot be found.  */
4917
4918 static struct dwo_unit *
4919 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4920                  struct die_info *comp_unit_die)
4921 {
4922   struct dwarf2_cu *cu = this_cu->cu;
4923   struct attribute *attr;
4924   ULONGEST signature;
4925   struct dwo_unit *dwo_unit;
4926   const char *comp_dir, *dwo_name;
4927
4928   gdb_assert (cu != NULL);
4929
4930   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4931   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4932   gdb_assert (attr != NULL);
4933   dwo_name = DW_STRING (attr);
4934   comp_dir = NULL;
4935   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4936   if (attr)
4937     comp_dir = DW_STRING (attr);
4938
4939   if (this_cu->is_debug_types)
4940     {
4941       struct signatured_type *sig_type;
4942
4943       /* Since this_cu is the first member of struct signatured_type,
4944          we can go from a pointer to one to a pointer to the other.  */
4945       sig_type = (struct signatured_type *) this_cu;
4946       signature = sig_type->signature;
4947       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4948     }
4949   else
4950     {
4951       struct attribute *attr;
4952
4953       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4954       if (! attr)
4955         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4956                  " [in module %s]"),
4957                dwo_name, objfile_name (this_cu->objfile));
4958       signature = DW_UNSND (attr);
4959       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4960                                        signature);
4961     }
4962
4963   return dwo_unit;
4964 }
4965
4966 /* Subroutine of init_cutu_and_read_dies to simplify it.
4967    Read a TU directly from a DWO file, bypassing the stub.  */
4968
4969 static void
4970 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4971                            die_reader_func_ftype *die_reader_func,
4972                            void *data)
4973 {
4974   struct dwarf2_cu *cu;
4975   struct signatured_type *sig_type;
4976   struct cleanup *cleanups, *free_cu_cleanup;
4977   struct die_reader_specs reader;
4978   const gdb_byte *info_ptr;
4979   struct die_info *comp_unit_die;
4980   int has_children;
4981
4982   /* Verify we can do the following downcast, and that we have the
4983      data we need.  */
4984   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4985   sig_type = (struct signatured_type *) this_cu;
4986   gdb_assert (sig_type->dwo_unit != NULL);
4987
4988   cleanups = make_cleanup (null_cleanup, NULL);
4989
4990   gdb_assert (this_cu->cu == NULL);
4991   cu = xmalloc (sizeof (*cu));
4992   init_one_comp_unit (cu, this_cu);
4993   /* If an error occurs while loading, release our storage.  */
4994   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4995
4996   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4997                               0 /* abbrev_table_provided */,
4998                               NULL /* stub_comp_unit_die */,
4999                               sig_type->dwo_unit->dwo_file->comp_dir,
5000                               &reader, &info_ptr,
5001                               &comp_unit_die, &has_children) == 0)
5002     {
5003       /* Dummy die.  */
5004       do_cleanups (cleanups);
5005       return;
5006     }
5007
5008   /* All the "real" work is done here.  */
5009   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5010
5011   /* This duplicates some code in init_cutu_and_read_dies,
5012      but the alternative is making the latter more complex.
5013      This function is only for the special case of using DWO files directly:
5014      no point in overly complicating the general case just to handle this.  */
5015   if (keep)
5016     {
5017       /* We've successfully allocated this compilation unit.  Let our
5018          caller clean it up when finished with it.  */
5019       discard_cleanups (free_cu_cleanup);
5020
5021       /* We can only discard free_cu_cleanup and all subsequent cleanups.
5022          So we have to manually free the abbrev table.  */
5023       dwarf2_free_abbrev_table (cu);
5024
5025       /* Link this CU into read_in_chain.  */
5026       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5027       dwarf2_per_objfile->read_in_chain = this_cu;
5028     }
5029   else
5030     do_cleanups (free_cu_cleanup);
5031
5032   do_cleanups (cleanups);
5033 }
5034
5035 /* Initialize a CU (or TU) and read its DIEs.
5036    If the CU defers to a DWO file, read the DWO file as well.
5037
5038    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5039    Otherwise the table specified in the comp unit header is read in and used.
5040    This is an optimization for when we already have the abbrev table.
5041
5042    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5043    Otherwise, a new CU is allocated with xmalloc.
5044
5045    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5046    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5047
5048    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5049    linker) then DIE_READER_FUNC will not get called.  */
5050
5051 static void
5052 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5053                          struct abbrev_table *abbrev_table,
5054                          int use_existing_cu, int keep,
5055                          die_reader_func_ftype *die_reader_func,
5056                          void *data)
5057 {
5058   struct objfile *objfile = dwarf2_per_objfile->objfile;
5059   struct dwarf2_section_info *section = this_cu->section;
5060   bfd *abfd = get_section_bfd_owner (section);
5061   struct dwarf2_cu *cu;
5062   const gdb_byte *begin_info_ptr, *info_ptr;
5063   struct die_reader_specs reader;
5064   struct die_info *comp_unit_die;
5065   int has_children;
5066   struct attribute *attr;
5067   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5068   struct signatured_type *sig_type = NULL;
5069   struct dwarf2_section_info *abbrev_section;
5070   /* Non-zero if CU currently points to a DWO file and we need to
5071      reread it.  When this happens we need to reread the skeleton die
5072      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5073   int rereading_dwo_cu = 0;
5074
5075   if (dwarf2_die_debug)
5076     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5077                         this_cu->is_debug_types ? "type" : "comp",
5078                         this_cu->offset.sect_off);
5079
5080   if (use_existing_cu)
5081     gdb_assert (keep);
5082
5083   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5084      file (instead of going through the stub), short-circuit all of this.  */
5085   if (this_cu->reading_dwo_directly)
5086     {
5087       /* Narrow down the scope of possibilities to have to understand.  */
5088       gdb_assert (this_cu->is_debug_types);
5089       gdb_assert (abbrev_table == NULL);
5090       gdb_assert (!use_existing_cu);
5091       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5092       return;
5093     }
5094
5095   cleanups = make_cleanup (null_cleanup, NULL);
5096
5097   /* This is cheap if the section is already read in.  */
5098   dwarf2_read_section (objfile, section);
5099
5100   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5101
5102   abbrev_section = get_abbrev_section_for_cu (this_cu);
5103
5104   if (use_existing_cu && this_cu->cu != NULL)
5105     {
5106       cu = this_cu->cu;
5107
5108       /* If this CU is from a DWO file we need to start over, we need to
5109          refetch the attributes from the skeleton CU.
5110          This could be optimized by retrieving those attributes from when we
5111          were here the first time: the previous comp_unit_die was stored in
5112          comp_unit_obstack.  But there's no data yet that we need this
5113          optimization.  */
5114       if (cu->dwo_unit != NULL)
5115         rereading_dwo_cu = 1;
5116     }
5117   else
5118     {
5119       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5120       gdb_assert (this_cu->cu == NULL);
5121
5122       cu = xmalloc (sizeof (*cu));
5123       init_one_comp_unit (cu, this_cu);
5124
5125       /* If an error occurs while loading, release our storage.  */
5126       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5127     }
5128
5129   /* Get the header.  */
5130   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5131     {
5132       /* We already have the header, there's no need to read it in again.  */
5133       info_ptr += cu->header.first_die_offset.cu_off;
5134     }
5135   else
5136     {
5137       if (this_cu->is_debug_types)
5138         {
5139           ULONGEST signature;
5140           cu_offset type_offset_in_tu;
5141
5142           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5143                                                     abbrev_section, info_ptr,
5144                                                     &signature,
5145                                                     &type_offset_in_tu);
5146
5147           /* Since per_cu is the first member of struct signatured_type,
5148              we can go from a pointer to one to a pointer to the other.  */
5149           sig_type = (struct signatured_type *) this_cu;
5150           gdb_assert (sig_type->signature == signature);
5151           gdb_assert (sig_type->type_offset_in_tu.cu_off
5152                       == type_offset_in_tu.cu_off);
5153           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5154
5155           /* LENGTH has not been set yet for type units if we're
5156              using .gdb_index.  */
5157           this_cu->length = get_cu_length (&cu->header);
5158
5159           /* Establish the type offset that can be used to lookup the type.  */
5160           sig_type->type_offset_in_section.sect_off =
5161             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5162         }
5163       else
5164         {
5165           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5166                                                     abbrev_section,
5167                                                     info_ptr, 0);
5168
5169           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5170           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5171         }
5172     }
5173
5174   /* Skip dummy compilation units.  */
5175   if (info_ptr >= begin_info_ptr + this_cu->length
5176       || peek_abbrev_code (abfd, info_ptr) == 0)
5177     {
5178       do_cleanups (cleanups);
5179       return;
5180     }
5181
5182   /* If we don't have them yet, read the abbrevs for this compilation unit.
5183      And if we need to read them now, make sure they're freed when we're
5184      done.  Note that it's important that if the CU had an abbrev table
5185      on entry we don't free it when we're done: Somewhere up the call stack
5186      it may be in use.  */
5187   if (abbrev_table != NULL)
5188     {
5189       gdb_assert (cu->abbrev_table == NULL);
5190       gdb_assert (cu->header.abbrev_offset.sect_off
5191                   == abbrev_table->offset.sect_off);
5192       cu->abbrev_table = abbrev_table;
5193     }
5194   else if (cu->abbrev_table == NULL)
5195     {
5196       dwarf2_read_abbrevs (cu, abbrev_section);
5197       make_cleanup (dwarf2_free_abbrev_table, cu);
5198     }
5199   else if (rereading_dwo_cu)
5200     {
5201       dwarf2_free_abbrev_table (cu);
5202       dwarf2_read_abbrevs (cu, abbrev_section);
5203     }
5204
5205   /* Read the top level CU/TU die.  */
5206   init_cu_die_reader (&reader, cu, section, NULL);
5207   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5208
5209   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5210      from the DWO file.
5211      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5212      DWO CU, that this test will fail (the attribute will not be present).  */
5213   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5214   if (attr)
5215     {
5216       struct dwo_unit *dwo_unit;
5217       struct die_info *dwo_comp_unit_die;
5218
5219       if (has_children)
5220         {
5221           complaint (&symfile_complaints,
5222                      _("compilation unit with DW_AT_GNU_dwo_name"
5223                        " has children (offset 0x%x) [in module %s]"),
5224                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5225         }
5226       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5227       if (dwo_unit != NULL)
5228         {
5229           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5230                                       abbrev_table != NULL,
5231                                       comp_unit_die, NULL,
5232                                       &reader, &info_ptr,
5233                                       &dwo_comp_unit_die, &has_children) == 0)
5234             {
5235               /* Dummy die.  */
5236               do_cleanups (cleanups);
5237               return;
5238             }
5239           comp_unit_die = dwo_comp_unit_die;
5240         }
5241       else
5242         {
5243           /* Yikes, we couldn't find the rest of the DIE, we only have
5244              the stub.  A complaint has already been logged.  There's
5245              not much more we can do except pass on the stub DIE to
5246              die_reader_func.  We don't want to throw an error on bad
5247              debug info.  */
5248         }
5249     }
5250
5251   /* All of the above is setup for this call.  Yikes.  */
5252   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5253
5254   /* Done, clean up.  */
5255   if (free_cu_cleanup != NULL)
5256     {
5257       if (keep)
5258         {
5259           /* We've successfully allocated this compilation unit.  Let our
5260              caller clean it up when finished with it.  */
5261           discard_cleanups (free_cu_cleanup);
5262
5263           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5264              So we have to manually free the abbrev table.  */
5265           dwarf2_free_abbrev_table (cu);
5266
5267           /* Link this CU into read_in_chain.  */
5268           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5269           dwarf2_per_objfile->read_in_chain = this_cu;
5270         }
5271       else
5272         do_cleanups (free_cu_cleanup);
5273     }
5274
5275   do_cleanups (cleanups);
5276 }
5277
5278 /* Read CU/TU THIS_CU in section SECTION,
5279    but do not follow DW_AT_GNU_dwo_name if present.
5280    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5281    to have already done the lookup to find the DWO/DWP file).
5282
5283    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5284    THIS_CU->is_debug_types, but nothing else.
5285
5286    We fill in THIS_CU->length.
5287
5288    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5289    linker) then DIE_READER_FUNC will not get called.
5290
5291    THIS_CU->cu is always freed when done.
5292    This is done in order to not leave THIS_CU->cu in a state where we have
5293    to care whether it refers to the "main" CU or the DWO CU.  */
5294
5295 static void
5296 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5297                                    struct dwarf2_section_info *abbrev_section,
5298                                    struct dwo_file *dwo_file,
5299                                    die_reader_func_ftype *die_reader_func,
5300                                    void *data)
5301 {
5302   struct objfile *objfile = dwarf2_per_objfile->objfile;
5303   struct dwarf2_section_info *section = this_cu->section;
5304   bfd *abfd = get_section_bfd_owner (section);
5305   struct dwarf2_cu cu;
5306   const gdb_byte *begin_info_ptr, *info_ptr;
5307   struct die_reader_specs reader;
5308   struct cleanup *cleanups;
5309   struct die_info *comp_unit_die;
5310   int has_children;
5311
5312   if (dwarf2_die_debug)
5313     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5314                         this_cu->is_debug_types ? "type" : "comp",
5315                         this_cu->offset.sect_off);
5316
5317   gdb_assert (this_cu->cu == NULL);
5318
5319   /* This is cheap if the section is already read in.  */
5320   dwarf2_read_section (objfile, section);
5321
5322   init_one_comp_unit (&cu, this_cu);
5323
5324   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5325
5326   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5327   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5328                                             abbrev_section, info_ptr,
5329                                             this_cu->is_debug_types);
5330
5331   this_cu->length = get_cu_length (&cu.header);
5332
5333   /* Skip dummy compilation units.  */
5334   if (info_ptr >= begin_info_ptr + this_cu->length
5335       || peek_abbrev_code (abfd, info_ptr) == 0)
5336     {
5337       do_cleanups (cleanups);
5338       return;
5339     }
5340
5341   dwarf2_read_abbrevs (&cu, abbrev_section);
5342   make_cleanup (dwarf2_free_abbrev_table, &cu);
5343
5344   init_cu_die_reader (&reader, &cu, section, dwo_file);
5345   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5346
5347   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5348
5349   do_cleanups (cleanups);
5350 }
5351
5352 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5353    does not lookup the specified DWO file.
5354    This cannot be used to read DWO files.
5355
5356    THIS_CU->cu is always freed when done.
5357    This is done in order to not leave THIS_CU->cu in a state where we have
5358    to care whether it refers to the "main" CU or the DWO CU.
5359    We can revisit this if the data shows there's a performance issue.  */
5360
5361 static void
5362 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5363                                 die_reader_func_ftype *die_reader_func,
5364                                 void *data)
5365 {
5366   init_cutu_and_read_dies_no_follow (this_cu,
5367                                      get_abbrev_section_for_cu (this_cu),
5368                                      NULL,
5369                                      die_reader_func, data);
5370 }
5371 \f
5372 /* Type Unit Groups.
5373
5374    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5375    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5376    so that all types coming from the same compilation (.o file) are grouped
5377    together.  A future step could be to put the types in the same symtab as
5378    the CU the types ultimately came from.  */
5379
5380 static hashval_t
5381 hash_type_unit_group (const void *item)
5382 {
5383   const struct type_unit_group *tu_group = item;
5384
5385   return hash_stmt_list_entry (&tu_group->hash);
5386 }
5387
5388 static int
5389 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5390 {
5391   const struct type_unit_group *lhs = item_lhs;
5392   const struct type_unit_group *rhs = item_rhs;
5393
5394   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5395 }
5396
5397 /* Allocate a hash table for type unit groups.  */
5398
5399 static htab_t
5400 allocate_type_unit_groups_table (void)
5401 {
5402   return htab_create_alloc_ex (3,
5403                                hash_type_unit_group,
5404                                eq_type_unit_group,
5405                                NULL,
5406                                &dwarf2_per_objfile->objfile->objfile_obstack,
5407                                hashtab_obstack_allocate,
5408                                dummy_obstack_deallocate);
5409 }
5410
5411 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5412    partial symtabs.  We combine several TUs per psymtab to not let the size
5413    of any one psymtab grow too big.  */
5414 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5415 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5416
5417 /* Helper routine for get_type_unit_group.
5418    Create the type_unit_group object used to hold one or more TUs.  */
5419
5420 static struct type_unit_group *
5421 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5422 {
5423   struct objfile *objfile = dwarf2_per_objfile->objfile;
5424   struct dwarf2_per_cu_data *per_cu;
5425   struct type_unit_group *tu_group;
5426
5427   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5428                              struct type_unit_group);
5429   per_cu = &tu_group->per_cu;
5430   per_cu->objfile = objfile;
5431
5432   if (dwarf2_per_objfile->using_index)
5433     {
5434       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5435                                         struct dwarf2_per_cu_quick_data);
5436     }
5437   else
5438     {
5439       unsigned int line_offset = line_offset_struct.sect_off;
5440       struct partial_symtab *pst;
5441       char *name;
5442
5443       /* Give the symtab a useful name for debug purposes.  */
5444       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5445         name = xstrprintf ("<type_units_%d>",
5446                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5447       else
5448         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5449
5450       pst = create_partial_symtab (per_cu, name);
5451       pst->anonymous = 1;
5452
5453       xfree (name);
5454     }
5455
5456   tu_group->hash.dwo_unit = cu->dwo_unit;
5457   tu_group->hash.line_offset = line_offset_struct;
5458
5459   return tu_group;
5460 }
5461
5462 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5463    STMT_LIST is a DW_AT_stmt_list attribute.  */
5464
5465 static struct type_unit_group *
5466 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5467 {
5468   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5469   struct type_unit_group *tu_group;
5470   void **slot;
5471   unsigned int line_offset;
5472   struct type_unit_group type_unit_group_for_lookup;
5473
5474   if (dwarf2_per_objfile->type_unit_groups == NULL)
5475     {
5476       dwarf2_per_objfile->type_unit_groups =
5477         allocate_type_unit_groups_table ();
5478     }
5479
5480   /* Do we need to create a new group, or can we use an existing one?  */
5481
5482   if (stmt_list)
5483     {
5484       line_offset = DW_UNSND (stmt_list);
5485       ++tu_stats->nr_symtab_sharers;
5486     }
5487   else
5488     {
5489       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5490          We can do various things here like create one group per TU or
5491          spread them over multiple groups to split up the expansion work.
5492          To avoid worst case scenarios (too many groups or too large groups)
5493          we, umm, group them in bunches.  */
5494       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5495                      | (tu_stats->nr_stmt_less_type_units
5496                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5497       ++tu_stats->nr_stmt_less_type_units;
5498     }
5499
5500   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5501   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5502   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5503                          &type_unit_group_for_lookup, INSERT);
5504   if (*slot != NULL)
5505     {
5506       tu_group = *slot;
5507       gdb_assert (tu_group != NULL);
5508     }
5509   else
5510     {
5511       sect_offset line_offset_struct;
5512
5513       line_offset_struct.sect_off = line_offset;
5514       tu_group = create_type_unit_group (cu, line_offset_struct);
5515       *slot = tu_group;
5516       ++tu_stats->nr_symtabs;
5517     }
5518
5519   return tu_group;
5520 }
5521
5522 /* Struct used to sort TUs by their abbreviation table offset.  */
5523
5524 struct tu_abbrev_offset
5525 {
5526   struct signatured_type *sig_type;
5527   sect_offset abbrev_offset;
5528 };
5529
5530 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5531
5532 static int
5533 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5534 {
5535   const struct tu_abbrev_offset * const *a = ap;
5536   const struct tu_abbrev_offset * const *b = bp;
5537   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5538   unsigned int boff = (*b)->abbrev_offset.sect_off;
5539
5540   return (aoff > boff) - (aoff < boff);
5541 }
5542
5543 /* A helper function to add a type_unit_group to a table.  */
5544
5545 static int
5546 add_type_unit_group_to_table (void **slot, void *datum)
5547 {
5548   struct type_unit_group *tu_group = *slot;
5549   struct type_unit_group ***datap = datum;
5550
5551   **datap = tu_group;
5552   ++*datap;
5553
5554   return 1;
5555 }
5556
5557 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5558    each one passing FUNC,DATA.
5559
5560    The efficiency is because we sort TUs by the abbrev table they use and
5561    only read each abbrev table once.  In one program there are 200K TUs
5562    sharing 8K abbrev tables.
5563
5564    The main purpose of this function is to support building the
5565    dwarf2_per_objfile->type_unit_groups table.
5566    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5567    can collapse the search space by grouping them by stmt_list.
5568    The savings can be significant, in the same program from above the 200K TUs
5569    share 8K stmt_list tables.
5570
5571    FUNC is expected to call get_type_unit_group, which will create the
5572    struct type_unit_group if necessary and add it to
5573    dwarf2_per_objfile->type_unit_groups.  */
5574
5575 static void
5576 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5577 {
5578   struct objfile *objfile = dwarf2_per_objfile->objfile;
5579   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5580   struct cleanup *cleanups;
5581   struct abbrev_table *abbrev_table;
5582   sect_offset abbrev_offset;
5583   struct tu_abbrev_offset *sorted_by_abbrev;
5584   struct type_unit_group **iter;
5585   int i;
5586
5587   /* It's up to the caller to not call us multiple times.  */
5588   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5589
5590   if (dwarf2_per_objfile->n_type_units == 0)
5591     return;
5592
5593   /* TUs typically share abbrev tables, and there can be way more TUs than
5594      abbrev tables.  Sort by abbrev table to reduce the number of times we
5595      read each abbrev table in.
5596      Alternatives are to punt or to maintain a cache of abbrev tables.
5597      This is simpler and efficient enough for now.
5598
5599      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5600      symtab to use).  Typically TUs with the same abbrev offset have the same
5601      stmt_list value too so in practice this should work well.
5602
5603      The basic algorithm here is:
5604
5605       sort TUs by abbrev table
5606       for each TU with same abbrev table:
5607         read abbrev table if first user
5608         read TU top level DIE
5609           [IWBN if DWO skeletons had DW_AT_stmt_list]
5610         call FUNC  */
5611
5612   if (dwarf2_read_debug)
5613     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5614
5615   /* Sort in a separate table to maintain the order of all_type_units
5616      for .gdb_index: TU indices directly index all_type_units.  */
5617   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5618                               dwarf2_per_objfile->n_type_units);
5619   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5620     {
5621       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5622
5623       sorted_by_abbrev[i].sig_type = sig_type;
5624       sorted_by_abbrev[i].abbrev_offset =
5625         read_abbrev_offset (sig_type->per_cu.section,
5626                             sig_type->per_cu.offset);
5627     }
5628   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5629   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5630          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5631
5632   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5633      called any number of times, so we don't reset tu_stats here.  */
5634
5635   abbrev_offset.sect_off = ~(unsigned) 0;
5636   abbrev_table = NULL;
5637   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5638
5639   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5640     {
5641       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5642
5643       /* Switch to the next abbrev table if necessary.  */
5644       if (abbrev_table == NULL
5645           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5646         {
5647           if (abbrev_table != NULL)
5648             {
5649               abbrev_table_free (abbrev_table);
5650               /* Reset to NULL in case abbrev_table_read_table throws
5651                  an error: abbrev_table_free_cleanup will get called.  */
5652               abbrev_table = NULL;
5653             }
5654           abbrev_offset = tu->abbrev_offset;
5655           abbrev_table =
5656             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5657                                      abbrev_offset);
5658           ++tu_stats->nr_uniq_abbrev_tables;
5659         }
5660
5661       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5662                                func, data);
5663     }
5664
5665   /* type_unit_groups can be NULL if there is an error in the debug info.
5666      Just create an empty table so the rest of gdb doesn't have to watch
5667      for this error case.  */
5668   if (dwarf2_per_objfile->type_unit_groups == NULL)
5669     {
5670       dwarf2_per_objfile->type_unit_groups =
5671         allocate_type_unit_groups_table ();
5672       dwarf2_per_objfile->n_type_unit_groups = 0;
5673     }
5674
5675   /* Create a vector of pointers to primary type units to make it easy to
5676      iterate over them and CUs.  See dw2_get_primary_cu.  */
5677   dwarf2_per_objfile->n_type_unit_groups =
5678     htab_elements (dwarf2_per_objfile->type_unit_groups);
5679   dwarf2_per_objfile->all_type_unit_groups =
5680     obstack_alloc (&objfile->objfile_obstack,
5681                    dwarf2_per_objfile->n_type_unit_groups
5682                    * sizeof (struct type_unit_group *));
5683   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5684   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5685                           add_type_unit_group_to_table, &iter);
5686   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5687               == dwarf2_per_objfile->n_type_unit_groups);
5688
5689   do_cleanups (cleanups);
5690
5691   if (dwarf2_read_debug)
5692     {
5693       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5694       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5695                           dwarf2_per_objfile->n_type_units);
5696       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5697                           tu_stats->nr_uniq_abbrev_tables);
5698       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5699                           tu_stats->nr_symtabs);
5700       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5701                           tu_stats->nr_symtab_sharers);
5702       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5703                           tu_stats->nr_stmt_less_type_units);
5704     }
5705 }
5706 \f
5707 /* Partial symbol tables.  */
5708
5709 /* Create a psymtab named NAME and assign it to PER_CU.
5710
5711    The caller must fill in the following details:
5712    dirname, textlow, texthigh.  */
5713
5714 static struct partial_symtab *
5715 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5716 {
5717   struct objfile *objfile = per_cu->objfile;
5718   struct partial_symtab *pst;
5719
5720   pst = start_psymtab_common (objfile, objfile->section_offsets,
5721                               name, 0,
5722                               objfile->global_psymbols.next,
5723                               objfile->static_psymbols.next);
5724
5725   pst->psymtabs_addrmap_supported = 1;
5726
5727   /* This is the glue that links PST into GDB's symbol API.  */
5728   pst->read_symtab_private = per_cu;
5729   pst->read_symtab = dwarf2_read_symtab;
5730   per_cu->v.psymtab = pst;
5731
5732   return pst;
5733 }
5734
5735 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5736    type.  */
5737
5738 struct process_psymtab_comp_unit_data
5739 {
5740   /* True if we are reading a DW_TAG_partial_unit.  */
5741
5742   int want_partial_unit;
5743
5744   /* The "pretend" language that is used if the CU doesn't declare a
5745      language.  */
5746
5747   enum language pretend_language;
5748 };
5749
5750 /* die_reader_func for process_psymtab_comp_unit.  */
5751
5752 static void
5753 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5754                                   const gdb_byte *info_ptr,
5755                                   struct die_info *comp_unit_die,
5756                                   int has_children,
5757                                   void *data)
5758 {
5759   struct dwarf2_cu *cu = reader->cu;
5760   struct objfile *objfile = cu->objfile;
5761   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5762   struct attribute *attr;
5763   CORE_ADDR baseaddr;
5764   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5765   struct partial_symtab *pst;
5766   int has_pc_info;
5767   const char *filename;
5768   struct process_psymtab_comp_unit_data *info = data;
5769
5770   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5771     return;
5772
5773   gdb_assert (! per_cu->is_debug_types);
5774
5775   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5776
5777   cu->list_in_scope = &file_symbols;
5778
5779   /* Allocate a new partial symbol table structure.  */
5780   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5781   if (attr == NULL || !DW_STRING (attr))
5782     filename = "";
5783   else
5784     filename = DW_STRING (attr);
5785
5786   pst = create_partial_symtab (per_cu, filename);
5787
5788   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5789   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5790   if (attr != NULL)
5791     pst->dirname = DW_STRING (attr);
5792
5793   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5794
5795   dwarf2_find_base_address (comp_unit_die, cu);
5796
5797   /* Possibly set the default values of LOWPC and HIGHPC from
5798      `DW_AT_ranges'.  */
5799   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5800                                       &best_highpc, cu, pst);
5801   if (has_pc_info == 1 && best_lowpc < best_highpc)
5802     /* Store the contiguous range if it is not empty; it can be empty for
5803        CUs with no code.  */
5804     addrmap_set_empty (objfile->psymtabs_addrmap,
5805                        best_lowpc + baseaddr,
5806                        best_highpc + baseaddr - 1, pst);
5807
5808   /* Check if comp unit has_children.
5809      If so, read the rest of the partial symbols from this comp unit.
5810      If not, there's no more debug_info for this comp unit.  */
5811   if (has_children)
5812     {
5813       struct partial_die_info *first_die;
5814       CORE_ADDR lowpc, highpc;
5815
5816       lowpc = ((CORE_ADDR) -1);
5817       highpc = ((CORE_ADDR) 0);
5818
5819       first_die = load_partial_dies (reader, info_ptr, 1);
5820
5821       scan_partial_symbols (first_die, &lowpc, &highpc,
5822                             ! has_pc_info, cu);
5823
5824       /* If we didn't find a lowpc, set it to highpc to avoid
5825          complaints from `maint check'.  */
5826       if (lowpc == ((CORE_ADDR) -1))
5827         lowpc = highpc;
5828
5829       /* If the compilation unit didn't have an explicit address range,
5830          then use the information extracted from its child dies.  */
5831       if (! has_pc_info)
5832         {
5833           best_lowpc = lowpc;
5834           best_highpc = highpc;
5835         }
5836     }
5837   pst->textlow = best_lowpc + baseaddr;
5838   pst->texthigh = best_highpc + baseaddr;
5839
5840   pst->n_global_syms = objfile->global_psymbols.next -
5841     (objfile->global_psymbols.list + pst->globals_offset);
5842   pst->n_static_syms = objfile->static_psymbols.next -
5843     (objfile->static_psymbols.list + pst->statics_offset);
5844   sort_pst_symbols (objfile, pst);
5845
5846   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5847     {
5848       int i;
5849       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5850       struct dwarf2_per_cu_data *iter;
5851
5852       /* Fill in 'dependencies' here; we fill in 'users' in a
5853          post-pass.  */
5854       pst->number_of_dependencies = len;
5855       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5856                                          len * sizeof (struct symtab *));
5857       for (i = 0;
5858            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5859                         i, iter);
5860            ++i)
5861         pst->dependencies[i] = iter->v.psymtab;
5862
5863       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5864     }
5865
5866   /* Get the list of files included in the current compilation unit,
5867      and build a psymtab for each of them.  */
5868   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5869
5870   if (dwarf2_read_debug)
5871     {
5872       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5873
5874       fprintf_unfiltered (gdb_stdlog,
5875                           "Psymtab for %s unit @0x%x: %s - %s"
5876                           ", %d global, %d static syms\n",
5877                           per_cu->is_debug_types ? "type" : "comp",
5878                           per_cu->offset.sect_off,
5879                           paddress (gdbarch, pst->textlow),
5880                           paddress (gdbarch, pst->texthigh),
5881                           pst->n_global_syms, pst->n_static_syms);
5882     }
5883 }
5884
5885 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5886    Process compilation unit THIS_CU for a psymtab.  */
5887
5888 static void
5889 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5890                            int want_partial_unit,
5891                            enum language pretend_language)
5892 {
5893   struct process_psymtab_comp_unit_data info;
5894
5895   /* If this compilation unit was already read in, free the
5896      cached copy in order to read it in again.  This is
5897      necessary because we skipped some symbols when we first
5898      read in the compilation unit (see load_partial_dies).
5899      This problem could be avoided, but the benefit is unclear.  */
5900   if (this_cu->cu != NULL)
5901     free_one_cached_comp_unit (this_cu);
5902
5903   gdb_assert (! this_cu->is_debug_types);
5904   info.want_partial_unit = want_partial_unit;
5905   info.pretend_language = pretend_language;
5906   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5907                            process_psymtab_comp_unit_reader,
5908                            &info);
5909
5910   /* Age out any secondary CUs.  */
5911   age_cached_comp_units ();
5912 }
5913
5914 /* Reader function for build_type_psymtabs.  */
5915
5916 static void
5917 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5918                             const gdb_byte *info_ptr,
5919                             struct die_info *type_unit_die,
5920                             int has_children,
5921                             void *data)
5922 {
5923   struct objfile *objfile = dwarf2_per_objfile->objfile;
5924   struct dwarf2_cu *cu = reader->cu;
5925   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5926   struct signatured_type *sig_type;
5927   struct type_unit_group *tu_group;
5928   struct attribute *attr;
5929   struct partial_die_info *first_die;
5930   CORE_ADDR lowpc, highpc;
5931   struct partial_symtab *pst;
5932
5933   gdb_assert (data == NULL);
5934   gdb_assert (per_cu->is_debug_types);
5935   sig_type = (struct signatured_type *) per_cu;
5936
5937   if (! has_children)
5938     return;
5939
5940   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5941   tu_group = get_type_unit_group (cu, attr);
5942
5943   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5944
5945   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5946   cu->list_in_scope = &file_symbols;
5947   pst = create_partial_symtab (per_cu, "");
5948   pst->anonymous = 1;
5949
5950   first_die = load_partial_dies (reader, info_ptr, 1);
5951
5952   lowpc = (CORE_ADDR) -1;
5953   highpc = (CORE_ADDR) 0;
5954   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5955
5956   pst->n_global_syms = objfile->global_psymbols.next -
5957     (objfile->global_psymbols.list + pst->globals_offset);
5958   pst->n_static_syms = objfile->static_psymbols.next -
5959     (objfile->static_psymbols.list + pst->statics_offset);
5960   sort_pst_symbols (objfile, pst);
5961 }
5962
5963 /* Traversal function for build_type_psymtabs.  */
5964
5965 static int
5966 build_type_psymtab_dependencies (void **slot, void *info)
5967 {
5968   struct objfile *objfile = dwarf2_per_objfile->objfile;
5969   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5970   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5971   struct partial_symtab *pst = per_cu->v.psymtab;
5972   int len = VEC_length (sig_type_ptr, tu_group->tus);
5973   struct signatured_type *iter;
5974   int i;
5975
5976   gdb_assert (len > 0);
5977   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5978
5979   pst->number_of_dependencies = len;
5980   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5981                                      len * sizeof (struct psymtab *));
5982   for (i = 0;
5983        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5984        ++i)
5985     {
5986       gdb_assert (iter->per_cu.is_debug_types);
5987       pst->dependencies[i] = iter->per_cu.v.psymtab;
5988       iter->type_unit_group = tu_group;
5989     }
5990
5991   VEC_free (sig_type_ptr, tu_group->tus);
5992
5993   return 1;
5994 }
5995
5996 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5997    Build partial symbol tables for the .debug_types comp-units.  */
5998
5999 static void
6000 build_type_psymtabs (struct objfile *objfile)
6001 {
6002   if (! create_all_type_units (objfile))
6003     return;
6004
6005   build_type_unit_groups (build_type_psymtabs_reader, NULL);
6006
6007   /* Now that all TUs have been processed we can fill in the dependencies.  */
6008   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6009                           build_type_psymtab_dependencies, NULL);
6010 }
6011
6012 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6013
6014 static void
6015 psymtabs_addrmap_cleanup (void *o)
6016 {
6017   struct objfile *objfile = o;
6018
6019   objfile->psymtabs_addrmap = NULL;
6020 }
6021
6022 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6023
6024 static void
6025 set_partial_user (struct objfile *objfile)
6026 {
6027   int i;
6028
6029   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6030     {
6031       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6032       struct partial_symtab *pst = per_cu->v.psymtab;
6033       int j;
6034
6035       if (pst == NULL)
6036         continue;
6037
6038       for (j = 0; j < pst->number_of_dependencies; ++j)
6039         {
6040           /* Set the 'user' field only if it is not already set.  */
6041           if (pst->dependencies[j]->user == NULL)
6042             pst->dependencies[j]->user = pst;
6043         }
6044     }
6045 }
6046
6047 /* Build the partial symbol table by doing a quick pass through the
6048    .debug_info and .debug_abbrev sections.  */
6049
6050 static void
6051 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6052 {
6053   struct cleanup *back_to, *addrmap_cleanup;
6054   struct obstack temp_obstack;
6055   int i;
6056
6057   if (dwarf2_read_debug)
6058     {
6059       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6060                           objfile_name (objfile));
6061     }
6062
6063   dwarf2_per_objfile->reading_partial_symbols = 1;
6064
6065   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6066
6067   /* Any cached compilation units will be linked by the per-objfile
6068      read_in_chain.  Make sure to free them when we're done.  */
6069   back_to = make_cleanup (free_cached_comp_units, NULL);
6070
6071   build_type_psymtabs (objfile);
6072
6073   create_all_comp_units (objfile);
6074
6075   /* Create a temporary address map on a temporary obstack.  We later
6076      copy this to the final obstack.  */
6077   obstack_init (&temp_obstack);
6078   make_cleanup_obstack_free (&temp_obstack);
6079   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6080   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6081
6082   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6083     {
6084       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6085
6086       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6087     }
6088
6089   set_partial_user (objfile);
6090
6091   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6092                                                     &objfile->objfile_obstack);
6093   discard_cleanups (addrmap_cleanup);
6094
6095   do_cleanups (back_to);
6096
6097   if (dwarf2_read_debug)
6098     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6099                         objfile_name (objfile));
6100 }
6101
6102 /* die_reader_func for load_partial_comp_unit.  */
6103
6104 static void
6105 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6106                                const gdb_byte *info_ptr,
6107                                struct die_info *comp_unit_die,
6108                                int has_children,
6109                                void *data)
6110 {
6111   struct dwarf2_cu *cu = reader->cu;
6112
6113   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6114
6115   /* Check if comp unit has_children.
6116      If so, read the rest of the partial symbols from this comp unit.
6117      If not, there's no more debug_info for this comp unit.  */
6118   if (has_children)
6119     load_partial_dies (reader, info_ptr, 0);
6120 }
6121
6122 /* Load the partial DIEs for a secondary CU into memory.
6123    This is also used when rereading a primary CU with load_all_dies.  */
6124
6125 static void
6126 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6127 {
6128   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6129                            load_partial_comp_unit_reader, NULL);
6130 }
6131
6132 static void
6133 read_comp_units_from_section (struct objfile *objfile,
6134                               struct dwarf2_section_info *section,
6135                               unsigned int is_dwz,
6136                               int *n_allocated,
6137                               int *n_comp_units,
6138                               struct dwarf2_per_cu_data ***all_comp_units)
6139 {
6140   const gdb_byte *info_ptr;
6141   bfd *abfd = get_section_bfd_owner (section);
6142
6143   if (dwarf2_read_debug)
6144     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6145                         get_section_name (section),
6146                         get_section_file_name (section));
6147
6148   dwarf2_read_section (objfile, section);
6149
6150   info_ptr = section->buffer;
6151
6152   while (info_ptr < section->buffer + section->size)
6153     {
6154       unsigned int length, initial_length_size;
6155       struct dwarf2_per_cu_data *this_cu;
6156       sect_offset offset;
6157
6158       offset.sect_off = info_ptr - section->buffer;
6159
6160       /* Read just enough information to find out where the next
6161          compilation unit is.  */
6162       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6163
6164       /* Save the compilation unit for later lookup.  */
6165       this_cu = obstack_alloc (&objfile->objfile_obstack,
6166                                sizeof (struct dwarf2_per_cu_data));
6167       memset (this_cu, 0, sizeof (*this_cu));
6168       this_cu->offset = offset;
6169       this_cu->length = length + initial_length_size;
6170       this_cu->is_dwz = is_dwz;
6171       this_cu->objfile = objfile;
6172       this_cu->section = section;
6173
6174       if (*n_comp_units == *n_allocated)
6175         {
6176           *n_allocated *= 2;
6177           *all_comp_units = xrealloc (*all_comp_units,
6178                                       *n_allocated
6179                                       * sizeof (struct dwarf2_per_cu_data *));
6180         }
6181       (*all_comp_units)[*n_comp_units] = this_cu;
6182       ++*n_comp_units;
6183
6184       info_ptr = info_ptr + this_cu->length;
6185     }
6186 }
6187
6188 /* Create a list of all compilation units in OBJFILE.
6189    This is only done for -readnow and building partial symtabs.  */
6190
6191 static void
6192 create_all_comp_units (struct objfile *objfile)
6193 {
6194   int n_allocated;
6195   int n_comp_units;
6196   struct dwarf2_per_cu_data **all_comp_units;
6197   struct dwz_file *dwz;
6198
6199   n_comp_units = 0;
6200   n_allocated = 10;
6201   all_comp_units = xmalloc (n_allocated
6202                             * sizeof (struct dwarf2_per_cu_data *));
6203
6204   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6205                                 &n_allocated, &n_comp_units, &all_comp_units);
6206
6207   dwz = dwarf2_get_dwz_file ();
6208   if (dwz != NULL)
6209     read_comp_units_from_section (objfile, &dwz->info, 1,
6210                                   &n_allocated, &n_comp_units,
6211                                   &all_comp_units);
6212
6213   dwarf2_per_objfile->all_comp_units
6214     = obstack_alloc (&objfile->objfile_obstack,
6215                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6216   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6217           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6218   xfree (all_comp_units);
6219   dwarf2_per_objfile->n_comp_units = n_comp_units;
6220 }
6221
6222 /* Process all loaded DIEs for compilation unit CU, starting at
6223    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6224    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6225    DW_AT_ranges).  If NEED_PC is set, then this function will set
6226    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6227    and record the covered ranges in the addrmap.  */
6228
6229 static void
6230 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6231                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6232 {
6233   struct partial_die_info *pdi;
6234
6235   /* Now, march along the PDI's, descending into ones which have
6236      interesting children but skipping the children of the other ones,
6237      until we reach the end of the compilation unit.  */
6238
6239   pdi = first_die;
6240
6241   while (pdi != NULL)
6242     {
6243       fixup_partial_die (pdi, cu);
6244
6245       /* Anonymous namespaces or modules have no name but have interesting
6246          children, so we need to look at them.  Ditto for anonymous
6247          enums.  */
6248
6249       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6250           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6251           || pdi->tag == DW_TAG_imported_unit)
6252         {
6253           switch (pdi->tag)
6254             {
6255             case DW_TAG_subprogram:
6256               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6257               break;
6258             case DW_TAG_constant:
6259             case DW_TAG_variable:
6260             case DW_TAG_typedef:
6261             case DW_TAG_union_type:
6262               if (!pdi->is_declaration)
6263                 {
6264                   add_partial_symbol (pdi, cu);
6265                 }
6266               break;
6267             case DW_TAG_class_type:
6268             case DW_TAG_interface_type:
6269             case DW_TAG_structure_type:
6270               if (!pdi->is_declaration)
6271                 {
6272                   add_partial_symbol (pdi, cu);
6273                 }
6274               break;
6275             case DW_TAG_enumeration_type:
6276               if (!pdi->is_declaration)
6277                 add_partial_enumeration (pdi, cu);
6278               break;
6279             case DW_TAG_base_type:
6280             case DW_TAG_subrange_type:
6281               /* File scope base type definitions are added to the partial
6282                  symbol table.  */
6283               add_partial_symbol (pdi, cu);
6284               break;
6285             case DW_TAG_namespace:
6286               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6287               break;
6288             case DW_TAG_module:
6289               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6290               break;
6291             case DW_TAG_imported_unit:
6292               {
6293                 struct dwarf2_per_cu_data *per_cu;
6294
6295                 /* For now we don't handle imported units in type units.  */
6296                 if (cu->per_cu->is_debug_types)
6297                   {
6298                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6299                              " supported in type units [in module %s]"),
6300                            objfile_name (cu->objfile));
6301                   }
6302
6303                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6304                                                            pdi->is_dwz,
6305                                                            cu->objfile);
6306
6307                 /* Go read the partial unit, if needed.  */
6308                 if (per_cu->v.psymtab == NULL)
6309                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6310
6311                 VEC_safe_push (dwarf2_per_cu_ptr,
6312                                cu->per_cu->imported_symtabs, per_cu);
6313               }
6314               break;
6315             default:
6316               break;
6317             }
6318         }
6319
6320       /* If the die has a sibling, skip to the sibling.  */
6321
6322       pdi = pdi->die_sibling;
6323     }
6324 }
6325
6326 /* Functions used to compute the fully scoped name of a partial DIE.
6327
6328    Normally, this is simple.  For C++, the parent DIE's fully scoped
6329    name is concatenated with "::" and the partial DIE's name.  For
6330    Java, the same thing occurs except that "." is used instead of "::".
6331    Enumerators are an exception; they use the scope of their parent
6332    enumeration type, i.e. the name of the enumeration type is not
6333    prepended to the enumerator.
6334
6335    There are two complexities.  One is DW_AT_specification; in this
6336    case "parent" means the parent of the target of the specification,
6337    instead of the direct parent of the DIE.  The other is compilers
6338    which do not emit DW_TAG_namespace; in this case we try to guess
6339    the fully qualified name of structure types from their members'
6340    linkage names.  This must be done using the DIE's children rather
6341    than the children of any DW_AT_specification target.  We only need
6342    to do this for structures at the top level, i.e. if the target of
6343    any DW_AT_specification (if any; otherwise the DIE itself) does not
6344    have a parent.  */
6345
6346 /* Compute the scope prefix associated with PDI's parent, in
6347    compilation unit CU.  The result will be allocated on CU's
6348    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6349    field.  NULL is returned if no prefix is necessary.  */
6350 static const char *
6351 partial_die_parent_scope (struct partial_die_info *pdi,
6352                           struct dwarf2_cu *cu)
6353 {
6354   const char *grandparent_scope;
6355   struct partial_die_info *parent, *real_pdi;
6356
6357   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6358      then this means the parent of the specification DIE.  */
6359
6360   real_pdi = pdi;
6361   while (real_pdi->has_specification)
6362     real_pdi = find_partial_die (real_pdi->spec_offset,
6363                                  real_pdi->spec_is_dwz, cu);
6364
6365   parent = real_pdi->die_parent;
6366   if (parent == NULL)
6367     return NULL;
6368
6369   if (parent->scope_set)
6370     return parent->scope;
6371
6372   fixup_partial_die (parent, cu);
6373
6374   grandparent_scope = partial_die_parent_scope (parent, cu);
6375
6376   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6377      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6378      Work around this problem here.  */
6379   if (cu->language == language_cplus
6380       && parent->tag == DW_TAG_namespace
6381       && strcmp (parent->name, "::") == 0
6382       && grandparent_scope == NULL)
6383     {
6384       parent->scope = NULL;
6385       parent->scope_set = 1;
6386       return NULL;
6387     }
6388
6389   if (pdi->tag == DW_TAG_enumerator)
6390     /* Enumerators should not get the name of the enumeration as a prefix.  */
6391     parent->scope = grandparent_scope;
6392   else if (parent->tag == DW_TAG_namespace
6393       || parent->tag == DW_TAG_module
6394       || parent->tag == DW_TAG_structure_type
6395       || parent->tag == DW_TAG_class_type
6396       || parent->tag == DW_TAG_interface_type
6397       || parent->tag == DW_TAG_union_type
6398       || parent->tag == DW_TAG_enumeration_type)
6399     {
6400       if (grandparent_scope == NULL)
6401         parent->scope = parent->name;
6402       else
6403         parent->scope = typename_concat (&cu->comp_unit_obstack,
6404                                          grandparent_scope,
6405                                          parent->name, 0, cu);
6406     }
6407   else
6408     {
6409       /* FIXME drow/2004-04-01: What should we be doing with
6410          function-local names?  For partial symbols, we should probably be
6411          ignoring them.  */
6412       complaint (&symfile_complaints,
6413                  _("unhandled containing DIE tag %d for DIE at %d"),
6414                  parent->tag, pdi->offset.sect_off);
6415       parent->scope = grandparent_scope;
6416     }
6417
6418   parent->scope_set = 1;
6419   return parent->scope;
6420 }
6421
6422 /* Return the fully scoped name associated with PDI, from compilation unit
6423    CU.  The result will be allocated with malloc.  */
6424
6425 static char *
6426 partial_die_full_name (struct partial_die_info *pdi,
6427                        struct dwarf2_cu *cu)
6428 {
6429   const char *parent_scope;
6430
6431   /* If this is a template instantiation, we can not work out the
6432      template arguments from partial DIEs.  So, unfortunately, we have
6433      to go through the full DIEs.  At least any work we do building
6434      types here will be reused if full symbols are loaded later.  */
6435   if (pdi->has_template_arguments)
6436     {
6437       fixup_partial_die (pdi, cu);
6438
6439       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6440         {
6441           struct die_info *die;
6442           struct attribute attr;
6443           struct dwarf2_cu *ref_cu = cu;
6444
6445           /* DW_FORM_ref_addr is using section offset.  */
6446           attr.name = 0;
6447           attr.form = DW_FORM_ref_addr;
6448           attr.u.unsnd = pdi->offset.sect_off;
6449           die = follow_die_ref (NULL, &attr, &ref_cu);
6450
6451           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6452         }
6453     }
6454
6455   parent_scope = partial_die_parent_scope (pdi, cu);
6456   if (parent_scope == NULL)
6457     return NULL;
6458   else
6459     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6460 }
6461
6462 static void
6463 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6464 {
6465   struct objfile *objfile = cu->objfile;
6466   CORE_ADDR addr = 0;
6467   const char *actual_name = NULL;
6468   CORE_ADDR baseaddr;
6469   char *built_actual_name;
6470
6471   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6472
6473   built_actual_name = partial_die_full_name (pdi, cu);
6474   if (built_actual_name != NULL)
6475     actual_name = built_actual_name;
6476
6477   if (actual_name == NULL)
6478     actual_name = pdi->name;
6479
6480   switch (pdi->tag)
6481     {
6482     case DW_TAG_subprogram:
6483       if (pdi->is_external || cu->language == language_ada)
6484         {
6485           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6486              of the global scope.  But in Ada, we want to be able to access
6487              nested procedures globally.  So all Ada subprograms are stored
6488              in the global scope.  */
6489           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6490              mst_text, objfile); */
6491           add_psymbol_to_list (actual_name, strlen (actual_name),
6492                                built_actual_name != NULL,
6493                                VAR_DOMAIN, LOC_BLOCK,
6494                                &objfile->global_psymbols,
6495                                0, pdi->lowpc + baseaddr,
6496                                cu->language, objfile);
6497         }
6498       else
6499         {
6500           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6501              mst_file_text, objfile); */
6502           add_psymbol_to_list (actual_name, strlen (actual_name),
6503                                built_actual_name != NULL,
6504                                VAR_DOMAIN, LOC_BLOCK,
6505                                &objfile->static_psymbols,
6506                                0, pdi->lowpc + baseaddr,
6507                                cu->language, objfile);
6508         }
6509       break;
6510     case DW_TAG_constant:
6511       {
6512         struct psymbol_allocation_list *list;
6513
6514         if (pdi->is_external)
6515           list = &objfile->global_psymbols;
6516         else
6517           list = &objfile->static_psymbols;
6518         add_psymbol_to_list (actual_name, strlen (actual_name),
6519                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6520                              list, 0, 0, cu->language, objfile);
6521       }
6522       break;
6523     case DW_TAG_variable:
6524       if (pdi->d.locdesc)
6525         addr = decode_locdesc (pdi->d.locdesc, cu);
6526
6527       if (pdi->d.locdesc
6528           && addr == 0
6529           && !dwarf2_per_objfile->has_section_at_zero)
6530         {
6531           /* A global or static variable may also have been stripped
6532              out by the linker if unused, in which case its address
6533              will be nullified; do not add such variables into partial
6534              symbol table then.  */
6535         }
6536       else if (pdi->is_external)
6537         {
6538           /* Global Variable.
6539              Don't enter into the minimal symbol tables as there is
6540              a minimal symbol table entry from the ELF symbols already.
6541              Enter into partial symbol table if it has a location
6542              descriptor or a type.
6543              If the location descriptor is missing, new_symbol will create
6544              a LOC_UNRESOLVED symbol, the address of the variable will then
6545              be determined from the minimal symbol table whenever the variable
6546              is referenced.
6547              The address for the partial symbol table entry is not
6548              used by GDB, but it comes in handy for debugging partial symbol
6549              table building.  */
6550
6551           if (pdi->d.locdesc || pdi->has_type)
6552             add_psymbol_to_list (actual_name, strlen (actual_name),
6553                                  built_actual_name != NULL,
6554                                  VAR_DOMAIN, LOC_STATIC,
6555                                  &objfile->global_psymbols,
6556                                  0, addr + baseaddr,
6557                                  cu->language, objfile);
6558         }
6559       else
6560         {
6561           /* Static Variable.  Skip symbols without location descriptors.  */
6562           if (pdi->d.locdesc == NULL)
6563             {
6564               xfree (built_actual_name);
6565               return;
6566             }
6567           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6568              mst_file_data, objfile); */
6569           add_psymbol_to_list (actual_name, strlen (actual_name),
6570                                built_actual_name != NULL,
6571                                VAR_DOMAIN, LOC_STATIC,
6572                                &objfile->static_psymbols,
6573                                0, addr + baseaddr,
6574                                cu->language, objfile);
6575         }
6576       break;
6577     case DW_TAG_typedef:
6578     case DW_TAG_base_type:
6579     case DW_TAG_subrange_type:
6580       add_psymbol_to_list (actual_name, strlen (actual_name),
6581                            built_actual_name != NULL,
6582                            VAR_DOMAIN, LOC_TYPEDEF,
6583                            &objfile->static_psymbols,
6584                            0, (CORE_ADDR) 0, cu->language, objfile);
6585       break;
6586     case DW_TAG_namespace:
6587       add_psymbol_to_list (actual_name, strlen (actual_name),
6588                            built_actual_name != NULL,
6589                            VAR_DOMAIN, LOC_TYPEDEF,
6590                            &objfile->global_psymbols,
6591                            0, (CORE_ADDR) 0, cu->language, objfile);
6592       break;
6593     case DW_TAG_class_type:
6594     case DW_TAG_interface_type:
6595     case DW_TAG_structure_type:
6596     case DW_TAG_union_type:
6597     case DW_TAG_enumeration_type:
6598       /* Skip external references.  The DWARF standard says in the section
6599          about "Structure, Union, and Class Type Entries": "An incomplete
6600          structure, union or class type is represented by a structure,
6601          union or class entry that does not have a byte size attribute
6602          and that has a DW_AT_declaration attribute."  */
6603       if (!pdi->has_byte_size && pdi->is_declaration)
6604         {
6605           xfree (built_actual_name);
6606           return;
6607         }
6608
6609       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6610          static vs. global.  */
6611       add_psymbol_to_list (actual_name, strlen (actual_name),
6612                            built_actual_name != NULL,
6613                            STRUCT_DOMAIN, LOC_TYPEDEF,
6614                            (cu->language == language_cplus
6615                             || cu->language == language_java)
6616                            ? &objfile->global_psymbols
6617                            : &objfile->static_psymbols,
6618                            0, (CORE_ADDR) 0, cu->language, objfile);
6619
6620       break;
6621     case DW_TAG_enumerator:
6622       add_psymbol_to_list (actual_name, strlen (actual_name),
6623                            built_actual_name != NULL,
6624                            VAR_DOMAIN, LOC_CONST,
6625                            (cu->language == language_cplus
6626                             || cu->language == language_java)
6627                            ? &objfile->global_psymbols
6628                            : &objfile->static_psymbols,
6629                            0, (CORE_ADDR) 0, cu->language, objfile);
6630       break;
6631     default:
6632       break;
6633     }
6634
6635   xfree (built_actual_name);
6636 }
6637
6638 /* Read a partial die corresponding to a namespace; also, add a symbol
6639    corresponding to that namespace to the symbol table.  NAMESPACE is
6640    the name of the enclosing namespace.  */
6641
6642 static void
6643 add_partial_namespace (struct partial_die_info *pdi,
6644                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6645                        int need_pc, struct dwarf2_cu *cu)
6646 {
6647   /* Add a symbol for the namespace.  */
6648
6649   add_partial_symbol (pdi, cu);
6650
6651   /* Now scan partial symbols in that namespace.  */
6652
6653   if (pdi->has_children)
6654     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6655 }
6656
6657 /* Read a partial die corresponding to a Fortran module.  */
6658
6659 static void
6660 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6661                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6662 {
6663   /* Now scan partial symbols in that module.  */
6664
6665   if (pdi->has_children)
6666     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6667 }
6668
6669 /* Read a partial die corresponding to a subprogram and create a partial
6670    symbol for that subprogram.  When the CU language allows it, this
6671    routine also defines a partial symbol for each nested subprogram
6672    that this subprogram contains.
6673
6674    DIE my also be a lexical block, in which case we simply search
6675    recursively for suprograms defined inside that lexical block.
6676    Again, this is only performed when the CU language allows this
6677    type of definitions.  */
6678
6679 static void
6680 add_partial_subprogram (struct partial_die_info *pdi,
6681                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6682                         int need_pc, struct dwarf2_cu *cu)
6683 {
6684   if (pdi->tag == DW_TAG_subprogram)
6685     {
6686       if (pdi->has_pc_info)
6687         {
6688           if (pdi->lowpc < *lowpc)
6689             *lowpc = pdi->lowpc;
6690           if (pdi->highpc > *highpc)
6691             *highpc = pdi->highpc;
6692           if (need_pc)
6693             {
6694               CORE_ADDR baseaddr;
6695               struct objfile *objfile = cu->objfile;
6696
6697               baseaddr = ANOFFSET (objfile->section_offsets,
6698                                    SECT_OFF_TEXT (objfile));
6699               addrmap_set_empty (objfile->psymtabs_addrmap,
6700                                  pdi->lowpc + baseaddr,
6701                                  pdi->highpc - 1 + baseaddr,
6702                                  cu->per_cu->v.psymtab);
6703             }
6704         }
6705
6706       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6707         {
6708           if (!pdi->is_declaration)
6709             /* Ignore subprogram DIEs that do not have a name, they are
6710                illegal.  Do not emit a complaint at this point, we will
6711                do so when we convert this psymtab into a symtab.  */
6712             if (pdi->name)
6713               add_partial_symbol (pdi, cu);
6714         }
6715     }
6716
6717   if (! pdi->has_children)
6718     return;
6719
6720   if (cu->language == language_ada)
6721     {
6722       pdi = pdi->die_child;
6723       while (pdi != NULL)
6724         {
6725           fixup_partial_die (pdi, cu);
6726           if (pdi->tag == DW_TAG_subprogram
6727               || pdi->tag == DW_TAG_lexical_block)
6728             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6729           pdi = pdi->die_sibling;
6730         }
6731     }
6732 }
6733
6734 /* Read a partial die corresponding to an enumeration type.  */
6735
6736 static void
6737 add_partial_enumeration (struct partial_die_info *enum_pdi,
6738                          struct dwarf2_cu *cu)
6739 {
6740   struct partial_die_info *pdi;
6741
6742   if (enum_pdi->name != NULL)
6743     add_partial_symbol (enum_pdi, cu);
6744
6745   pdi = enum_pdi->die_child;
6746   while (pdi)
6747     {
6748       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6749         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6750       else
6751         add_partial_symbol (pdi, cu);
6752       pdi = pdi->die_sibling;
6753     }
6754 }
6755
6756 /* Return the initial uleb128 in the die at INFO_PTR.  */
6757
6758 static unsigned int
6759 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6760 {
6761   unsigned int bytes_read;
6762
6763   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6764 }
6765
6766 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6767    Return the corresponding abbrev, or NULL if the number is zero (indicating
6768    an empty DIE).  In either case *BYTES_READ will be set to the length of
6769    the initial number.  */
6770
6771 static struct abbrev_info *
6772 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6773                  struct dwarf2_cu *cu)
6774 {
6775   bfd *abfd = cu->objfile->obfd;
6776   unsigned int abbrev_number;
6777   struct abbrev_info *abbrev;
6778
6779   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6780
6781   if (abbrev_number == 0)
6782     return NULL;
6783
6784   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6785   if (!abbrev)
6786     {
6787       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6788              abbrev_number, bfd_get_filename (abfd));
6789     }
6790
6791   return abbrev;
6792 }
6793
6794 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6795    Returns a pointer to the end of a series of DIEs, terminated by an empty
6796    DIE.  Any children of the skipped DIEs will also be skipped.  */
6797
6798 static const gdb_byte *
6799 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6800 {
6801   struct dwarf2_cu *cu = reader->cu;
6802   struct abbrev_info *abbrev;
6803   unsigned int bytes_read;
6804
6805   while (1)
6806     {
6807       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6808       if (abbrev == NULL)
6809         return info_ptr + bytes_read;
6810       else
6811         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6812     }
6813 }
6814
6815 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6816    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6817    abbrev corresponding to that skipped uleb128 should be passed in
6818    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6819    children.  */
6820
6821 static const gdb_byte *
6822 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6823               struct abbrev_info *abbrev)
6824 {
6825   unsigned int bytes_read;
6826   struct attribute attr;
6827   bfd *abfd = reader->abfd;
6828   struct dwarf2_cu *cu = reader->cu;
6829   const gdb_byte *buffer = reader->buffer;
6830   const gdb_byte *buffer_end = reader->buffer_end;
6831   const gdb_byte *start_info_ptr = info_ptr;
6832   unsigned int form, i;
6833
6834   for (i = 0; i < abbrev->num_attrs; i++)
6835     {
6836       /* The only abbrev we care about is DW_AT_sibling.  */
6837       if (abbrev->attrs[i].name == DW_AT_sibling)
6838         {
6839           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6840           if (attr.form == DW_FORM_ref_addr)
6841             complaint (&symfile_complaints,
6842                        _("ignoring absolute DW_AT_sibling"));
6843           else
6844             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6845         }
6846
6847       /* If it isn't DW_AT_sibling, skip this attribute.  */
6848       form = abbrev->attrs[i].form;
6849     skip_attribute:
6850       switch (form)
6851         {
6852         case DW_FORM_ref_addr:
6853           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6854              and later it is offset sized.  */
6855           if (cu->header.version == 2)
6856             info_ptr += cu->header.addr_size;
6857           else
6858             info_ptr += cu->header.offset_size;
6859           break;
6860         case DW_FORM_GNU_ref_alt:
6861           info_ptr += cu->header.offset_size;
6862           break;
6863         case DW_FORM_addr:
6864           info_ptr += cu->header.addr_size;
6865           break;
6866         case DW_FORM_data1:
6867         case DW_FORM_ref1:
6868         case DW_FORM_flag:
6869           info_ptr += 1;
6870           break;
6871         case DW_FORM_flag_present:
6872           break;
6873         case DW_FORM_data2:
6874         case DW_FORM_ref2:
6875           info_ptr += 2;
6876           break;
6877         case DW_FORM_data4:
6878         case DW_FORM_ref4:
6879           info_ptr += 4;
6880           break;
6881         case DW_FORM_data8:
6882         case DW_FORM_ref8:
6883         case DW_FORM_ref_sig8:
6884           info_ptr += 8;
6885           break;
6886         case DW_FORM_string:
6887           read_direct_string (abfd, info_ptr, &bytes_read);
6888           info_ptr += bytes_read;
6889           break;
6890         case DW_FORM_sec_offset:
6891         case DW_FORM_strp:
6892         case DW_FORM_GNU_strp_alt:
6893           info_ptr += cu->header.offset_size;
6894           break;
6895         case DW_FORM_exprloc:
6896         case DW_FORM_block:
6897           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6898           info_ptr += bytes_read;
6899           break;
6900         case DW_FORM_block1:
6901           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6902           break;
6903         case DW_FORM_block2:
6904           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6905           break;
6906         case DW_FORM_block4:
6907           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6908           break;
6909         case DW_FORM_sdata:
6910         case DW_FORM_udata:
6911         case DW_FORM_ref_udata:
6912         case DW_FORM_GNU_addr_index:
6913         case DW_FORM_GNU_str_index:
6914           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6915           break;
6916         case DW_FORM_indirect:
6917           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6918           info_ptr += bytes_read;
6919           /* We need to continue parsing from here, so just go back to
6920              the top.  */
6921           goto skip_attribute;
6922
6923         default:
6924           error (_("Dwarf Error: Cannot handle %s "
6925                    "in DWARF reader [in module %s]"),
6926                  dwarf_form_name (form),
6927                  bfd_get_filename (abfd));
6928         }
6929     }
6930
6931   if (abbrev->has_children)
6932     return skip_children (reader, info_ptr);
6933   else
6934     return info_ptr;
6935 }
6936
6937 /* Locate ORIG_PDI's sibling.
6938    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6939
6940 static const gdb_byte *
6941 locate_pdi_sibling (const struct die_reader_specs *reader,
6942                     struct partial_die_info *orig_pdi,
6943                     const gdb_byte *info_ptr)
6944 {
6945   /* Do we know the sibling already?  */
6946
6947   if (orig_pdi->sibling)
6948     return orig_pdi->sibling;
6949
6950   /* Are there any children to deal with?  */
6951
6952   if (!orig_pdi->has_children)
6953     return info_ptr;
6954
6955   /* Skip the children the long way.  */
6956
6957   return skip_children (reader, info_ptr);
6958 }
6959
6960 /* Expand this partial symbol table into a full symbol table.  SELF is
6961    not NULL.  */
6962
6963 static void
6964 dwarf2_read_symtab (struct partial_symtab *self,
6965                     struct objfile *objfile)
6966 {
6967   if (self->readin)
6968     {
6969       warning (_("bug: psymtab for %s is already read in."),
6970                self->filename);
6971     }
6972   else
6973     {
6974       if (info_verbose)
6975         {
6976           printf_filtered (_("Reading in symbols for %s..."),
6977                            self->filename);
6978           gdb_flush (gdb_stdout);
6979         }
6980
6981       /* Restore our global data.  */
6982       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6983
6984       /* If this psymtab is constructed from a debug-only objfile, the
6985          has_section_at_zero flag will not necessarily be correct.  We
6986          can get the correct value for this flag by looking at the data
6987          associated with the (presumably stripped) associated objfile.  */
6988       if (objfile->separate_debug_objfile_backlink)
6989         {
6990           struct dwarf2_per_objfile *dpo_backlink
6991             = objfile_data (objfile->separate_debug_objfile_backlink,
6992                             dwarf2_objfile_data_key);
6993
6994           dwarf2_per_objfile->has_section_at_zero
6995             = dpo_backlink->has_section_at_zero;
6996         }
6997
6998       dwarf2_per_objfile->reading_partial_symbols = 0;
6999
7000       psymtab_to_symtab_1 (self);
7001
7002       /* Finish up the debug error message.  */
7003       if (info_verbose)
7004         printf_filtered (_("done.\n"));
7005     }
7006
7007   process_cu_includes ();
7008 }
7009 \f
7010 /* Reading in full CUs.  */
7011
7012 /* Add PER_CU to the queue.  */
7013
7014 static void
7015 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7016                  enum language pretend_language)
7017 {
7018   struct dwarf2_queue_item *item;
7019
7020   per_cu->queued = 1;
7021   item = xmalloc (sizeof (*item));
7022   item->per_cu = per_cu;
7023   item->pretend_language = pretend_language;
7024   item->next = NULL;
7025
7026   if (dwarf2_queue == NULL)
7027     dwarf2_queue = item;
7028   else
7029     dwarf2_queue_tail->next = item;
7030
7031   dwarf2_queue_tail = item;
7032 }
7033
7034 /* If PER_CU is not yet queued, add it to the queue.
7035    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7036    dependency.
7037    The result is non-zero if PER_CU was queued, otherwise the result is zero
7038    meaning either PER_CU is already queued or it is already loaded.
7039
7040    N.B. There is an invariant here that if a CU is queued then it is loaded.
7041    The caller is required to load PER_CU if we return non-zero.  */
7042
7043 static int
7044 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7045                        struct dwarf2_per_cu_data *per_cu,
7046                        enum language pretend_language)
7047 {
7048   /* We may arrive here during partial symbol reading, if we need full
7049      DIEs to process an unusual case (e.g. template arguments).  Do
7050      not queue PER_CU, just tell our caller to load its DIEs.  */
7051   if (dwarf2_per_objfile->reading_partial_symbols)
7052     {
7053       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7054         return 1;
7055       return 0;
7056     }
7057
7058   /* Mark the dependence relation so that we don't flush PER_CU
7059      too early.  */
7060   if (dependent_cu != NULL)
7061     dwarf2_add_dependence (dependent_cu, per_cu);
7062
7063   /* If it's already on the queue, we have nothing to do.  */
7064   if (per_cu->queued)
7065     return 0;
7066
7067   /* If the compilation unit is already loaded, just mark it as
7068      used.  */
7069   if (per_cu->cu != NULL)
7070     {
7071       per_cu->cu->last_used = 0;
7072       return 0;
7073     }
7074
7075   /* Add it to the queue.  */
7076   queue_comp_unit (per_cu, pretend_language);
7077
7078   return 1;
7079 }
7080
7081 /* Process the queue.  */
7082
7083 static void
7084 process_queue (void)
7085 {
7086   struct dwarf2_queue_item *item, *next_item;
7087
7088   if (dwarf2_read_debug)
7089     {
7090       fprintf_unfiltered (gdb_stdlog,
7091                           "Expanding one or more symtabs of objfile %s ...\n",
7092                           objfile_name (dwarf2_per_objfile->objfile));
7093     }
7094
7095   /* The queue starts out with one item, but following a DIE reference
7096      may load a new CU, adding it to the end of the queue.  */
7097   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7098     {
7099       if (dwarf2_per_objfile->using_index
7100           ? !item->per_cu->v.quick->symtab
7101           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7102         {
7103           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7104           char buf[100];
7105
7106           if (per_cu->is_debug_types)
7107             {
7108               struct signatured_type *sig_type =
7109                 (struct signatured_type *) per_cu;
7110
7111               sprintf (buf, "TU %s at offset 0x%x",
7112                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7113             }
7114           else
7115             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7116
7117           if (dwarf2_read_debug)
7118             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7119
7120           if (per_cu->is_debug_types)
7121             process_full_type_unit (per_cu, item->pretend_language);
7122           else
7123             process_full_comp_unit (per_cu, item->pretend_language);
7124
7125           if (dwarf2_read_debug)
7126             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7127         }
7128
7129       item->per_cu->queued = 0;
7130       next_item = item->next;
7131       xfree (item);
7132     }
7133
7134   dwarf2_queue_tail = NULL;
7135
7136   if (dwarf2_read_debug)
7137     {
7138       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7139                           objfile_name (dwarf2_per_objfile->objfile));
7140     }
7141 }
7142
7143 /* Free all allocated queue entries.  This function only releases anything if
7144    an error was thrown; if the queue was processed then it would have been
7145    freed as we went along.  */
7146
7147 static void
7148 dwarf2_release_queue (void *dummy)
7149 {
7150   struct dwarf2_queue_item *item, *last;
7151
7152   item = dwarf2_queue;
7153   while (item)
7154     {
7155       /* Anything still marked queued is likely to be in an
7156          inconsistent state, so discard it.  */
7157       if (item->per_cu->queued)
7158         {
7159           if (item->per_cu->cu != NULL)
7160             free_one_cached_comp_unit (item->per_cu);
7161           item->per_cu->queued = 0;
7162         }
7163
7164       last = item;
7165       item = item->next;
7166       xfree (last);
7167     }
7168
7169   dwarf2_queue = dwarf2_queue_tail = NULL;
7170 }
7171
7172 /* Read in full symbols for PST, and anything it depends on.  */
7173
7174 static void
7175 psymtab_to_symtab_1 (struct partial_symtab *pst)
7176 {
7177   struct dwarf2_per_cu_data *per_cu;
7178   int i;
7179
7180   if (pst->readin)
7181     return;
7182
7183   for (i = 0; i < pst->number_of_dependencies; i++)
7184     if (!pst->dependencies[i]->readin
7185         && pst->dependencies[i]->user == NULL)
7186       {
7187         /* Inform about additional files that need to be read in.  */
7188         if (info_verbose)
7189           {
7190             /* FIXME: i18n: Need to make this a single string.  */
7191             fputs_filtered (" ", gdb_stdout);
7192             wrap_here ("");
7193             fputs_filtered ("and ", gdb_stdout);
7194             wrap_here ("");
7195             printf_filtered ("%s...", pst->dependencies[i]->filename);
7196             wrap_here ("");     /* Flush output.  */
7197             gdb_flush (gdb_stdout);
7198           }
7199         psymtab_to_symtab_1 (pst->dependencies[i]);
7200       }
7201
7202   per_cu = pst->read_symtab_private;
7203
7204   if (per_cu == NULL)
7205     {
7206       /* It's an include file, no symbols to read for it.
7207          Everything is in the parent symtab.  */
7208       pst->readin = 1;
7209       return;
7210     }
7211
7212   dw2_do_instantiate_symtab (per_cu);
7213 }
7214
7215 /* Trivial hash function for die_info: the hash value of a DIE
7216    is its offset in .debug_info for this objfile.  */
7217
7218 static hashval_t
7219 die_hash (const void *item)
7220 {
7221   const struct die_info *die = item;
7222
7223   return die->offset.sect_off;
7224 }
7225
7226 /* Trivial comparison function for die_info structures: two DIEs
7227    are equal if they have the same offset.  */
7228
7229 static int
7230 die_eq (const void *item_lhs, const void *item_rhs)
7231 {
7232   const struct die_info *die_lhs = item_lhs;
7233   const struct die_info *die_rhs = item_rhs;
7234
7235   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7236 }
7237
7238 /* die_reader_func for load_full_comp_unit.
7239    This is identical to read_signatured_type_reader,
7240    but is kept separate for now.  */
7241
7242 static void
7243 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7244                             const gdb_byte *info_ptr,
7245                             struct die_info *comp_unit_die,
7246                             int has_children,
7247                             void *data)
7248 {
7249   struct dwarf2_cu *cu = reader->cu;
7250   enum language *language_ptr = data;
7251
7252   gdb_assert (cu->die_hash == NULL);
7253   cu->die_hash =
7254     htab_create_alloc_ex (cu->header.length / 12,
7255                           die_hash,
7256                           die_eq,
7257                           NULL,
7258                           &cu->comp_unit_obstack,
7259                           hashtab_obstack_allocate,
7260                           dummy_obstack_deallocate);
7261
7262   if (has_children)
7263     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7264                                                   &info_ptr, comp_unit_die);
7265   cu->dies = comp_unit_die;
7266   /* comp_unit_die is not stored in die_hash, no need.  */
7267
7268   /* We try not to read any attributes in this function, because not
7269      all CUs needed for references have been loaded yet, and symbol
7270      table processing isn't initialized.  But we have to set the CU language,
7271      or we won't be able to build types correctly.
7272      Similarly, if we do not read the producer, we can not apply
7273      producer-specific interpretation.  */
7274   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7275 }
7276
7277 /* Load the DIEs associated with PER_CU into memory.  */
7278
7279 static void
7280 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7281                      enum language pretend_language)
7282 {
7283   gdb_assert (! this_cu->is_debug_types);
7284
7285   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7286                            load_full_comp_unit_reader, &pretend_language);
7287 }
7288
7289 /* Add a DIE to the delayed physname list.  */
7290
7291 static void
7292 add_to_method_list (struct type *type, int fnfield_index, int index,
7293                     const char *name, struct die_info *die,
7294                     struct dwarf2_cu *cu)
7295 {
7296   struct delayed_method_info mi;
7297   mi.type = type;
7298   mi.fnfield_index = fnfield_index;
7299   mi.index = index;
7300   mi.name = name;
7301   mi.die = die;
7302   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7303 }
7304
7305 /* A cleanup for freeing the delayed method list.  */
7306
7307 static void
7308 free_delayed_list (void *ptr)
7309 {
7310   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7311   if (cu->method_list != NULL)
7312     {
7313       VEC_free (delayed_method_info, cu->method_list);
7314       cu->method_list = NULL;
7315     }
7316 }
7317
7318 /* Compute the physnames of any methods on the CU's method list.
7319
7320    The computation of method physnames is delayed in order to avoid the
7321    (bad) condition that one of the method's formal parameters is of an as yet
7322    incomplete type.  */
7323
7324 static void
7325 compute_delayed_physnames (struct dwarf2_cu *cu)
7326 {
7327   int i;
7328   struct delayed_method_info *mi;
7329   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7330     {
7331       const char *physname;
7332       struct fn_fieldlist *fn_flp
7333         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7334       physname = dwarf2_physname (mi->name, mi->die, cu);
7335       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7336     }
7337 }
7338
7339 /* Go objects should be embedded in a DW_TAG_module DIE,
7340    and it's not clear if/how imported objects will appear.
7341    To keep Go support simple until that's worked out,
7342    go back through what we've read and create something usable.
7343    We could do this while processing each DIE, and feels kinda cleaner,
7344    but that way is more invasive.
7345    This is to, for example, allow the user to type "p var" or "b main"
7346    without having to specify the package name, and allow lookups
7347    of module.object to work in contexts that use the expression
7348    parser.  */
7349
7350 static void
7351 fixup_go_packaging (struct dwarf2_cu *cu)
7352 {
7353   char *package_name = NULL;
7354   struct pending *list;
7355   int i;
7356
7357   for (list = global_symbols; list != NULL; list = list->next)
7358     {
7359       for (i = 0; i < list->nsyms; ++i)
7360         {
7361           struct symbol *sym = list->symbol[i];
7362
7363           if (SYMBOL_LANGUAGE (sym) == language_go
7364               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7365             {
7366               char *this_package_name = go_symbol_package_name (sym);
7367
7368               if (this_package_name == NULL)
7369                 continue;
7370               if (package_name == NULL)
7371                 package_name = this_package_name;
7372               else
7373                 {
7374                   if (strcmp (package_name, this_package_name) != 0)
7375                     complaint (&symfile_complaints,
7376                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7377                                (SYMBOL_SYMTAB (sym)
7378                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7379                                 : objfile_name (cu->objfile)),
7380                                this_package_name, package_name);
7381                   xfree (this_package_name);
7382                 }
7383             }
7384         }
7385     }
7386
7387   if (package_name != NULL)
7388     {
7389       struct objfile *objfile = cu->objfile;
7390       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7391                                                       package_name,
7392                                                       strlen (package_name));
7393       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7394                                      saved_package_name, objfile);
7395       struct symbol *sym;
7396
7397       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7398
7399       sym = allocate_symbol (objfile);
7400       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7401       SYMBOL_SET_NAMES (sym, saved_package_name,
7402                         strlen (saved_package_name), 0, objfile);
7403       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7404          e.g., "main" finds the "main" module and not C's main().  */
7405       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7406       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7407       SYMBOL_TYPE (sym) = type;
7408
7409       add_symbol_to_list (sym, &global_symbols);
7410
7411       xfree (package_name);
7412     }
7413 }
7414
7415 /* Return the symtab for PER_CU.  This works properly regardless of
7416    whether we're using the index or psymtabs.  */
7417
7418 static struct symtab *
7419 get_symtab (struct dwarf2_per_cu_data *per_cu)
7420 {
7421   return (dwarf2_per_objfile->using_index
7422           ? per_cu->v.quick->symtab
7423           : per_cu->v.psymtab->symtab);
7424 }
7425
7426 /* A helper function for computing the list of all symbol tables
7427    included by PER_CU.  */
7428
7429 static void
7430 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7431                                 htab_t all_children, htab_t all_type_symtabs,
7432                                 struct dwarf2_per_cu_data *per_cu,
7433                                 struct symtab *immediate_parent)
7434 {
7435   void **slot;
7436   int ix;
7437   struct symtab *symtab;
7438   struct dwarf2_per_cu_data *iter;
7439
7440   slot = htab_find_slot (all_children, per_cu, INSERT);
7441   if (*slot != NULL)
7442     {
7443       /* This inclusion and its children have been processed.  */
7444       return;
7445     }
7446
7447   *slot = per_cu;
7448   /* Only add a CU if it has a symbol table.  */
7449   symtab = get_symtab (per_cu);
7450   if (symtab != NULL)
7451     {
7452       /* If this is a type unit only add its symbol table if we haven't
7453          seen it yet (type unit per_cu's can share symtabs).  */
7454       if (per_cu->is_debug_types)
7455         {
7456           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7457           if (*slot == NULL)
7458             {
7459               *slot = symtab;
7460               VEC_safe_push (symtab_ptr, *result, symtab);
7461               if (symtab->user == NULL)
7462                 symtab->user = immediate_parent;
7463             }
7464         }
7465       else
7466         {
7467           VEC_safe_push (symtab_ptr, *result, symtab);
7468           if (symtab->user == NULL)
7469             symtab->user = immediate_parent;
7470         }
7471     }
7472
7473   for (ix = 0;
7474        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7475        ++ix)
7476     {
7477       recursively_compute_inclusions (result, all_children,
7478                                       all_type_symtabs, iter, symtab);
7479     }
7480 }
7481
7482 /* Compute the symtab 'includes' fields for the symtab related to
7483    PER_CU.  */
7484
7485 static void
7486 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7487 {
7488   gdb_assert (! per_cu->is_debug_types);
7489
7490   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7491     {
7492       int ix, len;
7493       struct dwarf2_per_cu_data *per_cu_iter;
7494       struct symtab *symtab_iter;
7495       VEC (symtab_ptr) *result_symtabs = NULL;
7496       htab_t all_children, all_type_symtabs;
7497       struct symtab *symtab = get_symtab (per_cu);
7498
7499       /* If we don't have a symtab, we can just skip this case.  */
7500       if (symtab == NULL)
7501         return;
7502
7503       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7504                                         NULL, xcalloc, xfree);
7505       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7506                                             NULL, xcalloc, xfree);
7507
7508       for (ix = 0;
7509            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7510                         ix, per_cu_iter);
7511            ++ix)
7512         {
7513           recursively_compute_inclusions (&result_symtabs, all_children,
7514                                           all_type_symtabs, per_cu_iter,
7515                                           symtab);
7516         }
7517
7518       /* Now we have a transitive closure of all the included symtabs.  */
7519       len = VEC_length (symtab_ptr, result_symtabs);
7520       symtab->includes
7521         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7522                          (len + 1) * sizeof (struct symtab *));
7523       for (ix = 0;
7524            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7525            ++ix)
7526         symtab->includes[ix] = symtab_iter;
7527       symtab->includes[len] = NULL;
7528
7529       VEC_free (symtab_ptr, result_symtabs);
7530       htab_delete (all_children);
7531       htab_delete (all_type_symtabs);
7532     }
7533 }
7534
7535 /* Compute the 'includes' field for the symtabs of all the CUs we just
7536    read.  */
7537
7538 static void
7539 process_cu_includes (void)
7540 {
7541   int ix;
7542   struct dwarf2_per_cu_data *iter;
7543
7544   for (ix = 0;
7545        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7546                     ix, iter);
7547        ++ix)
7548     {
7549       if (! iter->is_debug_types)
7550         compute_symtab_includes (iter);
7551     }
7552
7553   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7554 }
7555
7556 /* Generate full symbol information for PER_CU, whose DIEs have
7557    already been loaded into memory.  */
7558
7559 static void
7560 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7561                         enum language pretend_language)
7562 {
7563   struct dwarf2_cu *cu = per_cu->cu;
7564   struct objfile *objfile = per_cu->objfile;
7565   CORE_ADDR lowpc, highpc;
7566   struct symtab *symtab;
7567   struct cleanup *back_to, *delayed_list_cleanup;
7568   CORE_ADDR baseaddr;
7569   struct block *static_block;
7570
7571   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7572
7573   buildsym_init ();
7574   back_to = make_cleanup (really_free_pendings, NULL);
7575   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7576
7577   cu->list_in_scope = &file_symbols;
7578
7579   cu->language = pretend_language;
7580   cu->language_defn = language_def (cu->language);
7581
7582   /* Do line number decoding in read_file_scope () */
7583   process_die (cu->dies, cu);
7584
7585   /* For now fudge the Go package.  */
7586   if (cu->language == language_go)
7587     fixup_go_packaging (cu);
7588
7589   /* Now that we have processed all the DIEs in the CU, all the types 
7590      should be complete, and it should now be safe to compute all of the
7591      physnames.  */
7592   compute_delayed_physnames (cu);
7593   do_cleanups (delayed_list_cleanup);
7594
7595   /* Some compilers don't define a DW_AT_high_pc attribute for the
7596      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7597      it, by scanning the DIE's below the compilation unit.  */
7598   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7599
7600   static_block
7601     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7602
7603   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7604      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7605      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7606      addrmap to help ensure it has an accurate map of pc values belonging to
7607      this comp unit.  */
7608   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7609
7610   symtab = end_symtab_from_static_block (static_block, objfile,
7611                                          SECT_OFF_TEXT (objfile), 0);
7612
7613   if (symtab != NULL)
7614     {
7615       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7616
7617       /* Set symtab language to language from DW_AT_language.  If the
7618          compilation is from a C file generated by language preprocessors, do
7619          not set the language if it was already deduced by start_subfile.  */
7620       if (!(cu->language == language_c && symtab->language != language_c))
7621         symtab->language = cu->language;
7622
7623       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7624          produce DW_AT_location with location lists but it can be possibly
7625          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7626          there were bugs in prologue debug info, fixed later in GCC-4.5
7627          by "unwind info for epilogues" patch (which is not directly related).
7628
7629          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7630          needed, it would be wrong due to missing DW_AT_producer there.
7631
7632          Still one can confuse GDB by using non-standard GCC compilation
7633          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7634          */ 
7635       if (cu->has_loclist && gcc_4_minor >= 5)
7636         symtab->locations_valid = 1;
7637
7638       if (gcc_4_minor >= 5)
7639         symtab->epilogue_unwind_valid = 1;
7640
7641       symtab->call_site_htab = cu->call_site_htab;
7642     }
7643
7644   if (dwarf2_per_objfile->using_index)
7645     per_cu->v.quick->symtab = symtab;
7646   else
7647     {
7648       struct partial_symtab *pst = per_cu->v.psymtab;
7649       pst->symtab = symtab;
7650       pst->readin = 1;
7651     }
7652
7653   /* Push it for inclusion processing later.  */
7654   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7655
7656   do_cleanups (back_to);
7657 }
7658
7659 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7660    already been loaded into memory.  */
7661
7662 static void
7663 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7664                         enum language pretend_language)
7665 {
7666   struct dwarf2_cu *cu = per_cu->cu;
7667   struct objfile *objfile = per_cu->objfile;
7668   struct symtab *symtab;
7669   struct cleanup *back_to, *delayed_list_cleanup;
7670   struct signatured_type *sig_type;
7671
7672   gdb_assert (per_cu->is_debug_types);
7673   sig_type = (struct signatured_type *) per_cu;
7674
7675   buildsym_init ();
7676   back_to = make_cleanup (really_free_pendings, NULL);
7677   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7678
7679   cu->list_in_scope = &file_symbols;
7680
7681   cu->language = pretend_language;
7682   cu->language_defn = language_def (cu->language);
7683
7684   /* The symbol tables are set up in read_type_unit_scope.  */
7685   process_die (cu->dies, cu);
7686
7687   /* For now fudge the Go package.  */
7688   if (cu->language == language_go)
7689     fixup_go_packaging (cu);
7690
7691   /* Now that we have processed all the DIEs in the CU, all the types 
7692      should be complete, and it should now be safe to compute all of the
7693      physnames.  */
7694   compute_delayed_physnames (cu);
7695   do_cleanups (delayed_list_cleanup);
7696
7697   /* TUs share symbol tables.
7698      If this is the first TU to use this symtab, complete the construction
7699      of it with end_expandable_symtab.  Otherwise, complete the addition of
7700      this TU's symbols to the existing symtab.  */
7701   if (sig_type->type_unit_group->primary_symtab == NULL)
7702     {
7703       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7704       sig_type->type_unit_group->primary_symtab = symtab;
7705
7706       if (symtab != NULL)
7707         {
7708           /* Set symtab language to language from DW_AT_language.  If the
7709              compilation is from a C file generated by language preprocessors,
7710              do not set the language if it was already deduced by
7711              start_subfile.  */
7712           if (!(cu->language == language_c && symtab->language != language_c))
7713             symtab->language = cu->language;
7714         }
7715     }
7716   else
7717     {
7718       augment_type_symtab (objfile,
7719                            sig_type->type_unit_group->primary_symtab);
7720       symtab = sig_type->type_unit_group->primary_symtab;
7721     }
7722
7723   if (dwarf2_per_objfile->using_index)
7724     per_cu->v.quick->symtab = symtab;
7725   else
7726     {
7727       struct partial_symtab *pst = per_cu->v.psymtab;
7728       pst->symtab = symtab;
7729       pst->readin = 1;
7730     }
7731
7732   do_cleanups (back_to);
7733 }
7734
7735 /* Process an imported unit DIE.  */
7736
7737 static void
7738 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7739 {
7740   struct attribute *attr;
7741
7742   /* For now we don't handle imported units in type units.  */
7743   if (cu->per_cu->is_debug_types)
7744     {
7745       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7746                " supported in type units [in module %s]"),
7747              objfile_name (cu->objfile));
7748     }
7749
7750   attr = dwarf2_attr (die, DW_AT_import, cu);
7751   if (attr != NULL)
7752     {
7753       struct dwarf2_per_cu_data *per_cu;
7754       struct symtab *imported_symtab;
7755       sect_offset offset;
7756       int is_dwz;
7757
7758       offset = dwarf2_get_ref_die_offset (attr);
7759       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7760       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7761
7762       /* If necessary, add it to the queue and load its DIEs.  */
7763       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7764         load_full_comp_unit (per_cu, cu->language);
7765
7766       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7767                      per_cu);
7768     }
7769 }
7770
7771 /* Process a die and its children.  */
7772
7773 static void
7774 process_die (struct die_info *die, struct dwarf2_cu *cu)
7775 {
7776   switch (die->tag)
7777     {
7778     case DW_TAG_padding:
7779       break;
7780     case DW_TAG_compile_unit:
7781     case DW_TAG_partial_unit:
7782       read_file_scope (die, cu);
7783       break;
7784     case DW_TAG_type_unit:
7785       read_type_unit_scope (die, cu);
7786       break;
7787     case DW_TAG_subprogram:
7788     case DW_TAG_inlined_subroutine:
7789       read_func_scope (die, cu);
7790       break;
7791     case DW_TAG_lexical_block:
7792     case DW_TAG_try_block:
7793     case DW_TAG_catch_block:
7794       read_lexical_block_scope (die, cu);
7795       break;
7796     case DW_TAG_GNU_call_site:
7797       read_call_site_scope (die, cu);
7798       break;
7799     case DW_TAG_class_type:
7800     case DW_TAG_interface_type:
7801     case DW_TAG_structure_type:
7802     case DW_TAG_union_type:
7803       process_structure_scope (die, cu);
7804       break;
7805     case DW_TAG_enumeration_type:
7806       process_enumeration_scope (die, cu);
7807       break;
7808
7809     /* These dies have a type, but processing them does not create
7810        a symbol or recurse to process the children.  Therefore we can
7811        read them on-demand through read_type_die.  */
7812     case DW_TAG_subroutine_type:
7813     case DW_TAG_set_type:
7814     case DW_TAG_array_type:
7815     case DW_TAG_pointer_type:
7816     case DW_TAG_ptr_to_member_type:
7817     case DW_TAG_reference_type:
7818     case DW_TAG_string_type:
7819       break;
7820
7821     case DW_TAG_base_type:
7822     case DW_TAG_subrange_type:
7823     case DW_TAG_typedef:
7824       /* Add a typedef symbol for the type definition, if it has a
7825          DW_AT_name.  */
7826       new_symbol (die, read_type_die (die, cu), cu);
7827       break;
7828     case DW_TAG_common_block:
7829       read_common_block (die, cu);
7830       break;
7831     case DW_TAG_common_inclusion:
7832       break;
7833     case DW_TAG_namespace:
7834       cu->processing_has_namespace_info = 1;
7835       read_namespace (die, cu);
7836       break;
7837     case DW_TAG_module:
7838       cu->processing_has_namespace_info = 1;
7839       read_module (die, cu);
7840       break;
7841     case DW_TAG_imported_declaration:
7842     case DW_TAG_imported_module:
7843       cu->processing_has_namespace_info = 1;
7844       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7845                                  || cu->language != language_fortran))
7846         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7847                    dwarf_tag_name (die->tag));
7848       read_import_statement (die, cu);
7849       break;
7850
7851     case DW_TAG_imported_unit:
7852       process_imported_unit_die (die, cu);
7853       break;
7854
7855     default:
7856       new_symbol (die, NULL, cu);
7857       break;
7858     }
7859 }
7860 \f
7861 /* DWARF name computation.  */
7862
7863 /* A helper function for dwarf2_compute_name which determines whether DIE
7864    needs to have the name of the scope prepended to the name listed in the
7865    die.  */
7866
7867 static int
7868 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7869 {
7870   struct attribute *attr;
7871
7872   switch (die->tag)
7873     {
7874     case DW_TAG_namespace:
7875     case DW_TAG_typedef:
7876     case DW_TAG_class_type:
7877     case DW_TAG_interface_type:
7878     case DW_TAG_structure_type:
7879     case DW_TAG_union_type:
7880     case DW_TAG_enumeration_type:
7881     case DW_TAG_enumerator:
7882     case DW_TAG_subprogram:
7883     case DW_TAG_member:
7884       return 1;
7885
7886     case DW_TAG_variable:
7887     case DW_TAG_constant:
7888       /* We only need to prefix "globally" visible variables.  These include
7889          any variable marked with DW_AT_external or any variable that
7890          lives in a namespace.  [Variables in anonymous namespaces
7891          require prefixing, but they are not DW_AT_external.]  */
7892
7893       if (dwarf2_attr (die, DW_AT_specification, cu))
7894         {
7895           struct dwarf2_cu *spec_cu = cu;
7896
7897           return die_needs_namespace (die_specification (die, &spec_cu),
7898                                       spec_cu);
7899         }
7900
7901       attr = dwarf2_attr (die, DW_AT_external, cu);
7902       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7903           && die->parent->tag != DW_TAG_module)
7904         return 0;
7905       /* A variable in a lexical block of some kind does not need a
7906          namespace, even though in C++ such variables may be external
7907          and have a mangled name.  */
7908       if (die->parent->tag ==  DW_TAG_lexical_block
7909           || die->parent->tag ==  DW_TAG_try_block
7910           || die->parent->tag ==  DW_TAG_catch_block
7911           || die->parent->tag == DW_TAG_subprogram)
7912         return 0;
7913       return 1;
7914
7915     default:
7916       return 0;
7917     }
7918 }
7919
7920 /* Retrieve the last character from a mem_file.  */
7921
7922 static void
7923 do_ui_file_peek_last (void *object, const char *buffer, long length)
7924 {
7925   char *last_char_p = (char *) object;
7926
7927   if (length > 0)
7928     *last_char_p = buffer[length - 1];
7929 }
7930
7931 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7932    compute the physname for the object, which include a method's:
7933    - formal parameters (C++/Java),
7934    - receiver type (Go),
7935    - return type (Java).
7936
7937    The term "physname" is a bit confusing.
7938    For C++, for example, it is the demangled name.
7939    For Go, for example, it's the mangled name.
7940
7941    For Ada, return the DIE's linkage name rather than the fully qualified
7942    name.  PHYSNAME is ignored..
7943
7944    The result is allocated on the objfile_obstack and canonicalized.  */
7945
7946 static const char *
7947 dwarf2_compute_name (const char *name,
7948                      struct die_info *die, struct dwarf2_cu *cu,
7949                      int physname)
7950 {
7951   struct objfile *objfile = cu->objfile;
7952
7953   if (name == NULL)
7954     name = dwarf2_name (die, cu);
7955
7956   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7957      compute it by typename_concat inside GDB.  */
7958   if (cu->language == language_ada
7959       || (cu->language == language_fortran && physname))
7960     {
7961       /* For Ada unit, we prefer the linkage name over the name, as
7962          the former contains the exported name, which the user expects
7963          to be able to reference.  Ideally, we want the user to be able
7964          to reference this entity using either natural or linkage name,
7965          but we haven't started looking at this enhancement yet.  */
7966       struct attribute *attr;
7967
7968       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7969       if (attr == NULL)
7970         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7971       if (attr && DW_STRING (attr))
7972         return DW_STRING (attr);
7973     }
7974
7975   /* These are the only languages we know how to qualify names in.  */
7976   if (name != NULL
7977       && (cu->language == language_cplus || cu->language == language_java
7978           || cu->language == language_fortran))
7979     {
7980       if (die_needs_namespace (die, cu))
7981         {
7982           long length;
7983           const char *prefix;
7984           struct ui_file *buf;
7985
7986           prefix = determine_prefix (die, cu);
7987           buf = mem_fileopen ();
7988           if (*prefix != '\0')
7989             {
7990               char *prefixed_name = typename_concat (NULL, prefix, name,
7991                                                      physname, cu);
7992
7993               fputs_unfiltered (prefixed_name, buf);
7994               xfree (prefixed_name);
7995             }
7996           else
7997             fputs_unfiltered (name, buf);
7998
7999           /* Template parameters may be specified in the DIE's DW_AT_name, or
8000              as children with DW_TAG_template_type_param or
8001              DW_TAG_value_type_param.  If the latter, add them to the name
8002              here.  If the name already has template parameters, then
8003              skip this step; some versions of GCC emit both, and
8004              it is more efficient to use the pre-computed name.
8005
8006              Something to keep in mind about this process: it is very
8007              unlikely, or in some cases downright impossible, to produce
8008              something that will match the mangled name of a function.
8009              If the definition of the function has the same debug info,
8010              we should be able to match up with it anyway.  But fallbacks
8011              using the minimal symbol, for instance to find a method
8012              implemented in a stripped copy of libstdc++, will not work.
8013              If we do not have debug info for the definition, we will have to
8014              match them up some other way.
8015
8016              When we do name matching there is a related problem with function
8017              templates; two instantiated function templates are allowed to
8018              differ only by their return types, which we do not add here.  */
8019
8020           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8021             {
8022               struct attribute *attr;
8023               struct die_info *child;
8024               int first = 1;
8025
8026               die->building_fullname = 1;
8027
8028               for (child = die->child; child != NULL; child = child->sibling)
8029                 {
8030                   struct type *type;
8031                   LONGEST value;
8032                   const gdb_byte *bytes;
8033                   struct dwarf2_locexpr_baton *baton;
8034                   struct value *v;
8035
8036                   if (child->tag != DW_TAG_template_type_param
8037                       && child->tag != DW_TAG_template_value_param)
8038                     continue;
8039
8040                   if (first)
8041                     {
8042                       fputs_unfiltered ("<", buf);
8043                       first = 0;
8044                     }
8045                   else
8046                     fputs_unfiltered (", ", buf);
8047
8048                   attr = dwarf2_attr (child, DW_AT_type, cu);
8049                   if (attr == NULL)
8050                     {
8051                       complaint (&symfile_complaints,
8052                                  _("template parameter missing DW_AT_type"));
8053                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
8054                       continue;
8055                     }
8056                   type = die_type (child, cu);
8057
8058                   if (child->tag == DW_TAG_template_type_param)
8059                     {
8060                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8061                       continue;
8062                     }
8063
8064                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8065                   if (attr == NULL)
8066                     {
8067                       complaint (&symfile_complaints,
8068                                  _("template parameter missing "
8069                                    "DW_AT_const_value"));
8070                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8071                       continue;
8072                     }
8073
8074                   dwarf2_const_value_attr (attr, type, name,
8075                                            &cu->comp_unit_obstack, cu,
8076                                            &value, &bytes, &baton);
8077
8078                   if (TYPE_NOSIGN (type))
8079                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8080                        changed, this can use value_print instead.  */
8081                     c_printchar (value, type, buf);
8082                   else
8083                     {
8084                       struct value_print_options opts;
8085
8086                       if (baton != NULL)
8087                         v = dwarf2_evaluate_loc_desc (type, NULL,
8088                                                       baton->data,
8089                                                       baton->size,
8090                                                       baton->per_cu);
8091                       else if (bytes != NULL)
8092                         {
8093                           v = allocate_value (type);
8094                           memcpy (value_contents_writeable (v), bytes,
8095                                   TYPE_LENGTH (type));
8096                         }
8097                       else
8098                         v = value_from_longest (type, value);
8099
8100                       /* Specify decimal so that we do not depend on
8101                          the radix.  */
8102                       get_formatted_print_options (&opts, 'd');
8103                       opts.raw = 1;
8104                       value_print (v, buf, &opts);
8105                       release_value (v);
8106                       value_free (v);
8107                     }
8108                 }
8109
8110               die->building_fullname = 0;
8111
8112               if (!first)
8113                 {
8114                   /* Close the argument list, with a space if necessary
8115                      (nested templates).  */
8116                   char last_char = '\0';
8117                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8118                   if (last_char == '>')
8119                     fputs_unfiltered (" >", buf);
8120                   else
8121                     fputs_unfiltered (">", buf);
8122                 }
8123             }
8124
8125           /* For Java and C++ methods, append formal parameter type
8126              information, if PHYSNAME.  */
8127
8128           if (physname && die->tag == DW_TAG_subprogram
8129               && (cu->language == language_cplus
8130                   || cu->language == language_java))
8131             {
8132               struct type *type = read_type_die (die, cu);
8133
8134               c_type_print_args (type, buf, 1, cu->language,
8135                                  &type_print_raw_options);
8136
8137               if (cu->language == language_java)
8138                 {
8139                   /* For java, we must append the return type to method
8140                      names.  */
8141                   if (die->tag == DW_TAG_subprogram)
8142                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8143                                      0, 0, &type_print_raw_options);
8144                 }
8145               else if (cu->language == language_cplus)
8146                 {
8147                   /* Assume that an artificial first parameter is
8148                      "this", but do not crash if it is not.  RealView
8149                      marks unnamed (and thus unused) parameters as
8150                      artificial; there is no way to differentiate
8151                      the two cases.  */
8152                   if (TYPE_NFIELDS (type) > 0
8153                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8154                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8155                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8156                                                                         0))))
8157                     fputs_unfiltered (" const", buf);
8158                 }
8159             }
8160
8161           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8162                                        &length);
8163           ui_file_delete (buf);
8164
8165           if (cu->language == language_cplus)
8166             {
8167               const char *cname
8168                 = dwarf2_canonicalize_name (name, cu,
8169                                             &objfile->objfile_obstack);
8170
8171               if (cname != NULL)
8172                 name = cname;
8173             }
8174         }
8175     }
8176
8177   return name;
8178 }
8179
8180 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8181    If scope qualifiers are appropriate they will be added.  The result
8182    will be allocated on the objfile_obstack, or NULL if the DIE does
8183    not have a name.  NAME may either be from a previous call to
8184    dwarf2_name or NULL.
8185
8186    The output string will be canonicalized (if C++/Java).  */
8187
8188 static const char *
8189 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8190 {
8191   return dwarf2_compute_name (name, die, cu, 0);
8192 }
8193
8194 /* Construct a physname for the given DIE in CU.  NAME may either be
8195    from a previous call to dwarf2_name or NULL.  The result will be
8196    allocated on the objfile_objstack or NULL if the DIE does not have a
8197    name.
8198
8199    The output string will be canonicalized (if C++/Java).  */
8200
8201 static const char *
8202 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8203 {
8204   struct objfile *objfile = cu->objfile;
8205   struct attribute *attr;
8206   const char *retval, *mangled = NULL, *canon = NULL;
8207   struct cleanup *back_to;
8208   int need_copy = 1;
8209
8210   /* In this case dwarf2_compute_name is just a shortcut not building anything
8211      on its own.  */
8212   if (!die_needs_namespace (die, cu))
8213     return dwarf2_compute_name (name, die, cu, 1);
8214
8215   back_to = make_cleanup (null_cleanup, NULL);
8216
8217   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8218   if (!attr)
8219     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8220
8221   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8222      has computed.  */
8223   if (attr && DW_STRING (attr))
8224     {
8225       char *demangled;
8226
8227       mangled = DW_STRING (attr);
8228
8229       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8230          type.  It is easier for GDB users to search for such functions as
8231          `name(params)' than `long name(params)'.  In such case the minimal
8232          symbol names do not match the full symbol names but for template
8233          functions there is never a need to look up their definition from their
8234          declaration so the only disadvantage remains the minimal symbol
8235          variant `long name(params)' does not have the proper inferior type.
8236          */
8237
8238       if (cu->language == language_go)
8239         {
8240           /* This is a lie, but we already lie to the caller new_symbol_full.
8241              new_symbol_full assumes we return the mangled name.
8242              This just undoes that lie until things are cleaned up.  */
8243           demangled = NULL;
8244         }
8245       else
8246         {
8247           demangled = gdb_demangle (mangled,
8248                                     (DMGL_PARAMS | DMGL_ANSI
8249                                      | (cu->language == language_java
8250                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8251                                         : DMGL_RET_DROP)));
8252         }
8253       if (demangled)
8254         {
8255           make_cleanup (xfree, demangled);
8256           canon = demangled;
8257         }
8258       else
8259         {
8260           canon = mangled;
8261           need_copy = 0;
8262         }
8263     }
8264
8265   if (canon == NULL || check_physname)
8266     {
8267       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8268
8269       if (canon != NULL && strcmp (physname, canon) != 0)
8270         {
8271           /* It may not mean a bug in GDB.  The compiler could also
8272              compute DW_AT_linkage_name incorrectly.  But in such case
8273              GDB would need to be bug-to-bug compatible.  */
8274
8275           complaint (&symfile_complaints,
8276                      _("Computed physname <%s> does not match demangled <%s> "
8277                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8278                      physname, canon, mangled, die->offset.sect_off,
8279                      objfile_name (objfile));
8280
8281           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8282              is available here - over computed PHYSNAME.  It is safer
8283              against both buggy GDB and buggy compilers.  */
8284
8285           retval = canon;
8286         }
8287       else
8288         {
8289           retval = physname;
8290           need_copy = 0;
8291         }
8292     }
8293   else
8294     retval = canon;
8295
8296   if (need_copy)
8297     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8298
8299   do_cleanups (back_to);
8300   return retval;
8301 }
8302
8303 /* Read the import statement specified by the given die and record it.  */
8304
8305 static void
8306 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8307 {
8308   struct objfile *objfile = cu->objfile;
8309   struct attribute *import_attr;
8310   struct die_info *imported_die, *child_die;
8311   struct dwarf2_cu *imported_cu;
8312   const char *imported_name;
8313   const char *imported_name_prefix;
8314   const char *canonical_name;
8315   const char *import_alias;
8316   const char *imported_declaration = NULL;
8317   const char *import_prefix;
8318   VEC (const_char_ptr) *excludes = NULL;
8319   struct cleanup *cleanups;
8320
8321   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8322   if (import_attr == NULL)
8323     {
8324       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8325                  dwarf_tag_name (die->tag));
8326       return;
8327     }
8328
8329   imported_cu = cu;
8330   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8331   imported_name = dwarf2_name (imported_die, imported_cu);
8332   if (imported_name == NULL)
8333     {
8334       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8335
8336         The import in the following code:
8337         namespace A
8338           {
8339             typedef int B;
8340           }
8341
8342         int main ()
8343           {
8344             using A::B;
8345             B b;
8346             return b;
8347           }
8348
8349         ...
8350          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8351             <52>   DW_AT_decl_file   : 1
8352             <53>   DW_AT_decl_line   : 6
8353             <54>   DW_AT_import      : <0x75>
8354          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8355             <59>   DW_AT_name        : B
8356             <5b>   DW_AT_decl_file   : 1
8357             <5c>   DW_AT_decl_line   : 2
8358             <5d>   DW_AT_type        : <0x6e>
8359         ...
8360          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8361             <76>   DW_AT_byte_size   : 4
8362             <77>   DW_AT_encoding    : 5        (signed)
8363
8364         imports the wrong die ( 0x75 instead of 0x58 ).
8365         This case will be ignored until the gcc bug is fixed.  */
8366       return;
8367     }
8368
8369   /* Figure out the local name after import.  */
8370   import_alias = dwarf2_name (die, cu);
8371
8372   /* Figure out where the statement is being imported to.  */
8373   import_prefix = determine_prefix (die, cu);
8374
8375   /* Figure out what the scope of the imported die is and prepend it
8376      to the name of the imported die.  */
8377   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8378
8379   if (imported_die->tag != DW_TAG_namespace
8380       && imported_die->tag != DW_TAG_module)
8381     {
8382       imported_declaration = imported_name;
8383       canonical_name = imported_name_prefix;
8384     }
8385   else if (strlen (imported_name_prefix) > 0)
8386     canonical_name = obconcat (&objfile->objfile_obstack,
8387                                imported_name_prefix, "::", imported_name,
8388                                (char *) NULL);
8389   else
8390     canonical_name = imported_name;
8391
8392   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8393
8394   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8395     for (child_die = die->child; child_die && child_die->tag;
8396          child_die = sibling_die (child_die))
8397       {
8398         /* DWARF-4: A Fortran use statement with a “rename list” may be
8399            represented by an imported module entry with an import attribute
8400            referring to the module and owned entries corresponding to those
8401            entities that are renamed as part of being imported.  */
8402
8403         if (child_die->tag != DW_TAG_imported_declaration)
8404           {
8405             complaint (&symfile_complaints,
8406                        _("child DW_TAG_imported_declaration expected "
8407                          "- DIE at 0x%x [in module %s]"),
8408                        child_die->offset.sect_off, objfile_name (objfile));
8409             continue;
8410           }
8411
8412         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8413         if (import_attr == NULL)
8414           {
8415             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8416                        dwarf_tag_name (child_die->tag));
8417             continue;
8418           }
8419
8420         imported_cu = cu;
8421         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8422                                               &imported_cu);
8423         imported_name = dwarf2_name (imported_die, imported_cu);
8424         if (imported_name == NULL)
8425           {
8426             complaint (&symfile_complaints,
8427                        _("child DW_TAG_imported_declaration has unknown "
8428                          "imported name - DIE at 0x%x [in module %s]"),
8429                        child_die->offset.sect_off, objfile_name (objfile));
8430             continue;
8431           }
8432
8433         VEC_safe_push (const_char_ptr, excludes, imported_name);
8434
8435         process_die (child_die, cu);
8436       }
8437
8438   cp_add_using_directive (import_prefix,
8439                           canonical_name,
8440                           import_alias,
8441                           imported_declaration,
8442                           excludes,
8443                           0,
8444                           &objfile->objfile_obstack);
8445
8446   do_cleanups (cleanups);
8447 }
8448
8449 /* Cleanup function for handle_DW_AT_stmt_list.  */
8450
8451 static void
8452 free_cu_line_header (void *arg)
8453 {
8454   struct dwarf2_cu *cu = arg;
8455
8456   free_line_header (cu->line_header);
8457   cu->line_header = NULL;
8458 }
8459
8460 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8461    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8462    this, it was first present in GCC release 4.3.0.  */
8463
8464 static int
8465 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8466 {
8467   if (!cu->checked_producer)
8468     check_producer (cu);
8469
8470   return cu->producer_is_gcc_lt_4_3;
8471 }
8472
8473 static void
8474 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8475                          const char **name, const char **comp_dir)
8476 {
8477   struct attribute *attr;
8478
8479   *name = NULL;
8480   *comp_dir = NULL;
8481
8482   /* Find the filename.  Do not use dwarf2_name here, since the filename
8483      is not a source language identifier.  */
8484   attr = dwarf2_attr (die, DW_AT_name, cu);
8485   if (attr)
8486     {
8487       *name = DW_STRING (attr);
8488     }
8489
8490   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8491   if (attr)
8492     *comp_dir = DW_STRING (attr);
8493   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8494            && IS_ABSOLUTE_PATH (*name))
8495     {
8496       char *d = ldirname (*name);
8497
8498       *comp_dir = d;
8499       if (d != NULL)
8500         make_cleanup (xfree, d);
8501     }
8502   if (*comp_dir != NULL)
8503     {
8504       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8505          directory, get rid of it.  */
8506       char *cp = strchr (*comp_dir, ':');
8507
8508       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8509         *comp_dir = cp + 1;
8510     }
8511
8512   if (*name == NULL)
8513     *name = "<unknown>";
8514 }
8515
8516 /* Handle DW_AT_stmt_list for a compilation unit.
8517    DIE is the DW_TAG_compile_unit die for CU.
8518    COMP_DIR is the compilation directory.
8519    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8520
8521 static void
8522 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8523                         const char *comp_dir) /* ARI: editCase function */
8524 {
8525   struct attribute *attr;
8526
8527   gdb_assert (! cu->per_cu->is_debug_types);
8528
8529   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8530   if (attr)
8531     {
8532       unsigned int line_offset = DW_UNSND (attr);
8533       struct line_header *line_header
8534         = dwarf_decode_line_header (line_offset, cu);
8535
8536       if (line_header)
8537         {
8538           cu->line_header = line_header;
8539           make_cleanup (free_cu_line_header, cu);
8540           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8541         }
8542     }
8543 }
8544
8545 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8546
8547 static void
8548 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8549 {
8550   struct objfile *objfile = dwarf2_per_objfile->objfile;
8551   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8552   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8553   CORE_ADDR highpc = ((CORE_ADDR) 0);
8554   struct attribute *attr;
8555   const char *name = NULL;
8556   const char *comp_dir = NULL;
8557   struct die_info *child_die;
8558   bfd *abfd = objfile->obfd;
8559   CORE_ADDR baseaddr;
8560
8561   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8562
8563   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8564
8565   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8566      from finish_block.  */
8567   if (lowpc == ((CORE_ADDR) -1))
8568     lowpc = highpc;
8569   lowpc += baseaddr;
8570   highpc += baseaddr;
8571
8572   find_file_and_directory (die, cu, &name, &comp_dir);
8573
8574   prepare_one_comp_unit (cu, die, cu->language);
8575
8576   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8577      standardised yet.  As a workaround for the language detection we fall
8578      back to the DW_AT_producer string.  */
8579   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8580     cu->language = language_opencl;
8581
8582   /* Similar hack for Go.  */
8583   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8584     set_cu_language (DW_LANG_Go, cu);
8585
8586   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8587
8588   /* Decode line number information if present.  We do this before
8589      processing child DIEs, so that the line header table is available
8590      for DW_AT_decl_file.  */
8591   handle_DW_AT_stmt_list (die, cu, comp_dir);
8592
8593   /* Process all dies in compilation unit.  */
8594   if (die->child != NULL)
8595     {
8596       child_die = die->child;
8597       while (child_die && child_die->tag)
8598         {
8599           process_die (child_die, cu);
8600           child_die = sibling_die (child_die);
8601         }
8602     }
8603
8604   /* Decode macro information, if present.  Dwarf 2 macro information
8605      refers to information in the line number info statement program
8606      header, so we can only read it if we've read the header
8607      successfully.  */
8608   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8609   if (attr && cu->line_header)
8610     {
8611       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8612         complaint (&symfile_complaints,
8613                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8614
8615       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8616     }
8617   else
8618     {
8619       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8620       if (attr && cu->line_header)
8621         {
8622           unsigned int macro_offset = DW_UNSND (attr);
8623
8624           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8625         }
8626     }
8627
8628   do_cleanups (back_to);
8629 }
8630
8631 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8632    Create the set of symtabs used by this TU, or if this TU is sharing
8633    symtabs with another TU and the symtabs have already been created
8634    then restore those symtabs in the line header.
8635    We don't need the pc/line-number mapping for type units.  */
8636
8637 static void
8638 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8639 {
8640   struct objfile *objfile = dwarf2_per_objfile->objfile;
8641   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8642   struct type_unit_group *tu_group;
8643   int first_time;
8644   struct line_header *lh;
8645   struct attribute *attr;
8646   unsigned int i, line_offset;
8647   struct signatured_type *sig_type;
8648
8649   gdb_assert (per_cu->is_debug_types);
8650   sig_type = (struct signatured_type *) per_cu;
8651
8652   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8653
8654   /* If we're using .gdb_index (includes -readnow) then
8655      per_cu->type_unit_group may not have been set up yet.  */
8656   if (sig_type->type_unit_group == NULL)
8657     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8658   tu_group = sig_type->type_unit_group;
8659
8660   /* If we've already processed this stmt_list there's no real need to
8661      do it again, we could fake it and just recreate the part we need
8662      (file name,index -> symtab mapping).  If data shows this optimization
8663      is useful we can do it then.  */
8664   first_time = tu_group->primary_symtab == NULL;
8665
8666   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8667      debug info.  */
8668   lh = NULL;
8669   if (attr != NULL)
8670     {
8671       line_offset = DW_UNSND (attr);
8672       lh = dwarf_decode_line_header (line_offset, cu);
8673     }
8674   if (lh == NULL)
8675     {
8676       if (first_time)
8677         dwarf2_start_symtab (cu, "", NULL, 0);
8678       else
8679         {
8680           gdb_assert (tu_group->symtabs == NULL);
8681           restart_symtab (0);
8682         }
8683       /* Note: The primary symtab will get allocated at the end.  */
8684       return;
8685     }
8686
8687   cu->line_header = lh;
8688   make_cleanup (free_cu_line_header, cu);
8689
8690   if (first_time)
8691     {
8692       dwarf2_start_symtab (cu, "", NULL, 0);
8693
8694       tu_group->num_symtabs = lh->num_file_names;
8695       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8696
8697       for (i = 0; i < lh->num_file_names; ++i)
8698         {
8699           const char *dir = NULL;
8700           struct file_entry *fe = &lh->file_names[i];
8701
8702           if (fe->dir_index)
8703             dir = lh->include_dirs[fe->dir_index - 1];
8704           dwarf2_start_subfile (fe->name, dir, NULL);
8705
8706           /* Note: We don't have to watch for the main subfile here, type units
8707              don't have DW_AT_name.  */
8708
8709           if (current_subfile->symtab == NULL)
8710             {
8711               /* NOTE: start_subfile will recognize when it's been passed
8712                  a file it has already seen.  So we can't assume there's a
8713                  simple mapping from lh->file_names to subfiles,
8714                  lh->file_names may contain dups.  */
8715               current_subfile->symtab = allocate_symtab (current_subfile->name,
8716                                                          objfile);
8717             }
8718
8719           fe->symtab = current_subfile->symtab;
8720           tu_group->symtabs[i] = fe->symtab;
8721         }
8722     }
8723   else
8724     {
8725       restart_symtab (0);
8726
8727       for (i = 0; i < lh->num_file_names; ++i)
8728         {
8729           struct file_entry *fe = &lh->file_names[i];
8730
8731           fe->symtab = tu_group->symtabs[i];
8732         }
8733     }
8734
8735   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8736      so they don't have a "real" (so to speak) symtab anyway.
8737      There is later code that will assign the main symtab to all symbols
8738      that don't have one.  We need to handle the case of a symbol with a
8739      missing symtab (DW_AT_decl_file) anyway.  */
8740 }
8741
8742 /* Process DW_TAG_type_unit.
8743    For TUs we want to skip the first top level sibling if it's not the
8744    actual type being defined by this TU.  In this case the first top
8745    level sibling is there to provide context only.  */
8746
8747 static void
8748 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8749 {
8750   struct die_info *child_die;
8751
8752   prepare_one_comp_unit (cu, die, language_minimal);
8753
8754   /* Initialize (or reinitialize) the machinery for building symtabs.
8755      We do this before processing child DIEs, so that the line header table
8756      is available for DW_AT_decl_file.  */
8757   setup_type_unit_groups (die, cu);
8758
8759   if (die->child != NULL)
8760     {
8761       child_die = die->child;
8762       while (child_die && child_die->tag)
8763         {
8764           process_die (child_die, cu);
8765           child_die = sibling_die (child_die);
8766         }
8767     }
8768 }
8769 \f
8770 /* DWO/DWP files.
8771
8772    http://gcc.gnu.org/wiki/DebugFission
8773    http://gcc.gnu.org/wiki/DebugFissionDWP
8774
8775    To simplify handling of both DWO files ("object" files with the DWARF info)
8776    and DWP files (a file with the DWOs packaged up into one file), we treat
8777    DWP files as having a collection of virtual DWO files.  */
8778
8779 static hashval_t
8780 hash_dwo_file (const void *item)
8781 {
8782   const struct dwo_file *dwo_file = item;
8783   hashval_t hash;
8784
8785   hash = htab_hash_string (dwo_file->dwo_name);
8786   if (dwo_file->comp_dir != NULL)
8787     hash += htab_hash_string (dwo_file->comp_dir);
8788   return hash;
8789 }
8790
8791 static int
8792 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8793 {
8794   const struct dwo_file *lhs = item_lhs;
8795   const struct dwo_file *rhs = item_rhs;
8796
8797   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8798     return 0;
8799   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8800     return lhs->comp_dir == rhs->comp_dir;
8801   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8802 }
8803
8804 /* Allocate a hash table for DWO files.  */
8805
8806 static htab_t
8807 allocate_dwo_file_hash_table (void)
8808 {
8809   struct objfile *objfile = dwarf2_per_objfile->objfile;
8810
8811   return htab_create_alloc_ex (41,
8812                                hash_dwo_file,
8813                                eq_dwo_file,
8814                                NULL,
8815                                &objfile->objfile_obstack,
8816                                hashtab_obstack_allocate,
8817                                dummy_obstack_deallocate);
8818 }
8819
8820 /* Lookup DWO file DWO_NAME.  */
8821
8822 static void **
8823 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8824 {
8825   struct dwo_file find_entry;
8826   void **slot;
8827
8828   if (dwarf2_per_objfile->dwo_files == NULL)
8829     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8830
8831   memset (&find_entry, 0, sizeof (find_entry));
8832   find_entry.dwo_name = dwo_name;
8833   find_entry.comp_dir = comp_dir;
8834   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8835
8836   return slot;
8837 }
8838
8839 static hashval_t
8840 hash_dwo_unit (const void *item)
8841 {
8842   const struct dwo_unit *dwo_unit = item;
8843
8844   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8845   return dwo_unit->signature;
8846 }
8847
8848 static int
8849 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8850 {
8851   const struct dwo_unit *lhs = item_lhs;
8852   const struct dwo_unit *rhs = item_rhs;
8853
8854   /* The signature is assumed to be unique within the DWO file.
8855      So while object file CU dwo_id's always have the value zero,
8856      that's OK, assuming each object file DWO file has only one CU,
8857      and that's the rule for now.  */
8858   return lhs->signature == rhs->signature;
8859 }
8860
8861 /* Allocate a hash table for DWO CUs,TUs.
8862    There is one of these tables for each of CUs,TUs for each DWO file.  */
8863
8864 static htab_t
8865 allocate_dwo_unit_table (struct objfile *objfile)
8866 {
8867   /* Start out with a pretty small number.
8868      Generally DWO files contain only one CU and maybe some TUs.  */
8869   return htab_create_alloc_ex (3,
8870                                hash_dwo_unit,
8871                                eq_dwo_unit,
8872                                NULL,
8873                                &objfile->objfile_obstack,
8874                                hashtab_obstack_allocate,
8875                                dummy_obstack_deallocate);
8876 }
8877
8878 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8879
8880 struct create_dwo_cu_data
8881 {
8882   struct dwo_file *dwo_file;
8883   struct dwo_unit dwo_unit;
8884 };
8885
8886 /* die_reader_func for create_dwo_cu.  */
8887
8888 static void
8889 create_dwo_cu_reader (const struct die_reader_specs *reader,
8890                       const gdb_byte *info_ptr,
8891                       struct die_info *comp_unit_die,
8892                       int has_children,
8893                       void *datap)
8894 {
8895   struct dwarf2_cu *cu = reader->cu;
8896   struct objfile *objfile = dwarf2_per_objfile->objfile;
8897   sect_offset offset = cu->per_cu->offset;
8898   struct dwarf2_section_info *section = cu->per_cu->section;
8899   struct create_dwo_cu_data *data = datap;
8900   struct dwo_file *dwo_file = data->dwo_file;
8901   struct dwo_unit *dwo_unit = &data->dwo_unit;
8902   struct attribute *attr;
8903
8904   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8905   if (attr == NULL)
8906     {
8907       complaint (&symfile_complaints,
8908                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8909                    " its dwo_id [in module %s]"),
8910                  offset.sect_off, dwo_file->dwo_name);
8911       return;
8912     }
8913
8914   dwo_unit->dwo_file = dwo_file;
8915   dwo_unit->signature = DW_UNSND (attr);
8916   dwo_unit->section = section;
8917   dwo_unit->offset = offset;
8918   dwo_unit->length = cu->per_cu->length;
8919
8920   if (dwarf2_read_debug)
8921     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8922                         offset.sect_off, hex_string (dwo_unit->signature));
8923 }
8924
8925 /* Create the dwo_unit for the lone CU in DWO_FILE.
8926    Note: This function processes DWO files only, not DWP files.  */
8927
8928 static struct dwo_unit *
8929 create_dwo_cu (struct dwo_file *dwo_file)
8930 {
8931   struct objfile *objfile = dwarf2_per_objfile->objfile;
8932   struct dwarf2_section_info *section = &dwo_file->sections.info;
8933   bfd *abfd;
8934   htab_t cu_htab;
8935   const gdb_byte *info_ptr, *end_ptr;
8936   struct create_dwo_cu_data create_dwo_cu_data;
8937   struct dwo_unit *dwo_unit;
8938
8939   dwarf2_read_section (objfile, section);
8940   info_ptr = section->buffer;
8941
8942   if (info_ptr == NULL)
8943     return NULL;
8944
8945   /* We can't set abfd until now because the section may be empty or
8946      not present, in which case section->asection will be NULL.  */
8947   abfd = get_section_bfd_owner (section);
8948
8949   if (dwarf2_read_debug)
8950     {
8951       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8952                           get_section_name (section),
8953                           get_section_file_name (section));
8954     }
8955
8956   create_dwo_cu_data.dwo_file = dwo_file;
8957   dwo_unit = NULL;
8958
8959   end_ptr = info_ptr + section->size;
8960   while (info_ptr < end_ptr)
8961     {
8962       struct dwarf2_per_cu_data per_cu;
8963
8964       memset (&create_dwo_cu_data.dwo_unit, 0,
8965               sizeof (create_dwo_cu_data.dwo_unit));
8966       memset (&per_cu, 0, sizeof (per_cu));
8967       per_cu.objfile = objfile;
8968       per_cu.is_debug_types = 0;
8969       per_cu.offset.sect_off = info_ptr - section->buffer;
8970       per_cu.section = section;
8971
8972       init_cutu_and_read_dies_no_follow (&per_cu,
8973                                          &dwo_file->sections.abbrev,
8974                                          dwo_file,
8975                                          create_dwo_cu_reader,
8976                                          &create_dwo_cu_data);
8977
8978       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8979         {
8980           /* If we've already found one, complain.  We only support one
8981              because having more than one requires hacking the dwo_name of
8982              each to match, which is highly unlikely to happen.  */
8983           if (dwo_unit != NULL)
8984             {
8985               complaint (&symfile_complaints,
8986                          _("Multiple CUs in DWO file %s [in module %s]"),
8987                          dwo_file->dwo_name, objfile_name (objfile));
8988               break;
8989             }
8990
8991           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8992           *dwo_unit = create_dwo_cu_data.dwo_unit;
8993         }
8994
8995       info_ptr += per_cu.length;
8996     }
8997
8998   return dwo_unit;
8999 }
9000
9001 /* DWP file .debug_{cu,tu}_index section format:
9002    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9003
9004    DWP Version 1:
9005
9006    Both index sections have the same format, and serve to map a 64-bit
9007    signature to a set of section numbers.  Each section begins with a header,
9008    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9009    indexes, and a pool of 32-bit section numbers.  The index sections will be
9010    aligned at 8-byte boundaries in the file.
9011
9012    The index section header consists of:
9013
9014     V, 32 bit version number
9015     -, 32 bits unused
9016     N, 32 bit number of compilation units or type units in the index
9017     M, 32 bit number of slots in the hash table
9018
9019    Numbers are recorded using the byte order of the application binary.
9020
9021    We assume that N and M will not exceed 2^32 - 1.
9022
9023    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9024
9025    The hash table begins at offset 16 in the section, and consists of an array
9026    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9027    order of the application binary).  Unused slots in the hash table are 0.
9028    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9029
9030    The parallel table begins immediately after the hash table
9031    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9032    array of 32-bit indexes (using the byte order of the application binary),
9033    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9034    table contains a 32-bit index into the pool of section numbers.  For unused
9035    hash table slots, the corresponding entry in the parallel table will be 0.
9036
9037    Given a 64-bit compilation unit signature or a type signature S, an entry
9038    in the hash table is located as follows:
9039
9040    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9041       the low-order k bits all set to 1.
9042
9043    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9044
9045    3) If the hash table entry at index H matches the signature, use that
9046       entry.  If the hash table entry at index H is unused (all zeroes),
9047       terminate the search: the signature is not present in the table.
9048
9049    4) Let H = (H + H') modulo M. Repeat at Step 3.
9050
9051    Because M > N and H' and M are relatively prime, the search is guaranteed
9052    to stop at an unused slot or find the match.
9053
9054    The pool of section numbers begins immediately following the hash table
9055    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9056    section numbers consists of an array of 32-bit words (using the byte order
9057    of the application binary).  Each item in the array is indexed starting
9058    from 0.  The hash table entry provides the index of the first section
9059    number in the set.  Additional section numbers in the set follow, and the
9060    set is terminated by a 0 entry (section number 0 is not used in ELF).
9061
9062    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9063    section must be the first entry in the set, and the .debug_abbrev.dwo must
9064    be the second entry. Other members of the set may follow in any order.  */
9065
9066 /* Create a hash table to map DWO IDs to their CU/TU entry in
9067    .debug_{info,types}.dwo in DWP_FILE.
9068    Returns NULL if there isn't one.
9069    Note: This function processes DWP files only, not DWO files.  */
9070
9071 static struct dwp_hash_table *
9072 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9073 {
9074   struct objfile *objfile = dwarf2_per_objfile->objfile;
9075   bfd *dbfd = dwp_file->dbfd;
9076   const gdb_byte *index_ptr, *index_end;
9077   struct dwarf2_section_info *index;
9078   uint32_t version, nr_units, nr_slots;
9079   struct dwp_hash_table *htab;
9080
9081   if (is_debug_types)
9082     index = &dwp_file->sections.tu_index;
9083   else
9084     index = &dwp_file->sections.cu_index;
9085
9086   if (dwarf2_section_empty_p (index))
9087     return NULL;
9088   dwarf2_read_section (objfile, index);
9089
9090   index_ptr = index->buffer;
9091   index_end = index_ptr + index->size;
9092
9093   version = read_4_bytes (dbfd, index_ptr);
9094   index_ptr += 8; /* Skip the unused word.  */
9095   nr_units = read_4_bytes (dbfd, index_ptr);
9096   index_ptr += 4;
9097   nr_slots = read_4_bytes (dbfd, index_ptr);
9098   index_ptr += 4;
9099
9100   if (version != 1)
9101     {
9102       error (_("Dwarf Error: unsupported DWP file version (%s)"
9103                " [in module %s]"),
9104              pulongest (version), dwp_file->name);
9105     }
9106   if (nr_slots != (nr_slots & -nr_slots))
9107     {
9108       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9109                " is not power of 2 [in module %s]"),
9110              pulongest (nr_slots), dwp_file->name);
9111     }
9112
9113   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9114   htab->nr_units = nr_units;
9115   htab->nr_slots = nr_slots;
9116   htab->hash_table = index_ptr;
9117   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9118   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9119
9120   return htab;
9121 }
9122
9123 /* Update SECTIONS with the data from SECTP.
9124
9125    This function is like the other "locate" section routines that are
9126    passed to bfd_map_over_sections, but in this context the sections to
9127    read comes from the DWP hash table, not the full ELF section table.
9128
9129    The result is non-zero for success, or zero if an error was found.  */
9130
9131 static int
9132 locate_virtual_dwo_sections (asection *sectp,
9133                              struct virtual_dwo_sections *sections)
9134 {
9135   const struct dwop_section_names *names = &dwop_section_names;
9136
9137   if (section_is_p (sectp->name, &names->abbrev_dwo))
9138     {
9139       /* There can be only one.  */
9140       if (sections->abbrev.asection != NULL)
9141         return 0;
9142       sections->abbrev.asection = sectp;
9143       sections->abbrev.size = bfd_get_section_size (sectp);
9144     }
9145   else if (section_is_p (sectp->name, &names->info_dwo)
9146            || section_is_p (sectp->name, &names->types_dwo))
9147     {
9148       /* There can be only one.  */
9149       if (sections->info_or_types.asection != NULL)
9150         return 0;
9151       sections->info_or_types.asection = sectp;
9152       sections->info_or_types.size = bfd_get_section_size (sectp);
9153     }
9154   else if (section_is_p (sectp->name, &names->line_dwo))
9155     {
9156       /* There can be only one.  */
9157       if (sections->line.asection != NULL)
9158         return 0;
9159       sections->line.asection = sectp;
9160       sections->line.size = bfd_get_section_size (sectp);
9161     }
9162   else if (section_is_p (sectp->name, &names->loc_dwo))
9163     {
9164       /* There can be only one.  */
9165       if (sections->loc.asection != NULL)
9166         return 0;
9167       sections->loc.asection = sectp;
9168       sections->loc.size = bfd_get_section_size (sectp);
9169     }
9170   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9171     {
9172       /* There can be only one.  */
9173       if (sections->macinfo.asection != NULL)
9174         return 0;
9175       sections->macinfo.asection = sectp;
9176       sections->macinfo.size = bfd_get_section_size (sectp);
9177     }
9178   else if (section_is_p (sectp->name, &names->macro_dwo))
9179     {
9180       /* There can be only one.  */
9181       if (sections->macro.asection != NULL)
9182         return 0;
9183       sections->macro.asection = sectp;
9184       sections->macro.size = bfd_get_section_size (sectp);
9185     }
9186   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9187     {
9188       /* There can be only one.  */
9189       if (sections->str_offsets.asection != NULL)
9190         return 0;
9191       sections->str_offsets.asection = sectp;
9192       sections->str_offsets.size = bfd_get_section_size (sectp);
9193     }
9194   else
9195     {
9196       /* No other kind of section is valid.  */
9197       return 0;
9198     }
9199
9200   return 1;
9201 }
9202
9203 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9204    HTAB is the hash table from the DWP file.
9205    SECTION_INDEX is the index of the DWO in HTAB.
9206    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9207
9208 static struct dwo_unit *
9209 create_dwo_in_dwp (struct dwp_file *dwp_file,
9210                    const struct dwp_hash_table *htab,
9211                    uint32_t section_index,
9212                    const char *comp_dir,
9213                    ULONGEST signature, int is_debug_types)
9214 {
9215   struct objfile *objfile = dwarf2_per_objfile->objfile;
9216   bfd *dbfd = dwp_file->dbfd;
9217   const char *kind = is_debug_types ? "TU" : "CU";
9218   struct dwo_file *dwo_file;
9219   struct dwo_unit *dwo_unit;
9220   struct virtual_dwo_sections sections;
9221   void **dwo_file_slot;
9222   char *virtual_dwo_name;
9223   struct dwarf2_section_info *cutu;
9224   struct cleanup *cleanups;
9225   int i;
9226
9227   if (dwarf2_read_debug)
9228     {
9229       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9230                           kind,
9231                           pulongest (section_index), hex_string (signature),
9232                           dwp_file->name);
9233     }
9234
9235   /* Fetch the sections of this DWO unit.
9236      Put a limit on the number of sections we look for so that bad data
9237      doesn't cause us to loop forever.  */
9238
9239 #define MAX_NR_DWO_SECTIONS \
9240   (1 /* .debug_info or .debug_types */ \
9241    + 1 /* .debug_abbrev */ \
9242    + 1 /* .debug_line */ \
9243    + 1 /* .debug_loc */ \
9244    + 1 /* .debug_str_offsets */ \
9245    + 1 /* .debug_macro or .debug_macinfo */ \
9246    + 1 /* trailing zero */)
9247
9248   memset (&sections, 0, sizeof (sections));
9249   cleanups = make_cleanup (null_cleanup, 0);
9250
9251   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9252     {
9253       asection *sectp;
9254       uint32_t section_nr =
9255         read_4_bytes (dbfd,
9256                       htab->section_pool
9257                       + (section_index + i) * sizeof (uint32_t));
9258
9259       if (section_nr == 0)
9260         break;
9261       if (section_nr >= dwp_file->num_sections)
9262         {
9263           error (_("Dwarf Error: bad DWP hash table, section number too large"
9264                    " [in module %s]"),
9265                  dwp_file->name);
9266         }
9267
9268       sectp = dwp_file->elf_sections[section_nr];
9269       if (! locate_virtual_dwo_sections (sectp, &sections))
9270         {
9271           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9272                    " [in module %s]"),
9273                  dwp_file->name);
9274         }
9275     }
9276
9277   if (i < 2
9278       || dwarf2_section_empty_p (&sections.info_or_types)
9279       || dwarf2_section_empty_p (&sections.abbrev))
9280     {
9281       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9282                " [in module %s]"),
9283              dwp_file->name);
9284     }
9285   if (i == MAX_NR_DWO_SECTIONS)
9286     {
9287       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9288                " [in module %s]"),
9289              dwp_file->name);
9290     }
9291
9292   /* It's easier for the rest of the code if we fake a struct dwo_file and
9293      have dwo_unit "live" in that.  At least for now.
9294
9295      The DWP file can be made up of a random collection of CUs and TUs.
9296      However, for each CU + set of TUs that came from the same original DWO
9297      file, we can combine them back into a virtual DWO file to save space
9298      (fewer struct dwo_file objects to allocate).  Remember that for really
9299      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9300
9301   virtual_dwo_name =
9302     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9303                 get_section_id (&sections.abbrev),
9304                 get_section_id (&sections.line),
9305                 get_section_id (&sections.loc),
9306                 get_section_id (&sections.str_offsets));
9307   make_cleanup (xfree, virtual_dwo_name);
9308   /* Can we use an existing virtual DWO file?  */
9309   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9310   /* Create one if necessary.  */
9311   if (*dwo_file_slot == NULL)
9312     {
9313       if (dwarf2_read_debug)
9314         {
9315           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9316                               virtual_dwo_name);
9317         }
9318       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9319       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9320                                           virtual_dwo_name,
9321                                           strlen (virtual_dwo_name));
9322       dwo_file->comp_dir = comp_dir;
9323       dwo_file->sections.abbrev = sections.abbrev;
9324       dwo_file->sections.line = sections.line;
9325       dwo_file->sections.loc = sections.loc;
9326       dwo_file->sections.macinfo = sections.macinfo;
9327       dwo_file->sections.macro = sections.macro;
9328       dwo_file->sections.str_offsets = sections.str_offsets;
9329       /* The "str" section is global to the entire DWP file.  */
9330       dwo_file->sections.str = dwp_file->sections.str;
9331       /* The info or types section is assigned below to dwo_unit,
9332          there's no need to record it in dwo_file.
9333          Also, we can't simply record type sections in dwo_file because
9334          we record a pointer into the vector in dwo_unit.  As we collect more
9335          types we'll grow the vector and eventually have to reallocate space
9336          for it, invalidating all copies of pointers into the previous
9337          contents.  */
9338       *dwo_file_slot = dwo_file;
9339     }
9340   else
9341     {
9342       if (dwarf2_read_debug)
9343         {
9344           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9345                               virtual_dwo_name);
9346         }
9347       dwo_file = *dwo_file_slot;
9348     }
9349   do_cleanups (cleanups);
9350
9351   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9352   dwo_unit->dwo_file = dwo_file;
9353   dwo_unit->signature = signature;
9354   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9355                                      sizeof (struct dwarf2_section_info));
9356   *dwo_unit->section = sections.info_or_types;
9357   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9358
9359   return dwo_unit;
9360 }
9361
9362 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
9363    Returns NULL if the signature isn't found.  */
9364
9365 static struct dwo_unit *
9366 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
9367                         ULONGEST signature, int is_debug_types)
9368 {
9369   const struct dwp_hash_table *dwp_htab =
9370     is_debug_types ? dwp_file->tus : dwp_file->cus;
9371   bfd *dbfd = dwp_file->dbfd;
9372   uint32_t mask = dwp_htab->nr_slots - 1;
9373   uint32_t hash = signature & mask;
9374   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9375   unsigned int i;
9376   void **slot;
9377   struct dwo_unit find_dwo_cu, *dwo_cu;
9378
9379   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9380   find_dwo_cu.signature = signature;
9381   slot = htab_find_slot (is_debug_types
9382                          ? dwp_file->loaded_tus
9383                          : dwp_file->loaded_cus,
9384                          &find_dwo_cu, INSERT);
9385
9386   if (*slot != NULL)
9387     return *slot;
9388
9389   /* Use a for loop so that we don't loop forever on bad debug info.  */
9390   for (i = 0; i < dwp_htab->nr_slots; ++i)
9391     {
9392       ULONGEST signature_in_table;
9393
9394       signature_in_table =
9395         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
9396       if (signature_in_table == signature)
9397         {
9398           uint32_t unit_index =
9399             read_4_bytes (dbfd,
9400                           dwp_htab->unit_table + hash * sizeof (uint32_t));
9401
9402           *slot = create_dwo_in_dwp (dwp_file, dwp_htab, unit_index,
9403                                      comp_dir, signature, is_debug_types);
9404           return *slot;
9405         }
9406       if (signature_in_table == 0)
9407         return NULL;
9408       hash = (hash + hash2) & mask;
9409     }
9410
9411   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9412            " [in module %s]"),
9413          dwp_file->name);
9414 }
9415
9416 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9417    Open the file specified by FILE_NAME and hand it off to BFD for
9418    preliminary analysis.  Return a newly initialized bfd *, which
9419    includes a canonicalized copy of FILE_NAME.
9420    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9421    SEARCH_CWD is true if the current directory is to be searched.
9422    It will be searched before debug-file-directory.
9423    If unable to find/open the file, return NULL.
9424    NOTE: This function is derived from symfile_bfd_open.  */
9425
9426 static bfd *
9427 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9428 {
9429   bfd *sym_bfd;
9430   int desc, flags;
9431   char *absolute_name;
9432   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9433      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9434      to debug_file_directory.  */
9435   char *search_path;
9436   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9437
9438   if (search_cwd)
9439     {
9440       if (*debug_file_directory != '\0')
9441         search_path = concat (".", dirname_separator_string,
9442                               debug_file_directory, NULL);
9443       else
9444         search_path = xstrdup (".");
9445     }
9446   else
9447     search_path = xstrdup (debug_file_directory);
9448
9449   flags = OPF_RETURN_REALPATH;
9450   if (is_dwp)
9451     flags |= OPF_SEARCH_IN_PATH;
9452   desc = openp (search_path, flags, file_name,
9453                 O_RDONLY | O_BINARY, &absolute_name);
9454   xfree (search_path);
9455   if (desc < 0)
9456     return NULL;
9457
9458   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9459   xfree (absolute_name);
9460   if (sym_bfd == NULL)
9461     return NULL;
9462   bfd_set_cacheable (sym_bfd, 1);
9463
9464   if (!bfd_check_format (sym_bfd, bfd_object))
9465     {
9466       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9467       return NULL;
9468     }
9469
9470   return sym_bfd;
9471 }
9472
9473 /* Try to open DWO file FILE_NAME.
9474    COMP_DIR is the DW_AT_comp_dir attribute.
9475    The result is the bfd handle of the file.
9476    If there is a problem finding or opening the file, return NULL.
9477    Upon success, the canonicalized path of the file is stored in the bfd,
9478    same as symfile_bfd_open.  */
9479
9480 static bfd *
9481 open_dwo_file (const char *file_name, const char *comp_dir)
9482 {
9483   bfd *abfd;
9484
9485   if (IS_ABSOLUTE_PATH (file_name))
9486     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9487
9488   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9489
9490   if (comp_dir != NULL)
9491     {
9492       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9493
9494       /* NOTE: If comp_dir is a relative path, this will also try the
9495          search path, which seems useful.  */
9496       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9497       xfree (path_to_try);
9498       if (abfd != NULL)
9499         return abfd;
9500     }
9501
9502   /* That didn't work, try debug-file-directory, which, despite its name,
9503      is a list of paths.  */
9504
9505   if (*debug_file_directory == '\0')
9506     return NULL;
9507
9508   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9509 }
9510
9511 /* This function is mapped across the sections and remembers the offset and
9512    size of each of the DWO debugging sections we are interested in.  */
9513
9514 static void
9515 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9516 {
9517   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9518   const struct dwop_section_names *names = &dwop_section_names;
9519
9520   if (section_is_p (sectp->name, &names->abbrev_dwo))
9521     {
9522       dwo_sections->abbrev.asection = sectp;
9523       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9524     }
9525   else if (section_is_p (sectp->name, &names->info_dwo))
9526     {
9527       dwo_sections->info.asection = sectp;
9528       dwo_sections->info.size = bfd_get_section_size (sectp);
9529     }
9530   else if (section_is_p (sectp->name, &names->line_dwo))
9531     {
9532       dwo_sections->line.asection = sectp;
9533       dwo_sections->line.size = bfd_get_section_size (sectp);
9534     }
9535   else if (section_is_p (sectp->name, &names->loc_dwo))
9536     {
9537       dwo_sections->loc.asection = sectp;
9538       dwo_sections->loc.size = bfd_get_section_size (sectp);
9539     }
9540   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9541     {
9542       dwo_sections->macinfo.asection = sectp;
9543       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9544     }
9545   else if (section_is_p (sectp->name, &names->macro_dwo))
9546     {
9547       dwo_sections->macro.asection = sectp;
9548       dwo_sections->macro.size = bfd_get_section_size (sectp);
9549     }
9550   else if (section_is_p (sectp->name, &names->str_dwo))
9551     {
9552       dwo_sections->str.asection = sectp;
9553       dwo_sections->str.size = bfd_get_section_size (sectp);
9554     }
9555   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9556     {
9557       dwo_sections->str_offsets.asection = sectp;
9558       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9559     }
9560   else if (section_is_p (sectp->name, &names->types_dwo))
9561     {
9562       struct dwarf2_section_info type_section;
9563
9564       memset (&type_section, 0, sizeof (type_section));
9565       type_section.asection = sectp;
9566       type_section.size = bfd_get_section_size (sectp);
9567       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9568                      &type_section);
9569     }
9570 }
9571
9572 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9573    by PER_CU.  This is for the non-DWP case.
9574    The result is NULL if DWO_NAME can't be found.  */
9575
9576 static struct dwo_file *
9577 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9578                         const char *dwo_name, const char *comp_dir)
9579 {
9580   struct objfile *objfile = dwarf2_per_objfile->objfile;
9581   struct dwo_file *dwo_file;
9582   bfd *dbfd;
9583   struct cleanup *cleanups;
9584
9585   dbfd = open_dwo_file (dwo_name, comp_dir);
9586   if (dbfd == NULL)
9587     {
9588       if (dwarf2_read_debug)
9589         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9590       return NULL;
9591     }
9592   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9593   dwo_file->dwo_name = dwo_name;
9594   dwo_file->comp_dir = comp_dir;
9595   dwo_file->dbfd = dbfd;
9596
9597   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9598
9599   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9600
9601   dwo_file->cu = create_dwo_cu (dwo_file);
9602
9603   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9604                                                  dwo_file->sections.types);
9605
9606   discard_cleanups (cleanups);
9607
9608   if (dwarf2_read_debug)
9609     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9610
9611   return dwo_file;
9612 }
9613
9614 /* This function is mapped across the sections and remembers the offset and
9615    size of each of the DWP debugging sections we are interested in.  */
9616
9617 static void
9618 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9619 {
9620   struct dwp_file *dwp_file = dwp_file_ptr;
9621   const struct dwop_section_names *names = &dwop_section_names;
9622   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9623
9624   /* Record the ELF section number for later lookup: this is what the
9625      .debug_cu_index,.debug_tu_index tables use.  */
9626   gdb_assert (elf_section_nr < dwp_file->num_sections);
9627   dwp_file->elf_sections[elf_section_nr] = sectp;
9628
9629   /* Look for specific sections that we need.  */
9630   if (section_is_p (sectp->name, &names->str_dwo))
9631     {
9632       dwp_file->sections.str.asection = sectp;
9633       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9634     }
9635   else if (section_is_p (sectp->name, &names->cu_index))
9636     {
9637       dwp_file->sections.cu_index.asection = sectp;
9638       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9639     }
9640   else if (section_is_p (sectp->name, &names->tu_index))
9641     {
9642       dwp_file->sections.tu_index.asection = sectp;
9643       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9644     }
9645 }
9646
9647 /* Hash function for dwp_file loaded CUs/TUs.  */
9648
9649 static hashval_t
9650 hash_dwp_loaded_cutus (const void *item)
9651 {
9652   const struct dwo_unit *dwo_unit = item;
9653
9654   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9655   return dwo_unit->signature;
9656 }
9657
9658 /* Equality function for dwp_file loaded CUs/TUs.  */
9659
9660 static int
9661 eq_dwp_loaded_cutus (const void *a, const void *b)
9662 {
9663   const struct dwo_unit *dua = a;
9664   const struct dwo_unit *dub = b;
9665
9666   return dua->signature == dub->signature;
9667 }
9668
9669 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9670
9671 static htab_t
9672 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9673 {
9674   return htab_create_alloc_ex (3,
9675                                hash_dwp_loaded_cutus,
9676                                eq_dwp_loaded_cutus,
9677                                NULL,
9678                                &objfile->objfile_obstack,
9679                                hashtab_obstack_allocate,
9680                                dummy_obstack_deallocate);
9681 }
9682
9683 /* Try to open DWP file FILE_NAME.
9684    The result is the bfd handle of the file.
9685    If there is a problem finding or opening the file, return NULL.
9686    Upon success, the canonicalized path of the file is stored in the bfd,
9687    same as symfile_bfd_open.  */
9688
9689 static bfd *
9690 open_dwp_file (const char *file_name)
9691 {
9692   bfd *abfd;
9693
9694   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9695   if (abfd != NULL)
9696     return abfd;
9697
9698   /* Work around upstream bug 15652.
9699      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9700      [Whether that's a "bug" is debatable, but it is getting in our way.]
9701      We have no real idea where the dwp file is, because gdb's realpath-ing
9702      of the executable's path may have discarded the needed info.
9703      [IWBN if the dwp file name was recorded in the executable, akin to
9704      .gnu_debuglink, but that doesn't exist yet.]
9705      Strip the directory from FILE_NAME and search again.  */
9706   if (*debug_file_directory != '\0')
9707     {
9708       /* Don't implicitly search the current directory here.
9709          If the user wants to search "." to handle this case,
9710          it must be added to debug-file-directory.  */
9711       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9712                                  0 /*search_cwd*/);
9713     }
9714
9715   return NULL;
9716 }
9717
9718 /* Initialize the use of the DWP file for the current objfile.
9719    By convention the name of the DWP file is ${objfile}.dwp.
9720    The result is NULL if it can't be found.  */
9721
9722 static struct dwp_file *
9723 open_and_init_dwp_file (void)
9724 {
9725   struct objfile *objfile = dwarf2_per_objfile->objfile;
9726   struct dwp_file *dwp_file;
9727   char *dwp_name;
9728   bfd *dbfd;
9729   struct cleanup *cleanups;
9730
9731   /* Try to find first .dwp for the binary file before any symbolic links
9732      resolving.  */
9733   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
9734   cleanups = make_cleanup (xfree, dwp_name);
9735
9736   dbfd = open_dwp_file (dwp_name);
9737   if (dbfd == NULL
9738       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
9739     {
9740       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
9741       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
9742       make_cleanup (xfree, dwp_name);
9743       dbfd = open_dwp_file (dwp_name);
9744     }
9745
9746   if (dbfd == NULL)
9747     {
9748       if (dwarf2_read_debug)
9749         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9750       do_cleanups (cleanups);
9751       return NULL;
9752     }
9753   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9754   dwp_file->name = bfd_get_filename (dbfd);
9755   dwp_file->dbfd = dbfd;
9756   do_cleanups (cleanups);
9757
9758   /* +1: section 0 is unused */
9759   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9760   dwp_file->elf_sections =
9761     OBSTACK_CALLOC (&objfile->objfile_obstack,
9762                     dwp_file->num_sections, asection *);
9763
9764   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9765
9766   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9767
9768   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9769
9770   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
9771   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
9772
9773   if (dwarf2_read_debug)
9774     {
9775       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9776       fprintf_unfiltered (gdb_stdlog,
9777                           "    %s CUs, %s TUs\n",
9778                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9779                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9780     }
9781
9782   return dwp_file;
9783 }
9784
9785 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9786
9787 static struct dwp_file *
9788 get_dwp_file (void)
9789 {
9790   if (! dwarf2_per_objfile->dwp_checked)
9791     {
9792       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9793       dwarf2_per_objfile->dwp_checked = 1;
9794     }
9795   return dwarf2_per_objfile->dwp_file;
9796 }
9797
9798 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9799    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9800    or in the DWP file for the objfile, referenced by THIS_UNIT.
9801    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9802    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9803
9804    This is called, for example, when wanting to read a variable with a
9805    complex location.  Therefore we don't want to do file i/o for every call.
9806    Therefore we don't want to look for a DWO file on every call.
9807    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9808    then we check if we've already seen DWO_NAME, and only THEN do we check
9809    for a DWO file.
9810
9811    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9812    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9813
9814 static struct dwo_unit *
9815 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9816                  const char *dwo_name, const char *comp_dir,
9817                  ULONGEST signature, int is_debug_types)
9818 {
9819   struct objfile *objfile = dwarf2_per_objfile->objfile;
9820   const char *kind = is_debug_types ? "TU" : "CU";
9821   void **dwo_file_slot;
9822   struct dwo_file *dwo_file;
9823   struct dwp_file *dwp_file;
9824
9825   /* First see if there's a DWP file.
9826      If we have a DWP file but didn't find the DWO inside it, don't
9827      look for the original DWO file.  It makes gdb behave differently
9828      depending on whether one is debugging in the build tree.  */
9829
9830   dwp_file = get_dwp_file ();
9831   if (dwp_file != NULL)
9832     {
9833       const struct dwp_hash_table *dwp_htab =
9834         is_debug_types ? dwp_file->tus : dwp_file->cus;
9835
9836       if (dwp_htab != NULL)
9837         {
9838           struct dwo_unit *dwo_cutu =
9839             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
9840                                     signature, is_debug_types);
9841
9842           if (dwo_cutu != NULL)
9843             {
9844               if (dwarf2_read_debug)
9845                 {
9846                   fprintf_unfiltered (gdb_stdlog,
9847                                       "Virtual DWO %s %s found: @%s\n",
9848                                       kind, hex_string (signature),
9849                                       host_address_to_string (dwo_cutu));
9850                 }
9851               return dwo_cutu;
9852             }
9853         }
9854     }
9855   else
9856     {
9857       /* No DWP file, look for the DWO file.  */
9858
9859       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9860       if (*dwo_file_slot == NULL)
9861         {
9862           /* Read in the file and build a table of the CUs/TUs it contains.  */
9863           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9864         }
9865       /* NOTE: This will be NULL if unable to open the file.  */
9866       dwo_file = *dwo_file_slot;
9867
9868       if (dwo_file != NULL)
9869         {
9870           struct dwo_unit *dwo_cutu = NULL;
9871
9872           if (is_debug_types && dwo_file->tus)
9873             {
9874               struct dwo_unit find_dwo_cutu;
9875
9876               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9877               find_dwo_cutu.signature = signature;
9878               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9879             }
9880           else if (!is_debug_types && dwo_file->cu)
9881             {
9882               if (signature == dwo_file->cu->signature)
9883                 dwo_cutu = dwo_file->cu;
9884             }
9885
9886           if (dwo_cutu != NULL)
9887             {
9888               if (dwarf2_read_debug)
9889                 {
9890                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9891                                       kind, dwo_name, hex_string (signature),
9892                                       host_address_to_string (dwo_cutu));
9893                 }
9894               return dwo_cutu;
9895             }
9896         }
9897     }
9898
9899   /* We didn't find it.  This could mean a dwo_id mismatch, or
9900      someone deleted the DWO/DWP file, or the search path isn't set up
9901      correctly to find the file.  */
9902
9903   if (dwarf2_read_debug)
9904     {
9905       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9906                           kind, dwo_name, hex_string (signature));
9907     }
9908
9909   /* This is a warning and not a complaint because it can be caused by
9910      pilot error (e.g., user accidentally deleting the DWO).  */
9911   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9912              " [in module %s]"),
9913            kind, dwo_name, hex_string (signature),
9914            this_unit->is_debug_types ? "TU" : "CU",
9915            this_unit->offset.sect_off, objfile_name (objfile));
9916   return NULL;
9917 }
9918
9919 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9920    See lookup_dwo_cutu_unit for details.  */
9921
9922 static struct dwo_unit *
9923 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9924                       const char *dwo_name, const char *comp_dir,
9925                       ULONGEST signature)
9926 {
9927   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9928 }
9929
9930 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9931    See lookup_dwo_cutu_unit for details.  */
9932
9933 static struct dwo_unit *
9934 lookup_dwo_type_unit (struct signatured_type *this_tu,
9935                       const char *dwo_name, const char *comp_dir)
9936 {
9937   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9938 }
9939
9940 /* Traversal function for queue_and_load_all_dwo_tus.  */
9941
9942 static int
9943 queue_and_load_dwo_tu (void **slot, void *info)
9944 {
9945   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
9946   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
9947   ULONGEST signature = dwo_unit->signature;
9948   struct signatured_type *sig_type =
9949     lookup_dwo_signatured_type (per_cu->cu, signature);
9950
9951   if (sig_type != NULL)
9952     {
9953       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
9954
9955       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
9956          a real dependency of PER_CU on SIG_TYPE.  That is detected later
9957          while processing PER_CU.  */
9958       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
9959         load_full_type_unit (sig_cu);
9960       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
9961     }
9962
9963   return 1;
9964 }
9965
9966 /* Queue all TUs contained in the DWO of PER_CU to be read in.
9967    The DWO may have the only definition of the type, though it may not be
9968    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
9969    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
9970
9971 static void
9972 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
9973 {
9974   struct dwo_unit *dwo_unit;
9975   struct dwo_file *dwo_file;
9976
9977   gdb_assert (!per_cu->is_debug_types);
9978   gdb_assert (get_dwp_file () == NULL);
9979   gdb_assert (per_cu->cu != NULL);
9980
9981   dwo_unit = per_cu->cu->dwo_unit;
9982   gdb_assert (dwo_unit != NULL);
9983
9984   dwo_file = dwo_unit->dwo_file;
9985   if (dwo_file->tus != NULL)
9986     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
9987 }
9988
9989 /* Free all resources associated with DWO_FILE.
9990    Close the DWO file and munmap the sections.
9991    All memory should be on the objfile obstack.  */
9992
9993 static void
9994 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9995 {
9996   int ix;
9997   struct dwarf2_section_info *section;
9998
9999   /* Note: dbfd is NULL for virtual DWO files.  */
10000   gdb_bfd_unref (dwo_file->dbfd);
10001
10002   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
10003 }
10004
10005 /* Wrapper for free_dwo_file for use in cleanups.  */
10006
10007 static void
10008 free_dwo_file_cleanup (void *arg)
10009 {
10010   struct dwo_file *dwo_file = (struct dwo_file *) arg;
10011   struct objfile *objfile = dwarf2_per_objfile->objfile;
10012
10013   free_dwo_file (dwo_file, objfile);
10014 }
10015
10016 /* Traversal function for free_dwo_files.  */
10017
10018 static int
10019 free_dwo_file_from_slot (void **slot, void *info)
10020 {
10021   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
10022   struct objfile *objfile = (struct objfile *) info;
10023
10024   free_dwo_file (dwo_file, objfile);
10025
10026   return 1;
10027 }
10028
10029 /* Free all resources associated with DWO_FILES.  */
10030
10031 static void
10032 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
10033 {
10034   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
10035 }
10036 \f
10037 /* Read in various DIEs.  */
10038
10039 /* qsort helper for inherit_abstract_dies.  */
10040
10041 static int
10042 unsigned_int_compar (const void *ap, const void *bp)
10043 {
10044   unsigned int a = *(unsigned int *) ap;
10045   unsigned int b = *(unsigned int *) bp;
10046
10047   return (a > b) - (b > a);
10048 }
10049
10050 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
10051    Inherit only the children of the DW_AT_abstract_origin DIE not being
10052    already referenced by DW_AT_abstract_origin from the children of the
10053    current DIE.  */
10054
10055 static void
10056 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
10057 {
10058   struct die_info *child_die;
10059   unsigned die_children_count;
10060   /* CU offsets which were referenced by children of the current DIE.  */
10061   sect_offset *offsets;
10062   sect_offset *offsets_end, *offsetp;
10063   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
10064   struct die_info *origin_die;
10065   /* Iterator of the ORIGIN_DIE children.  */
10066   struct die_info *origin_child_die;
10067   struct cleanup *cleanups;
10068   struct attribute *attr;
10069   struct dwarf2_cu *origin_cu;
10070   struct pending **origin_previous_list_in_scope;
10071
10072   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10073   if (!attr)
10074     return;
10075
10076   /* Note that following die references may follow to a die in a
10077      different cu.  */
10078
10079   origin_cu = cu;
10080   origin_die = follow_die_ref (die, attr, &origin_cu);
10081
10082   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
10083      symbols in.  */
10084   origin_previous_list_in_scope = origin_cu->list_in_scope;
10085   origin_cu->list_in_scope = cu->list_in_scope;
10086
10087   if (die->tag != origin_die->tag
10088       && !(die->tag == DW_TAG_inlined_subroutine
10089            && origin_die->tag == DW_TAG_subprogram))
10090     complaint (&symfile_complaints,
10091                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
10092                die->offset.sect_off, origin_die->offset.sect_off);
10093
10094   child_die = die->child;
10095   die_children_count = 0;
10096   while (child_die && child_die->tag)
10097     {
10098       child_die = sibling_die (child_die);
10099       die_children_count++;
10100     }
10101   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10102   cleanups = make_cleanup (xfree, offsets);
10103
10104   offsets_end = offsets;
10105   child_die = die->child;
10106   while (child_die && child_die->tag)
10107     {
10108       /* For each CHILD_DIE, find the corresponding child of
10109          ORIGIN_DIE.  If there is more than one layer of
10110          DW_AT_abstract_origin, follow them all; there shouldn't be,
10111          but GCC versions at least through 4.4 generate this (GCC PR
10112          40573).  */
10113       struct die_info *child_origin_die = child_die;
10114       struct dwarf2_cu *child_origin_cu = cu;
10115
10116       while (1)
10117         {
10118           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10119                               child_origin_cu);
10120           if (attr == NULL)
10121             break;
10122           child_origin_die = follow_die_ref (child_origin_die, attr,
10123                                              &child_origin_cu);
10124         }
10125
10126       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10127          counterpart may exist.  */
10128       if (child_origin_die != child_die)
10129         {
10130           if (child_die->tag != child_origin_die->tag
10131               && !(child_die->tag == DW_TAG_inlined_subroutine
10132                    && child_origin_die->tag == DW_TAG_subprogram))
10133             complaint (&symfile_complaints,
10134                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10135                          "different tags"), child_die->offset.sect_off,
10136                        child_origin_die->offset.sect_off);
10137           if (child_origin_die->parent != origin_die)
10138             complaint (&symfile_complaints,
10139                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10140                          "different parents"), child_die->offset.sect_off,
10141                        child_origin_die->offset.sect_off);
10142           else
10143             *offsets_end++ = child_origin_die->offset;
10144         }
10145       child_die = sibling_die (child_die);
10146     }
10147   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10148          unsigned_int_compar);
10149   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10150     if (offsetp[-1].sect_off == offsetp->sect_off)
10151       complaint (&symfile_complaints,
10152                  _("Multiple children of DIE 0x%x refer "
10153                    "to DIE 0x%x as their abstract origin"),
10154                  die->offset.sect_off, offsetp->sect_off);
10155
10156   offsetp = offsets;
10157   origin_child_die = origin_die->child;
10158   while (origin_child_die && origin_child_die->tag)
10159     {
10160       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10161       while (offsetp < offsets_end
10162              && offsetp->sect_off < origin_child_die->offset.sect_off)
10163         offsetp++;
10164       if (offsetp >= offsets_end
10165           || offsetp->sect_off > origin_child_die->offset.sect_off)
10166         {
10167           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10168           process_die (origin_child_die, origin_cu);
10169         }
10170       origin_child_die = sibling_die (origin_child_die);
10171     }
10172   origin_cu->list_in_scope = origin_previous_list_in_scope;
10173
10174   do_cleanups (cleanups);
10175 }
10176
10177 static void
10178 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10179 {
10180   struct objfile *objfile = cu->objfile;
10181   struct context_stack *new;
10182   CORE_ADDR lowpc;
10183   CORE_ADDR highpc;
10184   struct die_info *child_die;
10185   struct attribute *attr, *call_line, *call_file;
10186   const char *name;
10187   CORE_ADDR baseaddr;
10188   struct block *block;
10189   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10190   VEC (symbolp) *template_args = NULL;
10191   struct template_symbol *templ_func = NULL;
10192
10193   if (inlined_func)
10194     {
10195       /* If we do not have call site information, we can't show the
10196          caller of this inlined function.  That's too confusing, so
10197          only use the scope for local variables.  */
10198       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10199       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10200       if (call_line == NULL || call_file == NULL)
10201         {
10202           read_lexical_block_scope (die, cu);
10203           return;
10204         }
10205     }
10206
10207   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10208
10209   name = dwarf2_name (die, cu);
10210
10211   /* Ignore functions with missing or empty names.  These are actually
10212      illegal according to the DWARF standard.  */
10213   if (name == NULL)
10214     {
10215       complaint (&symfile_complaints,
10216                  _("missing name for subprogram DIE at %d"),
10217                  die->offset.sect_off);
10218       return;
10219     }
10220
10221   /* Ignore functions with missing or invalid low and high pc attributes.  */
10222   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10223     {
10224       attr = dwarf2_attr (die, DW_AT_external, cu);
10225       if (!attr || !DW_UNSND (attr))
10226         complaint (&symfile_complaints,
10227                    _("cannot get low and high bounds "
10228                      "for subprogram DIE at %d"),
10229                    die->offset.sect_off);
10230       return;
10231     }
10232
10233   lowpc += baseaddr;
10234   highpc += baseaddr;
10235
10236   /* If we have any template arguments, then we must allocate a
10237      different sort of symbol.  */
10238   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10239     {
10240       if (child_die->tag == DW_TAG_template_type_param
10241           || child_die->tag == DW_TAG_template_value_param)
10242         {
10243           templ_func = allocate_template_symbol (objfile);
10244           templ_func->base.is_cplus_template_function = 1;
10245           break;
10246         }
10247     }
10248
10249   new = push_context (0, lowpc);
10250   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10251                                (struct symbol *) templ_func);
10252
10253   /* If there is a location expression for DW_AT_frame_base, record
10254      it.  */
10255   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10256   if (attr)
10257     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10258
10259   cu->list_in_scope = &local_symbols;
10260
10261   if (die->child != NULL)
10262     {
10263       child_die = die->child;
10264       while (child_die && child_die->tag)
10265         {
10266           if (child_die->tag == DW_TAG_template_type_param
10267               || child_die->tag == DW_TAG_template_value_param)
10268             {
10269               struct symbol *arg = new_symbol (child_die, NULL, cu);
10270
10271               if (arg != NULL)
10272                 VEC_safe_push (symbolp, template_args, arg);
10273             }
10274           else
10275             process_die (child_die, cu);
10276           child_die = sibling_die (child_die);
10277         }
10278     }
10279
10280   inherit_abstract_dies (die, cu);
10281
10282   /* If we have a DW_AT_specification, we might need to import using
10283      directives from the context of the specification DIE.  See the
10284      comment in determine_prefix.  */
10285   if (cu->language == language_cplus
10286       && dwarf2_attr (die, DW_AT_specification, cu))
10287     {
10288       struct dwarf2_cu *spec_cu = cu;
10289       struct die_info *spec_die = die_specification (die, &spec_cu);
10290
10291       while (spec_die)
10292         {
10293           child_die = spec_die->child;
10294           while (child_die && child_die->tag)
10295             {
10296               if (child_die->tag == DW_TAG_imported_module)
10297                 process_die (child_die, spec_cu);
10298               child_die = sibling_die (child_die);
10299             }
10300
10301           /* In some cases, GCC generates specification DIEs that
10302              themselves contain DW_AT_specification attributes.  */
10303           spec_die = die_specification (spec_die, &spec_cu);
10304         }
10305     }
10306
10307   new = pop_context ();
10308   /* Make a block for the local symbols within.  */
10309   block = finish_block (new->name, &local_symbols, new->old_blocks,
10310                         lowpc, highpc, objfile);
10311
10312   /* For C++, set the block's scope.  */
10313   if ((cu->language == language_cplus || cu->language == language_fortran)
10314       && cu->processing_has_namespace_info)
10315     block_set_scope (block, determine_prefix (die, cu),
10316                      &objfile->objfile_obstack);
10317
10318   /* If we have address ranges, record them.  */
10319   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10320
10321   /* Attach template arguments to function.  */
10322   if (! VEC_empty (symbolp, template_args))
10323     {
10324       gdb_assert (templ_func != NULL);
10325
10326       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10327       templ_func->template_arguments
10328         = obstack_alloc (&objfile->objfile_obstack,
10329                          (templ_func->n_template_arguments
10330                           * sizeof (struct symbol *)));
10331       memcpy (templ_func->template_arguments,
10332               VEC_address (symbolp, template_args),
10333               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10334       VEC_free (symbolp, template_args);
10335     }
10336
10337   /* In C++, we can have functions nested inside functions (e.g., when
10338      a function declares a class that has methods).  This means that
10339      when we finish processing a function scope, we may need to go
10340      back to building a containing block's symbol lists.  */
10341   local_symbols = new->locals;
10342   using_directives = new->using_directives;
10343
10344   /* If we've finished processing a top-level function, subsequent
10345      symbols go in the file symbol list.  */
10346   if (outermost_context_p ())
10347     cu->list_in_scope = &file_symbols;
10348 }
10349
10350 /* Process all the DIES contained within a lexical block scope.  Start
10351    a new scope, process the dies, and then close the scope.  */
10352
10353 static void
10354 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10355 {
10356   struct objfile *objfile = cu->objfile;
10357   struct context_stack *new;
10358   CORE_ADDR lowpc, highpc;
10359   struct die_info *child_die;
10360   CORE_ADDR baseaddr;
10361
10362   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10363
10364   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10365   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10366      as multiple lexical blocks?  Handling children in a sane way would
10367      be nasty.  Might be easier to properly extend generic blocks to
10368      describe ranges.  */
10369   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10370     return;
10371   lowpc += baseaddr;
10372   highpc += baseaddr;
10373
10374   push_context (0, lowpc);
10375   if (die->child != NULL)
10376     {
10377       child_die = die->child;
10378       while (child_die && child_die->tag)
10379         {
10380           process_die (child_die, cu);
10381           child_die = sibling_die (child_die);
10382         }
10383     }
10384   new = pop_context ();
10385
10386   if (local_symbols != NULL || using_directives != NULL)
10387     {
10388       struct block *block
10389         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10390                         highpc, objfile);
10391
10392       /* Note that recording ranges after traversing children, as we
10393          do here, means that recording a parent's ranges entails
10394          walking across all its children's ranges as they appear in
10395          the address map, which is quadratic behavior.
10396
10397          It would be nicer to record the parent's ranges before
10398          traversing its children, simply overriding whatever you find
10399          there.  But since we don't even decide whether to create a
10400          block until after we've traversed its children, that's hard
10401          to do.  */
10402       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10403     }
10404   local_symbols = new->locals;
10405   using_directives = new->using_directives;
10406 }
10407
10408 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10409
10410 static void
10411 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10412 {
10413   struct objfile *objfile = cu->objfile;
10414   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10415   CORE_ADDR pc, baseaddr;
10416   struct attribute *attr;
10417   struct call_site *call_site, call_site_local;
10418   void **slot;
10419   int nparams;
10420   struct die_info *child_die;
10421
10422   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10423
10424   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10425   if (!attr)
10426     {
10427       complaint (&symfile_complaints,
10428                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10429                    "DIE 0x%x [in module %s]"),
10430                  die->offset.sect_off, objfile_name (objfile));
10431       return;
10432     }
10433   pc = DW_ADDR (attr) + baseaddr;
10434
10435   if (cu->call_site_htab == NULL)
10436     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10437                                                NULL, &objfile->objfile_obstack,
10438                                                hashtab_obstack_allocate, NULL);
10439   call_site_local.pc = pc;
10440   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10441   if (*slot != NULL)
10442     {
10443       complaint (&symfile_complaints,
10444                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10445                    "DIE 0x%x [in module %s]"),
10446                  paddress (gdbarch, pc), die->offset.sect_off,
10447                  objfile_name (objfile));
10448       return;
10449     }
10450
10451   /* Count parameters at the caller.  */
10452
10453   nparams = 0;
10454   for (child_die = die->child; child_die && child_die->tag;
10455        child_die = sibling_die (child_die))
10456     {
10457       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10458         {
10459           complaint (&symfile_complaints,
10460                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10461                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10462                      child_die->tag, child_die->offset.sect_off,
10463                      objfile_name (objfile));
10464           continue;
10465         }
10466
10467       nparams++;
10468     }
10469
10470   call_site = obstack_alloc (&objfile->objfile_obstack,
10471                              (sizeof (*call_site)
10472                               + (sizeof (*call_site->parameter)
10473                                  * (nparams - 1))));
10474   *slot = call_site;
10475   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10476   call_site->pc = pc;
10477
10478   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10479     {
10480       struct die_info *func_die;
10481
10482       /* Skip also over DW_TAG_inlined_subroutine.  */
10483       for (func_die = die->parent;
10484            func_die && func_die->tag != DW_TAG_subprogram
10485            && func_die->tag != DW_TAG_subroutine_type;
10486            func_die = func_die->parent);
10487
10488       /* DW_AT_GNU_all_call_sites is a superset
10489          of DW_AT_GNU_all_tail_call_sites.  */
10490       if (func_die
10491           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10492           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10493         {
10494           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10495              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10496              both the initial caller containing the real return address PC and
10497              the final callee containing the current PC of a chain of tail
10498              calls do not need to have the tail call list complete.  But any
10499              function candidate for a virtual tail call frame searched via
10500              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10501              determined unambiguously.  */
10502         }
10503       else
10504         {
10505           struct type *func_type = NULL;
10506
10507           if (func_die)
10508             func_type = get_die_type (func_die, cu);
10509           if (func_type != NULL)
10510             {
10511               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10512
10513               /* Enlist this call site to the function.  */
10514               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10515               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10516             }
10517           else
10518             complaint (&symfile_complaints,
10519                        _("Cannot find function owning DW_TAG_GNU_call_site "
10520                          "DIE 0x%x [in module %s]"),
10521                        die->offset.sect_off, objfile_name (objfile));
10522         }
10523     }
10524
10525   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10526   if (attr == NULL)
10527     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10528   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10529   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10530     /* Keep NULL DWARF_BLOCK.  */;
10531   else if (attr_form_is_block (attr))
10532     {
10533       struct dwarf2_locexpr_baton *dlbaton;
10534
10535       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10536       dlbaton->data = DW_BLOCK (attr)->data;
10537       dlbaton->size = DW_BLOCK (attr)->size;
10538       dlbaton->per_cu = cu->per_cu;
10539
10540       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10541     }
10542   else if (attr_form_is_ref (attr))
10543     {
10544       struct dwarf2_cu *target_cu = cu;
10545       struct die_info *target_die;
10546
10547       target_die = follow_die_ref (die, attr, &target_cu);
10548       gdb_assert (target_cu->objfile == objfile);
10549       if (die_is_declaration (target_die, target_cu))
10550         {
10551           const char *target_physname = NULL;
10552           struct attribute *target_attr;
10553
10554           /* Prefer the mangled name; otherwise compute the demangled one.  */
10555           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10556           if (target_attr == NULL)
10557             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10558                                        target_cu);
10559           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10560             target_physname = DW_STRING (target_attr);
10561           else
10562             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10563           if (target_physname == NULL)
10564             complaint (&symfile_complaints,
10565                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10566                          "physname, for referencing DIE 0x%x [in module %s]"),
10567                        die->offset.sect_off, objfile_name (objfile));
10568           else
10569             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10570         }
10571       else
10572         {
10573           CORE_ADDR lowpc;
10574
10575           /* DW_AT_entry_pc should be preferred.  */
10576           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10577             complaint (&symfile_complaints,
10578                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10579                          "low pc, for referencing DIE 0x%x [in module %s]"),
10580                        die->offset.sect_off, objfile_name (objfile));
10581           else
10582             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10583         }
10584     }
10585   else
10586     complaint (&symfile_complaints,
10587                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10588                  "block nor reference, for DIE 0x%x [in module %s]"),
10589                die->offset.sect_off, objfile_name (objfile));
10590
10591   call_site->per_cu = cu->per_cu;
10592
10593   for (child_die = die->child;
10594        child_die && child_die->tag;
10595        child_die = sibling_die (child_die))
10596     {
10597       struct call_site_parameter *parameter;
10598       struct attribute *loc, *origin;
10599
10600       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10601         {
10602           /* Already printed the complaint above.  */
10603           continue;
10604         }
10605
10606       gdb_assert (call_site->parameter_count < nparams);
10607       parameter = &call_site->parameter[call_site->parameter_count];
10608
10609       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10610          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10611          register is contained in DW_AT_GNU_call_site_value.  */
10612
10613       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10614       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10615       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
10616         {
10617           sect_offset offset;
10618
10619           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10620           offset = dwarf2_get_ref_die_offset (origin);
10621           if (!offset_in_cu_p (&cu->header, offset))
10622             {
10623               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10624                  binding can be done only inside one CU.  Such referenced DIE
10625                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10626               complaint (&symfile_complaints,
10627                          _("DW_AT_abstract_origin offset is not in CU for "
10628                            "DW_TAG_GNU_call_site child DIE 0x%x "
10629                            "[in module %s]"),
10630                          child_die->offset.sect_off, objfile_name (objfile));
10631               continue;
10632             }
10633           parameter->u.param_offset.cu_off = (offset.sect_off
10634                                               - cu->header.offset.sect_off);
10635         }
10636       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10637         {
10638           complaint (&symfile_complaints,
10639                      _("No DW_FORM_block* DW_AT_location for "
10640                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10641                      child_die->offset.sect_off, objfile_name (objfile));
10642           continue;
10643         }
10644       else
10645         {
10646           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10647             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10648           if (parameter->u.dwarf_reg != -1)
10649             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10650           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10651                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10652                                              &parameter->u.fb_offset))
10653             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10654           else
10655             {
10656               complaint (&symfile_complaints,
10657                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10658                            "for DW_FORM_block* DW_AT_location is supported for "
10659                            "DW_TAG_GNU_call_site child DIE 0x%x "
10660                            "[in module %s]"),
10661                          child_die->offset.sect_off, objfile_name (objfile));
10662               continue;
10663             }
10664         }
10665
10666       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10667       if (!attr_form_is_block (attr))
10668         {
10669           complaint (&symfile_complaints,
10670                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10671                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10672                      child_die->offset.sect_off, objfile_name (objfile));
10673           continue;
10674         }
10675       parameter->value = DW_BLOCK (attr)->data;
10676       parameter->value_size = DW_BLOCK (attr)->size;
10677
10678       /* Parameters are not pre-cleared by memset above.  */
10679       parameter->data_value = NULL;
10680       parameter->data_value_size = 0;
10681       call_site->parameter_count++;
10682
10683       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10684       if (attr)
10685         {
10686           if (!attr_form_is_block (attr))
10687             complaint (&symfile_complaints,
10688                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10689                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10690                        child_die->offset.sect_off, objfile_name (objfile));
10691           else
10692             {
10693               parameter->data_value = DW_BLOCK (attr)->data;
10694               parameter->data_value_size = DW_BLOCK (attr)->size;
10695             }
10696         }
10697     }
10698 }
10699
10700 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10701    Return 1 if the attributes are present and valid, otherwise, return 0.
10702    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10703
10704 static int
10705 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10706                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10707                     struct partial_symtab *ranges_pst)
10708 {
10709   struct objfile *objfile = cu->objfile;
10710   struct comp_unit_head *cu_header = &cu->header;
10711   bfd *obfd = objfile->obfd;
10712   unsigned int addr_size = cu_header->addr_size;
10713   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10714   /* Base address selection entry.  */
10715   CORE_ADDR base;
10716   int found_base;
10717   unsigned int dummy;
10718   const gdb_byte *buffer;
10719   CORE_ADDR marker;
10720   int low_set;
10721   CORE_ADDR low = 0;
10722   CORE_ADDR high = 0;
10723   CORE_ADDR baseaddr;
10724
10725   found_base = cu->base_known;
10726   base = cu->base_address;
10727
10728   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10729   if (offset >= dwarf2_per_objfile->ranges.size)
10730     {
10731       complaint (&symfile_complaints,
10732                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10733                  offset);
10734       return 0;
10735     }
10736   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10737
10738   /* Read in the largest possible address.  */
10739   marker = read_address (obfd, buffer, cu, &dummy);
10740   if ((marker & mask) == mask)
10741     {
10742       /* If we found the largest possible address, then
10743          read the base address.  */
10744       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10745       buffer += 2 * addr_size;
10746       offset += 2 * addr_size;
10747       found_base = 1;
10748     }
10749
10750   low_set = 0;
10751
10752   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10753
10754   while (1)
10755     {
10756       CORE_ADDR range_beginning, range_end;
10757
10758       range_beginning = read_address (obfd, buffer, cu, &dummy);
10759       buffer += addr_size;
10760       range_end = read_address (obfd, buffer, cu, &dummy);
10761       buffer += addr_size;
10762       offset += 2 * addr_size;
10763
10764       /* An end of list marker is a pair of zero addresses.  */
10765       if (range_beginning == 0 && range_end == 0)
10766         /* Found the end of list entry.  */
10767         break;
10768
10769       /* Each base address selection entry is a pair of 2 values.
10770          The first is the largest possible address, the second is
10771          the base address.  Check for a base address here.  */
10772       if ((range_beginning & mask) == mask)
10773         {
10774           /* If we found the largest possible address, then
10775              read the base address.  */
10776           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10777           found_base = 1;
10778           continue;
10779         }
10780
10781       if (!found_base)
10782         {
10783           /* We have no valid base address for the ranges
10784              data.  */
10785           complaint (&symfile_complaints,
10786                      _("Invalid .debug_ranges data (no base address)"));
10787           return 0;
10788         }
10789
10790       if (range_beginning > range_end)
10791         {
10792           /* Inverted range entries are invalid.  */
10793           complaint (&symfile_complaints,
10794                      _("Invalid .debug_ranges data (inverted range)"));
10795           return 0;
10796         }
10797
10798       /* Empty range entries have no effect.  */
10799       if (range_beginning == range_end)
10800         continue;
10801
10802       range_beginning += base;
10803       range_end += base;
10804
10805       /* A not-uncommon case of bad debug info.
10806          Don't pollute the addrmap with bad data.  */
10807       if (range_beginning + baseaddr == 0
10808           && !dwarf2_per_objfile->has_section_at_zero)
10809         {
10810           complaint (&symfile_complaints,
10811                      _(".debug_ranges entry has start address of zero"
10812                        " [in module %s]"), objfile_name (objfile));
10813           continue;
10814         }
10815
10816       if (ranges_pst != NULL)
10817         addrmap_set_empty (objfile->psymtabs_addrmap,
10818                            range_beginning + baseaddr,
10819                            range_end - 1 + baseaddr,
10820                            ranges_pst);
10821
10822       /* FIXME: This is recording everything as a low-high
10823          segment of consecutive addresses.  We should have a
10824          data structure for discontiguous block ranges
10825          instead.  */
10826       if (! low_set)
10827         {
10828           low = range_beginning;
10829           high = range_end;
10830           low_set = 1;
10831         }
10832       else
10833         {
10834           if (range_beginning < low)
10835             low = range_beginning;
10836           if (range_end > high)
10837             high = range_end;
10838         }
10839     }
10840
10841   if (! low_set)
10842     /* If the first entry is an end-of-list marker, the range
10843        describes an empty scope, i.e. no instructions.  */
10844     return 0;
10845
10846   if (low_return)
10847     *low_return = low;
10848   if (high_return)
10849     *high_return = high;
10850   return 1;
10851 }
10852
10853 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10854    are present and valid, otherwise, return 0.  Return -1 if the range is
10855    discontinuous, i.e. derived from DW_AT_ranges information.  */
10856
10857 static int
10858 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10859                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10860                       struct partial_symtab *pst)
10861 {
10862   struct attribute *attr;
10863   struct attribute *attr_high;
10864   CORE_ADDR low = 0;
10865   CORE_ADDR high = 0;
10866   int ret = 0;
10867
10868   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10869   if (attr_high)
10870     {
10871       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10872       if (attr)
10873         {
10874           low = DW_ADDR (attr);
10875           if (attr_high->form == DW_FORM_addr
10876               || attr_high->form == DW_FORM_GNU_addr_index)
10877             high = DW_ADDR (attr_high);
10878           else
10879             high = low + DW_UNSND (attr_high);
10880         }
10881       else
10882         /* Found high w/o low attribute.  */
10883         return 0;
10884
10885       /* Found consecutive range of addresses.  */
10886       ret = 1;
10887     }
10888   else
10889     {
10890       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10891       if (attr != NULL)
10892         {
10893           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10894              We take advantage of the fact that DW_AT_ranges does not appear
10895              in DW_TAG_compile_unit of DWO files.  */
10896           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10897           unsigned int ranges_offset = (DW_UNSND (attr)
10898                                         + (need_ranges_base
10899                                            ? cu->ranges_base
10900                                            : 0));
10901
10902           /* Value of the DW_AT_ranges attribute is the offset in the
10903              .debug_ranges section.  */
10904           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10905             return 0;
10906           /* Found discontinuous range of addresses.  */
10907           ret = -1;
10908         }
10909     }
10910
10911   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10912   if (high <= low)
10913     return 0;
10914
10915   /* When using the GNU linker, .gnu.linkonce. sections are used to
10916      eliminate duplicate copies of functions and vtables and such.
10917      The linker will arbitrarily choose one and discard the others.
10918      The AT_*_pc values for such functions refer to local labels in
10919      these sections.  If the section from that file was discarded, the
10920      labels are not in the output, so the relocs get a value of 0.
10921      If this is a discarded function, mark the pc bounds as invalid,
10922      so that GDB will ignore it.  */
10923   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10924     return 0;
10925
10926   *lowpc = low;
10927   if (highpc)
10928     *highpc = high;
10929   return ret;
10930 }
10931
10932 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10933    its low and high PC addresses.  Do nothing if these addresses could not
10934    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10935    and HIGHPC to the high address if greater than HIGHPC.  */
10936
10937 static void
10938 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10939                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10940                                  struct dwarf2_cu *cu)
10941 {
10942   CORE_ADDR low, high;
10943   struct die_info *child = die->child;
10944
10945   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10946     {
10947       *lowpc = min (*lowpc, low);
10948       *highpc = max (*highpc, high);
10949     }
10950
10951   /* If the language does not allow nested subprograms (either inside
10952      subprograms or lexical blocks), we're done.  */
10953   if (cu->language != language_ada)
10954     return;
10955
10956   /* Check all the children of the given DIE.  If it contains nested
10957      subprograms, then check their pc bounds.  Likewise, we need to
10958      check lexical blocks as well, as they may also contain subprogram
10959      definitions.  */
10960   while (child && child->tag)
10961     {
10962       if (child->tag == DW_TAG_subprogram
10963           || child->tag == DW_TAG_lexical_block)
10964         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10965       child = sibling_die (child);
10966     }
10967 }
10968
10969 /* Get the low and high pc's represented by the scope DIE, and store
10970    them in *LOWPC and *HIGHPC.  If the correct values can't be
10971    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10972
10973 static void
10974 get_scope_pc_bounds (struct die_info *die,
10975                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10976                      struct dwarf2_cu *cu)
10977 {
10978   CORE_ADDR best_low = (CORE_ADDR) -1;
10979   CORE_ADDR best_high = (CORE_ADDR) 0;
10980   CORE_ADDR current_low, current_high;
10981
10982   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10983     {
10984       best_low = current_low;
10985       best_high = current_high;
10986     }
10987   else
10988     {
10989       struct die_info *child = die->child;
10990
10991       while (child && child->tag)
10992         {
10993           switch (child->tag) {
10994           case DW_TAG_subprogram:
10995             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10996             break;
10997           case DW_TAG_namespace:
10998           case DW_TAG_module:
10999             /* FIXME: carlton/2004-01-16: Should we do this for
11000                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
11001                that current GCC's always emit the DIEs corresponding
11002                to definitions of methods of classes as children of a
11003                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
11004                the DIEs giving the declarations, which could be
11005                anywhere).  But I don't see any reason why the
11006                standards says that they have to be there.  */
11007             get_scope_pc_bounds (child, &current_low, &current_high, cu);
11008
11009             if (current_low != ((CORE_ADDR) -1))
11010               {
11011                 best_low = min (best_low, current_low);
11012                 best_high = max (best_high, current_high);
11013               }
11014             break;
11015           default:
11016             /* Ignore.  */
11017             break;
11018           }
11019
11020           child = sibling_die (child);
11021         }
11022     }
11023
11024   *lowpc = best_low;
11025   *highpc = best_high;
11026 }
11027
11028 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
11029    in DIE.  */
11030
11031 static void
11032 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
11033                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
11034 {
11035   struct objfile *objfile = cu->objfile;
11036   struct attribute *attr;
11037   struct attribute *attr_high;
11038
11039   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11040   if (attr_high)
11041     {
11042       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11043       if (attr)
11044         {
11045           CORE_ADDR low = DW_ADDR (attr);
11046           CORE_ADDR high;
11047           if (attr_high->form == DW_FORM_addr
11048               || attr_high->form == DW_FORM_GNU_addr_index)
11049             high = DW_ADDR (attr_high);
11050           else
11051             high = low + DW_UNSND (attr_high);
11052
11053           record_block_range (block, baseaddr + low, baseaddr + high - 1);
11054         }
11055     }
11056
11057   attr = dwarf2_attr (die, DW_AT_ranges, cu);
11058   if (attr)
11059     {
11060       bfd *obfd = objfile->obfd;
11061       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11062          We take advantage of the fact that DW_AT_ranges does not appear
11063          in DW_TAG_compile_unit of DWO files.  */
11064       int need_ranges_base = die->tag != DW_TAG_compile_unit;
11065
11066       /* The value of the DW_AT_ranges attribute is the offset of the
11067          address range list in the .debug_ranges section.  */
11068       unsigned long offset = (DW_UNSND (attr)
11069                               + (need_ranges_base ? cu->ranges_base : 0));
11070       const gdb_byte *buffer;
11071
11072       /* For some target architectures, but not others, the
11073          read_address function sign-extends the addresses it returns.
11074          To recognize base address selection entries, we need a
11075          mask.  */
11076       unsigned int addr_size = cu->header.addr_size;
11077       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11078
11079       /* The base address, to which the next pair is relative.  Note
11080          that this 'base' is a DWARF concept: most entries in a range
11081          list are relative, to reduce the number of relocs against the
11082          debugging information.  This is separate from this function's
11083          'baseaddr' argument, which GDB uses to relocate debugging
11084          information from a shared library based on the address at
11085          which the library was loaded.  */
11086       CORE_ADDR base = cu->base_address;
11087       int base_known = cu->base_known;
11088
11089       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11090       if (offset >= dwarf2_per_objfile->ranges.size)
11091         {
11092           complaint (&symfile_complaints,
11093                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
11094                      offset);
11095           return;
11096         }
11097       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11098
11099       for (;;)
11100         {
11101           unsigned int bytes_read;
11102           CORE_ADDR start, end;
11103
11104           start = read_address (obfd, buffer, cu, &bytes_read);
11105           buffer += bytes_read;
11106           end = read_address (obfd, buffer, cu, &bytes_read);
11107           buffer += bytes_read;
11108
11109           /* Did we find the end of the range list?  */
11110           if (start == 0 && end == 0)
11111             break;
11112
11113           /* Did we find a base address selection entry?  */
11114           else if ((start & base_select_mask) == base_select_mask)
11115             {
11116               base = end;
11117               base_known = 1;
11118             }
11119
11120           /* We found an ordinary address range.  */
11121           else
11122             {
11123               if (!base_known)
11124                 {
11125                   complaint (&symfile_complaints,
11126                              _("Invalid .debug_ranges data "
11127                                "(no base address)"));
11128                   return;
11129                 }
11130
11131               if (start > end)
11132                 {
11133                   /* Inverted range entries are invalid.  */
11134                   complaint (&symfile_complaints,
11135                              _("Invalid .debug_ranges data "
11136                                "(inverted range)"));
11137                   return;
11138                 }
11139
11140               /* Empty range entries have no effect.  */
11141               if (start == end)
11142                 continue;
11143
11144               start += base + baseaddr;
11145               end += base + baseaddr;
11146
11147               /* A not-uncommon case of bad debug info.
11148                  Don't pollute the addrmap with bad data.  */
11149               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11150                 {
11151                   complaint (&symfile_complaints,
11152                              _(".debug_ranges entry has start address of zero"
11153                                " [in module %s]"), objfile_name (objfile));
11154                   continue;
11155                 }
11156
11157               record_block_range (block, start, end - 1);
11158             }
11159         }
11160     }
11161 }
11162
11163 /* Check whether the producer field indicates either of GCC < 4.6, or the
11164    Intel C/C++ compiler, and cache the result in CU.  */
11165
11166 static void
11167 check_producer (struct dwarf2_cu *cu)
11168 {
11169   const char *cs;
11170   int major, minor, release;
11171
11172   if (cu->producer == NULL)
11173     {
11174       /* For unknown compilers expect their behavior is DWARF version
11175          compliant.
11176
11177          GCC started to support .debug_types sections by -gdwarf-4 since
11178          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11179          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11180          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11181          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11182     }
11183   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11184     {
11185       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11186
11187       cs = &cu->producer[strlen ("GNU ")];
11188       while (*cs && !isdigit (*cs))
11189         cs++;
11190       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11191         {
11192           /* Not recognized as GCC.  */
11193         }
11194       else
11195         {
11196           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11197           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11198         }
11199     }
11200   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11201     cu->producer_is_icc = 1;
11202   else
11203     {
11204       /* For other non-GCC compilers, expect their behavior is DWARF version
11205          compliant.  */
11206     }
11207
11208   cu->checked_producer = 1;
11209 }
11210
11211 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11212    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11213    during 4.6.0 experimental.  */
11214
11215 static int
11216 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11217 {
11218   if (!cu->checked_producer)
11219     check_producer (cu);
11220
11221   return cu->producer_is_gxx_lt_4_6;
11222 }
11223
11224 /* Return the default accessibility type if it is not overriden by
11225    DW_AT_accessibility.  */
11226
11227 static enum dwarf_access_attribute
11228 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11229 {
11230   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11231     {
11232       /* The default DWARF 2 accessibility for members is public, the default
11233          accessibility for inheritance is private.  */
11234
11235       if (die->tag != DW_TAG_inheritance)
11236         return DW_ACCESS_public;
11237       else
11238         return DW_ACCESS_private;
11239     }
11240   else
11241     {
11242       /* DWARF 3+ defines the default accessibility a different way.  The same
11243          rules apply now for DW_TAG_inheritance as for the members and it only
11244          depends on the container kind.  */
11245
11246       if (die->parent->tag == DW_TAG_class_type)
11247         return DW_ACCESS_private;
11248       else
11249         return DW_ACCESS_public;
11250     }
11251 }
11252
11253 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11254    offset.  If the attribute was not found return 0, otherwise return
11255    1.  If it was found but could not properly be handled, set *OFFSET
11256    to 0.  */
11257
11258 static int
11259 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11260                              LONGEST *offset)
11261 {
11262   struct attribute *attr;
11263
11264   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11265   if (attr != NULL)
11266     {
11267       *offset = 0;
11268
11269       /* Note that we do not check for a section offset first here.
11270          This is because DW_AT_data_member_location is new in DWARF 4,
11271          so if we see it, we can assume that a constant form is really
11272          a constant and not a section offset.  */
11273       if (attr_form_is_constant (attr))
11274         *offset = dwarf2_get_attr_constant_value (attr, 0);
11275       else if (attr_form_is_section_offset (attr))
11276         dwarf2_complex_location_expr_complaint ();
11277       else if (attr_form_is_block (attr))
11278         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11279       else
11280         dwarf2_complex_location_expr_complaint ();
11281
11282       return 1;
11283     }
11284
11285   return 0;
11286 }
11287
11288 /* Add an aggregate field to the field list.  */
11289
11290 static void
11291 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11292                   struct dwarf2_cu *cu)
11293 {
11294   struct objfile *objfile = cu->objfile;
11295   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11296   struct nextfield *new_field;
11297   struct attribute *attr;
11298   struct field *fp;
11299   const char *fieldname = "";
11300
11301   /* Allocate a new field list entry and link it in.  */
11302   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11303   make_cleanup (xfree, new_field);
11304   memset (new_field, 0, sizeof (struct nextfield));
11305
11306   if (die->tag == DW_TAG_inheritance)
11307     {
11308       new_field->next = fip->baseclasses;
11309       fip->baseclasses = new_field;
11310     }
11311   else
11312     {
11313       new_field->next = fip->fields;
11314       fip->fields = new_field;
11315     }
11316   fip->nfields++;
11317
11318   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11319   if (attr)
11320     new_field->accessibility = DW_UNSND (attr);
11321   else
11322     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11323   if (new_field->accessibility != DW_ACCESS_public)
11324     fip->non_public_fields = 1;
11325
11326   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11327   if (attr)
11328     new_field->virtuality = DW_UNSND (attr);
11329   else
11330     new_field->virtuality = DW_VIRTUALITY_none;
11331
11332   fp = &new_field->field;
11333
11334   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11335     {
11336       LONGEST offset;
11337
11338       /* Data member other than a C++ static data member.  */
11339
11340       /* Get type of field.  */
11341       fp->type = die_type (die, cu);
11342
11343       SET_FIELD_BITPOS (*fp, 0);
11344
11345       /* Get bit size of field (zero if none).  */
11346       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11347       if (attr)
11348         {
11349           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11350         }
11351       else
11352         {
11353           FIELD_BITSIZE (*fp) = 0;
11354         }
11355
11356       /* Get bit offset of field.  */
11357       if (handle_data_member_location (die, cu, &offset))
11358         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11359       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11360       if (attr)
11361         {
11362           if (gdbarch_bits_big_endian (gdbarch))
11363             {
11364               /* For big endian bits, the DW_AT_bit_offset gives the
11365                  additional bit offset from the MSB of the containing
11366                  anonymous object to the MSB of the field.  We don't
11367                  have to do anything special since we don't need to
11368                  know the size of the anonymous object.  */
11369               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11370             }
11371           else
11372             {
11373               /* For little endian bits, compute the bit offset to the
11374                  MSB of the anonymous object, subtract off the number of
11375                  bits from the MSB of the field to the MSB of the
11376                  object, and then subtract off the number of bits of
11377                  the field itself.  The result is the bit offset of
11378                  the LSB of the field.  */
11379               int anonymous_size;
11380               int bit_offset = DW_UNSND (attr);
11381
11382               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11383               if (attr)
11384                 {
11385                   /* The size of the anonymous object containing
11386                      the bit field is explicit, so use the
11387                      indicated size (in bytes).  */
11388                   anonymous_size = DW_UNSND (attr);
11389                 }
11390               else
11391                 {
11392                   /* The size of the anonymous object containing
11393                      the bit field must be inferred from the type
11394                      attribute of the data member containing the
11395                      bit field.  */
11396                   anonymous_size = TYPE_LENGTH (fp->type);
11397                 }
11398               SET_FIELD_BITPOS (*fp,
11399                                 (FIELD_BITPOS (*fp)
11400                                  + anonymous_size * bits_per_byte
11401                                  - bit_offset - FIELD_BITSIZE (*fp)));
11402             }
11403         }
11404
11405       /* Get name of field.  */
11406       fieldname = dwarf2_name (die, cu);
11407       if (fieldname == NULL)
11408         fieldname = "";
11409
11410       /* The name is already allocated along with this objfile, so we don't
11411          need to duplicate it for the type.  */
11412       fp->name = fieldname;
11413
11414       /* Change accessibility for artificial fields (e.g. virtual table
11415          pointer or virtual base class pointer) to private.  */
11416       if (dwarf2_attr (die, DW_AT_artificial, cu))
11417         {
11418           FIELD_ARTIFICIAL (*fp) = 1;
11419           new_field->accessibility = DW_ACCESS_private;
11420           fip->non_public_fields = 1;
11421         }
11422     }
11423   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11424     {
11425       /* C++ static member.  */
11426
11427       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11428          is a declaration, but all versions of G++ as of this writing
11429          (so through at least 3.2.1) incorrectly generate
11430          DW_TAG_variable tags.  */
11431
11432       const char *physname;
11433
11434       /* Get name of field.  */
11435       fieldname = dwarf2_name (die, cu);
11436       if (fieldname == NULL)
11437         return;
11438
11439       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11440       if (attr
11441           /* Only create a symbol if this is an external value.
11442              new_symbol checks this and puts the value in the global symbol
11443              table, which we want.  If it is not external, new_symbol
11444              will try to put the value in cu->list_in_scope which is wrong.  */
11445           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11446         {
11447           /* A static const member, not much different than an enum as far as
11448              we're concerned, except that we can support more types.  */
11449           new_symbol (die, NULL, cu);
11450         }
11451
11452       /* Get physical name.  */
11453       physname = dwarf2_physname (fieldname, die, cu);
11454
11455       /* The name is already allocated along with this objfile, so we don't
11456          need to duplicate it for the type.  */
11457       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11458       FIELD_TYPE (*fp) = die_type (die, cu);
11459       FIELD_NAME (*fp) = fieldname;
11460     }
11461   else if (die->tag == DW_TAG_inheritance)
11462     {
11463       LONGEST offset;
11464
11465       /* C++ base class field.  */
11466       if (handle_data_member_location (die, cu, &offset))
11467         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11468       FIELD_BITSIZE (*fp) = 0;
11469       FIELD_TYPE (*fp) = die_type (die, cu);
11470       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11471       fip->nbaseclasses++;
11472     }
11473 }
11474
11475 /* Add a typedef defined in the scope of the FIP's class.  */
11476
11477 static void
11478 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11479                     struct dwarf2_cu *cu)
11480 {
11481   struct objfile *objfile = cu->objfile;
11482   struct typedef_field_list *new_field;
11483   struct attribute *attr;
11484   struct typedef_field *fp;
11485   char *fieldname = "";
11486
11487   /* Allocate a new field list entry and link it in.  */
11488   new_field = xzalloc (sizeof (*new_field));
11489   make_cleanup (xfree, new_field);
11490
11491   gdb_assert (die->tag == DW_TAG_typedef);
11492
11493   fp = &new_field->field;
11494
11495   /* Get name of field.  */
11496   fp->name = dwarf2_name (die, cu);
11497   if (fp->name == NULL)
11498     return;
11499
11500   fp->type = read_type_die (die, cu);
11501
11502   new_field->next = fip->typedef_field_list;
11503   fip->typedef_field_list = new_field;
11504   fip->typedef_field_list_count++;
11505 }
11506
11507 /* Create the vector of fields, and attach it to the type.  */
11508
11509 static void
11510 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11511                               struct dwarf2_cu *cu)
11512 {
11513   int nfields = fip->nfields;
11514
11515   /* Record the field count, allocate space for the array of fields,
11516      and create blank accessibility bitfields if necessary.  */
11517   TYPE_NFIELDS (type) = nfields;
11518   TYPE_FIELDS (type) = (struct field *)
11519     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11520   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11521
11522   if (fip->non_public_fields && cu->language != language_ada)
11523     {
11524       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11525
11526       TYPE_FIELD_PRIVATE_BITS (type) =
11527         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11528       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11529
11530       TYPE_FIELD_PROTECTED_BITS (type) =
11531         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11532       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11533
11534       TYPE_FIELD_IGNORE_BITS (type) =
11535         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11536       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11537     }
11538
11539   /* If the type has baseclasses, allocate and clear a bit vector for
11540      TYPE_FIELD_VIRTUAL_BITS.  */
11541   if (fip->nbaseclasses && cu->language != language_ada)
11542     {
11543       int num_bytes = B_BYTES (fip->nbaseclasses);
11544       unsigned char *pointer;
11545
11546       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11547       pointer = TYPE_ALLOC (type, num_bytes);
11548       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11549       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11550       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11551     }
11552
11553   /* Copy the saved-up fields into the field vector.  Start from the head of
11554      the list, adding to the tail of the field array, so that they end up in
11555      the same order in the array in which they were added to the list.  */
11556   while (nfields-- > 0)
11557     {
11558       struct nextfield *fieldp;
11559
11560       if (fip->fields)
11561         {
11562           fieldp = fip->fields;
11563           fip->fields = fieldp->next;
11564         }
11565       else
11566         {
11567           fieldp = fip->baseclasses;
11568           fip->baseclasses = fieldp->next;
11569         }
11570
11571       TYPE_FIELD (type, nfields) = fieldp->field;
11572       switch (fieldp->accessibility)
11573         {
11574         case DW_ACCESS_private:
11575           if (cu->language != language_ada)
11576             SET_TYPE_FIELD_PRIVATE (type, nfields);
11577           break;
11578
11579         case DW_ACCESS_protected:
11580           if (cu->language != language_ada)
11581             SET_TYPE_FIELD_PROTECTED (type, nfields);
11582           break;
11583
11584         case DW_ACCESS_public:
11585           break;
11586
11587         default:
11588           /* Unknown accessibility.  Complain and treat it as public.  */
11589           {
11590             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11591                        fieldp->accessibility);
11592           }
11593           break;
11594         }
11595       if (nfields < fip->nbaseclasses)
11596         {
11597           switch (fieldp->virtuality)
11598             {
11599             case DW_VIRTUALITY_virtual:
11600             case DW_VIRTUALITY_pure_virtual:
11601               if (cu->language == language_ada)
11602                 error (_("unexpected virtuality in component of Ada type"));
11603               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11604               break;
11605             }
11606         }
11607     }
11608 }
11609
11610 /* Return true if this member function is a constructor, false
11611    otherwise.  */
11612
11613 static int
11614 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11615 {
11616   const char *fieldname;
11617   const char *typename;
11618   int len;
11619
11620   if (die->parent == NULL)
11621     return 0;
11622
11623   if (die->parent->tag != DW_TAG_structure_type
11624       && die->parent->tag != DW_TAG_union_type
11625       && die->parent->tag != DW_TAG_class_type)
11626     return 0;
11627
11628   fieldname = dwarf2_name (die, cu);
11629   typename = dwarf2_name (die->parent, cu);
11630   if (fieldname == NULL || typename == NULL)
11631     return 0;
11632
11633   len = strlen (fieldname);
11634   return (strncmp (fieldname, typename, len) == 0
11635           && (typename[len] == '\0' || typename[len] == '<'));
11636 }
11637
11638 /* Add a member function to the proper fieldlist.  */
11639
11640 static void
11641 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11642                       struct type *type, struct dwarf2_cu *cu)
11643 {
11644   struct objfile *objfile = cu->objfile;
11645   struct attribute *attr;
11646   struct fnfieldlist *flp;
11647   int i;
11648   struct fn_field *fnp;
11649   const char *fieldname;
11650   struct nextfnfield *new_fnfield;
11651   struct type *this_type;
11652   enum dwarf_access_attribute accessibility;
11653
11654   if (cu->language == language_ada)
11655     error (_("unexpected member function in Ada type"));
11656
11657   /* Get name of member function.  */
11658   fieldname = dwarf2_name (die, cu);
11659   if (fieldname == NULL)
11660     return;
11661
11662   /* Look up member function name in fieldlist.  */
11663   for (i = 0; i < fip->nfnfields; i++)
11664     {
11665       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11666         break;
11667     }
11668
11669   /* Create new list element if necessary.  */
11670   if (i < fip->nfnfields)
11671     flp = &fip->fnfieldlists[i];
11672   else
11673     {
11674       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11675         {
11676           fip->fnfieldlists = (struct fnfieldlist *)
11677             xrealloc (fip->fnfieldlists,
11678                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11679                       * sizeof (struct fnfieldlist));
11680           if (fip->nfnfields == 0)
11681             make_cleanup (free_current_contents, &fip->fnfieldlists);
11682         }
11683       flp = &fip->fnfieldlists[fip->nfnfields];
11684       flp->name = fieldname;
11685       flp->length = 0;
11686       flp->head = NULL;
11687       i = fip->nfnfields++;
11688     }
11689
11690   /* Create a new member function field and chain it to the field list
11691      entry.  */
11692   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11693   make_cleanup (xfree, new_fnfield);
11694   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11695   new_fnfield->next = flp->head;
11696   flp->head = new_fnfield;
11697   flp->length++;
11698
11699   /* Fill in the member function field info.  */
11700   fnp = &new_fnfield->fnfield;
11701
11702   /* Delay processing of the physname until later.  */
11703   if (cu->language == language_cplus || cu->language == language_java)
11704     {
11705       add_to_method_list (type, i, flp->length - 1, fieldname,
11706                           die, cu);
11707     }
11708   else
11709     {
11710       const char *physname = dwarf2_physname (fieldname, die, cu);
11711       fnp->physname = physname ? physname : "";
11712     }
11713
11714   fnp->type = alloc_type (objfile);
11715   this_type = read_type_die (die, cu);
11716   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11717     {
11718       int nparams = TYPE_NFIELDS (this_type);
11719
11720       /* TYPE is the domain of this method, and THIS_TYPE is the type
11721            of the method itself (TYPE_CODE_METHOD).  */
11722       smash_to_method_type (fnp->type, type,
11723                             TYPE_TARGET_TYPE (this_type),
11724                             TYPE_FIELDS (this_type),
11725                             TYPE_NFIELDS (this_type),
11726                             TYPE_VARARGS (this_type));
11727
11728       /* Handle static member functions.
11729          Dwarf2 has no clean way to discern C++ static and non-static
11730          member functions.  G++ helps GDB by marking the first
11731          parameter for non-static member functions (which is the this
11732          pointer) as artificial.  We obtain this information from
11733          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11734       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11735         fnp->voffset = VOFFSET_STATIC;
11736     }
11737   else
11738     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11739                dwarf2_full_name (fieldname, die, cu));
11740
11741   /* Get fcontext from DW_AT_containing_type if present.  */
11742   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11743     fnp->fcontext = die_containing_type (die, cu);
11744
11745   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11746      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11747
11748   /* Get accessibility.  */
11749   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11750   if (attr)
11751     accessibility = DW_UNSND (attr);
11752   else
11753     accessibility = dwarf2_default_access_attribute (die, cu);
11754   switch (accessibility)
11755     {
11756     case DW_ACCESS_private:
11757       fnp->is_private = 1;
11758       break;
11759     case DW_ACCESS_protected:
11760       fnp->is_protected = 1;
11761       break;
11762     }
11763
11764   /* Check for artificial methods.  */
11765   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11766   if (attr && DW_UNSND (attr) != 0)
11767     fnp->is_artificial = 1;
11768
11769   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11770
11771   /* Get index in virtual function table if it is a virtual member
11772      function.  For older versions of GCC, this is an offset in the
11773      appropriate virtual table, as specified by DW_AT_containing_type.
11774      For everyone else, it is an expression to be evaluated relative
11775      to the object address.  */
11776
11777   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11778   if (attr)
11779     {
11780       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11781         {
11782           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11783             {
11784               /* Old-style GCC.  */
11785               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11786             }
11787           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11788                    || (DW_BLOCK (attr)->size > 1
11789                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11790                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11791             {
11792               struct dwarf_block blk;
11793               int offset;
11794
11795               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11796                         ? 1 : 2);
11797               blk.size = DW_BLOCK (attr)->size - offset;
11798               blk.data = DW_BLOCK (attr)->data + offset;
11799               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11800               if ((fnp->voffset % cu->header.addr_size) != 0)
11801                 dwarf2_complex_location_expr_complaint ();
11802               else
11803                 fnp->voffset /= cu->header.addr_size;
11804               fnp->voffset += 2;
11805             }
11806           else
11807             dwarf2_complex_location_expr_complaint ();
11808
11809           if (!fnp->fcontext)
11810             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11811         }
11812       else if (attr_form_is_section_offset (attr))
11813         {
11814           dwarf2_complex_location_expr_complaint ();
11815         }
11816       else
11817         {
11818           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11819                                                  fieldname);
11820         }
11821     }
11822   else
11823     {
11824       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11825       if (attr && DW_UNSND (attr))
11826         {
11827           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11828           complaint (&symfile_complaints,
11829                      _("Member function \"%s\" (offset %d) is virtual "
11830                        "but the vtable offset is not specified"),
11831                      fieldname, die->offset.sect_off);
11832           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11833           TYPE_CPLUS_DYNAMIC (type) = 1;
11834         }
11835     }
11836 }
11837
11838 /* Create the vector of member function fields, and attach it to the type.  */
11839
11840 static void
11841 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11842                                  struct dwarf2_cu *cu)
11843 {
11844   struct fnfieldlist *flp;
11845   int i;
11846
11847   if (cu->language == language_ada)
11848     error (_("unexpected member functions in Ada type"));
11849
11850   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11851   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11852     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11853
11854   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11855     {
11856       struct nextfnfield *nfp = flp->head;
11857       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11858       int k;
11859
11860       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11861       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11862       fn_flp->fn_fields = (struct fn_field *)
11863         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11864       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11865         fn_flp->fn_fields[k] = nfp->fnfield;
11866     }
11867
11868   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11869 }
11870
11871 /* Returns non-zero if NAME is the name of a vtable member in CU's
11872    language, zero otherwise.  */
11873 static int
11874 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11875 {
11876   static const char vptr[] = "_vptr";
11877   static const char vtable[] = "vtable";
11878
11879   /* Look for the C++ and Java forms of the vtable.  */
11880   if ((cu->language == language_java
11881        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11882        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11883        && is_cplus_marker (name[sizeof (vptr) - 1])))
11884     return 1;
11885
11886   return 0;
11887 }
11888
11889 /* GCC outputs unnamed structures that are really pointers to member
11890    functions, with the ABI-specified layout.  If TYPE describes
11891    such a structure, smash it into a member function type.
11892
11893    GCC shouldn't do this; it should just output pointer to member DIEs.
11894    This is GCC PR debug/28767.  */
11895
11896 static void
11897 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11898 {
11899   struct type *pfn_type, *domain_type, *new_type;
11900
11901   /* Check for a structure with no name and two children.  */
11902   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11903     return;
11904
11905   /* Check for __pfn and __delta members.  */
11906   if (TYPE_FIELD_NAME (type, 0) == NULL
11907       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11908       || TYPE_FIELD_NAME (type, 1) == NULL
11909       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11910     return;
11911
11912   /* Find the type of the method.  */
11913   pfn_type = TYPE_FIELD_TYPE (type, 0);
11914   if (pfn_type == NULL
11915       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11916       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11917     return;
11918
11919   /* Look for the "this" argument.  */
11920   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11921   if (TYPE_NFIELDS (pfn_type) == 0
11922       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11923       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11924     return;
11925
11926   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11927   new_type = alloc_type (objfile);
11928   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11929                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11930                         TYPE_VARARGS (pfn_type));
11931   smash_to_methodptr_type (type, new_type);
11932 }
11933
11934 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11935    (icc).  */
11936
11937 static int
11938 producer_is_icc (struct dwarf2_cu *cu)
11939 {
11940   if (!cu->checked_producer)
11941     check_producer (cu);
11942
11943   return cu->producer_is_icc;
11944 }
11945
11946 /* Called when we find the DIE that starts a structure or union scope
11947    (definition) to create a type for the structure or union.  Fill in
11948    the type's name and general properties; the members will not be
11949    processed until process_structure_scope.
11950
11951    NOTE: we need to call these functions regardless of whether or not the
11952    DIE has a DW_AT_name attribute, since it might be an anonymous
11953    structure or union.  This gets the type entered into our set of
11954    user defined types.
11955
11956    However, if the structure is incomplete (an opaque struct/union)
11957    then suppress creating a symbol table entry for it since gdb only
11958    wants to find the one with the complete definition.  Note that if
11959    it is complete, we just call new_symbol, which does it's own
11960    checking about whether the struct/union is anonymous or not (and
11961    suppresses creating a symbol table entry itself).  */
11962
11963 static struct type *
11964 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11965 {
11966   struct objfile *objfile = cu->objfile;
11967   struct type *type;
11968   struct attribute *attr;
11969   const char *name;
11970
11971   /* If the definition of this type lives in .debug_types, read that type.
11972      Don't follow DW_AT_specification though, that will take us back up
11973      the chain and we want to go down.  */
11974   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11975   if (attr)
11976     {
11977       type = get_DW_AT_signature_type (die, attr, cu);
11978
11979       /* The type's CU may not be the same as CU.
11980          Ensure TYPE is recorded with CU in die_type_hash.  */
11981       return set_die_type (die, type, cu);
11982     }
11983
11984   type = alloc_type (objfile);
11985   INIT_CPLUS_SPECIFIC (type);
11986
11987   name = dwarf2_name (die, cu);
11988   if (name != NULL)
11989     {
11990       if (cu->language == language_cplus
11991           || cu->language == language_java)
11992         {
11993           const char *full_name = dwarf2_full_name (name, die, cu);
11994
11995           /* dwarf2_full_name might have already finished building the DIE's
11996              type.  If so, there is no need to continue.  */
11997           if (get_die_type (die, cu) != NULL)
11998             return get_die_type (die, cu);
11999
12000           TYPE_TAG_NAME (type) = full_name;
12001           if (die->tag == DW_TAG_structure_type
12002               || die->tag == DW_TAG_class_type)
12003             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12004         }
12005       else
12006         {
12007           /* The name is already allocated along with this objfile, so
12008              we don't need to duplicate it for the type.  */
12009           TYPE_TAG_NAME (type) = name;
12010           if (die->tag == DW_TAG_class_type)
12011             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12012         }
12013     }
12014
12015   if (die->tag == DW_TAG_structure_type)
12016     {
12017       TYPE_CODE (type) = TYPE_CODE_STRUCT;
12018     }
12019   else if (die->tag == DW_TAG_union_type)
12020     {
12021       TYPE_CODE (type) = TYPE_CODE_UNION;
12022     }
12023   else
12024     {
12025       TYPE_CODE (type) = TYPE_CODE_CLASS;
12026     }
12027
12028   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
12029     TYPE_DECLARED_CLASS (type) = 1;
12030
12031   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12032   if (attr)
12033     {
12034       TYPE_LENGTH (type) = DW_UNSND (attr);
12035     }
12036   else
12037     {
12038       TYPE_LENGTH (type) = 0;
12039     }
12040
12041   if (producer_is_icc (cu))
12042     {
12043       /* ICC does not output the required DW_AT_declaration
12044          on incomplete types, but gives them a size of zero.  */
12045     }
12046   else
12047     TYPE_STUB_SUPPORTED (type) = 1;
12048
12049   if (die_is_declaration (die, cu))
12050     TYPE_STUB (type) = 1;
12051   else if (attr == NULL && die->child == NULL
12052            && producer_is_realview (cu->producer))
12053     /* RealView does not output the required DW_AT_declaration
12054        on incomplete types.  */
12055     TYPE_STUB (type) = 1;
12056
12057   /* We need to add the type field to the die immediately so we don't
12058      infinitely recurse when dealing with pointers to the structure
12059      type within the structure itself.  */
12060   set_die_type (die, type, cu);
12061
12062   /* set_die_type should be already done.  */
12063   set_descriptive_type (type, die, cu);
12064
12065   return type;
12066 }
12067
12068 /* Finish creating a structure or union type, including filling in
12069    its members and creating a symbol for it.  */
12070
12071 static void
12072 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
12073 {
12074   struct objfile *objfile = cu->objfile;
12075   struct die_info *child_die = die->child;
12076   struct type *type;
12077
12078   type = get_die_type (die, cu);
12079   if (type == NULL)
12080     type = read_structure_type (die, cu);
12081
12082   if (die->child != NULL && ! die_is_declaration (die, cu))
12083     {
12084       struct field_info fi;
12085       struct die_info *child_die;
12086       VEC (symbolp) *template_args = NULL;
12087       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
12088
12089       memset (&fi, 0, sizeof (struct field_info));
12090
12091       child_die = die->child;
12092
12093       while (child_die && child_die->tag)
12094         {
12095           if (child_die->tag == DW_TAG_member
12096               || child_die->tag == DW_TAG_variable)
12097             {
12098               /* NOTE: carlton/2002-11-05: A C++ static data member
12099                  should be a DW_TAG_member that is a declaration, but
12100                  all versions of G++ as of this writing (so through at
12101                  least 3.2.1) incorrectly generate DW_TAG_variable
12102                  tags for them instead.  */
12103               dwarf2_add_field (&fi, child_die, cu);
12104             }
12105           else if (child_die->tag == DW_TAG_subprogram)
12106             {
12107               /* C++ member function.  */
12108               dwarf2_add_member_fn (&fi, child_die, type, cu);
12109             }
12110           else if (child_die->tag == DW_TAG_inheritance)
12111             {
12112               /* C++ base class field.  */
12113               dwarf2_add_field (&fi, child_die, cu);
12114             }
12115           else if (child_die->tag == DW_TAG_typedef)
12116             dwarf2_add_typedef (&fi, child_die, cu);
12117           else if (child_die->tag == DW_TAG_template_type_param
12118                    || child_die->tag == DW_TAG_template_value_param)
12119             {
12120               struct symbol *arg = new_symbol (child_die, NULL, cu);
12121
12122               if (arg != NULL)
12123                 VEC_safe_push (symbolp, template_args, arg);
12124             }
12125
12126           child_die = sibling_die (child_die);
12127         }
12128
12129       /* Attach template arguments to type.  */
12130       if (! VEC_empty (symbolp, template_args))
12131         {
12132           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12133           TYPE_N_TEMPLATE_ARGUMENTS (type)
12134             = VEC_length (symbolp, template_args);
12135           TYPE_TEMPLATE_ARGUMENTS (type)
12136             = obstack_alloc (&objfile->objfile_obstack,
12137                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12138                               * sizeof (struct symbol *)));
12139           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12140                   VEC_address (symbolp, template_args),
12141                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12142                    * sizeof (struct symbol *)));
12143           VEC_free (symbolp, template_args);
12144         }
12145
12146       /* Attach fields and member functions to the type.  */
12147       if (fi.nfields)
12148         dwarf2_attach_fields_to_type (&fi, type, cu);
12149       if (fi.nfnfields)
12150         {
12151           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12152
12153           /* Get the type which refers to the base class (possibly this
12154              class itself) which contains the vtable pointer for the current
12155              class from the DW_AT_containing_type attribute.  This use of
12156              DW_AT_containing_type is a GNU extension.  */
12157
12158           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12159             {
12160               struct type *t = die_containing_type (die, cu);
12161
12162               TYPE_VPTR_BASETYPE (type) = t;
12163               if (type == t)
12164                 {
12165                   int i;
12166
12167                   /* Our own class provides vtbl ptr.  */
12168                   for (i = TYPE_NFIELDS (t) - 1;
12169                        i >= TYPE_N_BASECLASSES (t);
12170                        --i)
12171                     {
12172                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12173
12174                       if (is_vtable_name (fieldname, cu))
12175                         {
12176                           TYPE_VPTR_FIELDNO (type) = i;
12177                           break;
12178                         }
12179                     }
12180
12181                   /* Complain if virtual function table field not found.  */
12182                   if (i < TYPE_N_BASECLASSES (t))
12183                     complaint (&symfile_complaints,
12184                                _("virtual function table pointer "
12185                                  "not found when defining class '%s'"),
12186                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12187                                "");
12188                 }
12189               else
12190                 {
12191                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12192                 }
12193             }
12194           else if (cu->producer
12195                    && strncmp (cu->producer,
12196                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12197             {
12198               /* The IBM XLC compiler does not provide direct indication
12199                  of the containing type, but the vtable pointer is
12200                  always named __vfp.  */
12201
12202               int i;
12203
12204               for (i = TYPE_NFIELDS (type) - 1;
12205                    i >= TYPE_N_BASECLASSES (type);
12206                    --i)
12207                 {
12208                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12209                     {
12210                       TYPE_VPTR_FIELDNO (type) = i;
12211                       TYPE_VPTR_BASETYPE (type) = type;
12212                       break;
12213                     }
12214                 }
12215             }
12216         }
12217
12218       /* Copy fi.typedef_field_list linked list elements content into the
12219          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12220       if (fi.typedef_field_list)
12221         {
12222           int i = fi.typedef_field_list_count;
12223
12224           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12225           TYPE_TYPEDEF_FIELD_ARRAY (type)
12226             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12227           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12228
12229           /* Reverse the list order to keep the debug info elements order.  */
12230           while (--i >= 0)
12231             {
12232               struct typedef_field *dest, *src;
12233
12234               dest = &TYPE_TYPEDEF_FIELD (type, i);
12235               src = &fi.typedef_field_list->field;
12236               fi.typedef_field_list = fi.typedef_field_list->next;
12237               *dest = *src;
12238             }
12239         }
12240
12241       do_cleanups (back_to);
12242
12243       if (HAVE_CPLUS_STRUCT (type))
12244         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12245     }
12246
12247   quirk_gcc_member_function_pointer (type, objfile);
12248
12249   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12250      snapshots) has been known to create a die giving a declaration
12251      for a class that has, as a child, a die giving a definition for a
12252      nested class.  So we have to process our children even if the
12253      current die is a declaration.  Normally, of course, a declaration
12254      won't have any children at all.  */
12255
12256   while (child_die != NULL && child_die->tag)
12257     {
12258       if (child_die->tag == DW_TAG_member
12259           || child_die->tag == DW_TAG_variable
12260           || child_die->tag == DW_TAG_inheritance
12261           || child_die->tag == DW_TAG_template_value_param
12262           || child_die->tag == DW_TAG_template_type_param)
12263         {
12264           /* Do nothing.  */
12265         }
12266       else
12267         process_die (child_die, cu);
12268
12269       child_die = sibling_die (child_die);
12270     }
12271
12272   /* Do not consider external references.  According to the DWARF standard,
12273      these DIEs are identified by the fact that they have no byte_size
12274      attribute, and a declaration attribute.  */
12275   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12276       || !die_is_declaration (die, cu))
12277     new_symbol (die, type, cu);
12278 }
12279
12280 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12281    complete the type's fields yet, or create any symbols.  */
12282
12283 static struct type *
12284 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12285 {
12286   struct objfile *objfile = cu->objfile;
12287   struct type *type;
12288   struct attribute *attr;
12289   const char *name;
12290
12291   /* If the definition of this type lives in .debug_types, read that type.
12292      Don't follow DW_AT_specification though, that will take us back up
12293      the chain and we want to go down.  */
12294   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12295   if (attr)
12296     {
12297       type = get_DW_AT_signature_type (die, attr, cu);
12298
12299       /* The type's CU may not be the same as CU.
12300          Ensure TYPE is recorded with CU in die_type_hash.  */
12301       return set_die_type (die, type, cu);
12302     }
12303
12304   type = alloc_type (objfile);
12305
12306   TYPE_CODE (type) = TYPE_CODE_ENUM;
12307   name = dwarf2_full_name (NULL, die, cu);
12308   if (name != NULL)
12309     TYPE_TAG_NAME (type) = name;
12310
12311   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12312   if (attr)
12313     {
12314       TYPE_LENGTH (type) = DW_UNSND (attr);
12315     }
12316   else
12317     {
12318       TYPE_LENGTH (type) = 0;
12319     }
12320
12321   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12322      declared as private in the package spec, and then defined only
12323      inside the package body.  Such types are known as Taft Amendment
12324      Types.  When another package uses such a type, an incomplete DIE
12325      may be generated by the compiler.  */
12326   if (die_is_declaration (die, cu))
12327     TYPE_STUB (type) = 1;
12328
12329   return set_die_type (die, type, cu);
12330 }
12331
12332 /* Given a pointer to a die which begins an enumeration, process all
12333    the dies that define the members of the enumeration, and create the
12334    symbol for the enumeration type.
12335
12336    NOTE: We reverse the order of the element list.  */
12337
12338 static void
12339 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12340 {
12341   struct type *this_type;
12342
12343   this_type = get_die_type (die, cu);
12344   if (this_type == NULL)
12345     this_type = read_enumeration_type (die, cu);
12346
12347   if (die->child != NULL)
12348     {
12349       struct die_info *child_die;
12350       struct symbol *sym;
12351       struct field *fields = NULL;
12352       int num_fields = 0;
12353       int unsigned_enum = 1;
12354       const char *name;
12355       int flag_enum = 1;
12356       ULONGEST mask = 0;
12357
12358       child_die = die->child;
12359       while (child_die && child_die->tag)
12360         {
12361           if (child_die->tag != DW_TAG_enumerator)
12362             {
12363               process_die (child_die, cu);
12364             }
12365           else
12366             {
12367               name = dwarf2_name (child_die, cu);
12368               if (name)
12369                 {
12370                   sym = new_symbol (child_die, this_type, cu);
12371                   if (SYMBOL_VALUE (sym) < 0)
12372                     {
12373                       unsigned_enum = 0;
12374                       flag_enum = 0;
12375                     }
12376                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12377                     flag_enum = 0;
12378                   else
12379                     mask |= SYMBOL_VALUE (sym);
12380
12381                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12382                     {
12383                       fields = (struct field *)
12384                         xrealloc (fields,
12385                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12386                                   * sizeof (struct field));
12387                     }
12388
12389                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12390                   FIELD_TYPE (fields[num_fields]) = NULL;
12391                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12392                   FIELD_BITSIZE (fields[num_fields]) = 0;
12393
12394                   num_fields++;
12395                 }
12396             }
12397
12398           child_die = sibling_die (child_die);
12399         }
12400
12401       if (num_fields)
12402         {
12403           TYPE_NFIELDS (this_type) = num_fields;
12404           TYPE_FIELDS (this_type) = (struct field *)
12405             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12406           memcpy (TYPE_FIELDS (this_type), fields,
12407                   sizeof (struct field) * num_fields);
12408           xfree (fields);
12409         }
12410       if (unsigned_enum)
12411         TYPE_UNSIGNED (this_type) = 1;
12412       if (flag_enum)
12413         TYPE_FLAG_ENUM (this_type) = 1;
12414     }
12415
12416   /* If we are reading an enum from a .debug_types unit, and the enum
12417      is a declaration, and the enum is not the signatured type in the
12418      unit, then we do not want to add a symbol for it.  Adding a
12419      symbol would in some cases obscure the true definition of the
12420      enum, giving users an incomplete type when the definition is
12421      actually available.  Note that we do not want to do this for all
12422      enums which are just declarations, because C++0x allows forward
12423      enum declarations.  */
12424   if (cu->per_cu->is_debug_types
12425       && die_is_declaration (die, cu))
12426     {
12427       struct signatured_type *sig_type;
12428
12429       sig_type = (struct signatured_type *) cu->per_cu;
12430       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12431       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12432         return;
12433     }
12434
12435   new_symbol (die, this_type, cu);
12436 }
12437
12438 /* Extract all information from a DW_TAG_array_type DIE and put it in
12439    the DIE's type field.  For now, this only handles one dimensional
12440    arrays.  */
12441
12442 static struct type *
12443 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12444 {
12445   struct objfile *objfile = cu->objfile;
12446   struct die_info *child_die;
12447   struct type *type;
12448   struct type *element_type, *range_type, *index_type;
12449   struct type **range_types = NULL;
12450   struct attribute *attr;
12451   int ndim = 0;
12452   struct cleanup *back_to;
12453   const char *name;
12454
12455   element_type = die_type (die, cu);
12456
12457   /* The die_type call above may have already set the type for this DIE.  */
12458   type = get_die_type (die, cu);
12459   if (type)
12460     return type;
12461
12462   /* Irix 6.2 native cc creates array types without children for
12463      arrays with unspecified length.  */
12464   if (die->child == NULL)
12465     {
12466       index_type = objfile_type (objfile)->builtin_int;
12467       range_type = create_range_type (NULL, index_type, 0, -1);
12468       type = create_array_type (NULL, element_type, range_type);
12469       return set_die_type (die, type, cu);
12470     }
12471
12472   back_to = make_cleanup (null_cleanup, NULL);
12473   child_die = die->child;
12474   while (child_die && child_die->tag)
12475     {
12476       if (child_die->tag == DW_TAG_subrange_type)
12477         {
12478           struct type *child_type = read_type_die (child_die, cu);
12479
12480           if (child_type != NULL)
12481             {
12482               /* The range type was succesfully read.  Save it for the
12483                  array type creation.  */
12484               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12485                 {
12486                   range_types = (struct type **)
12487                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12488                               * sizeof (struct type *));
12489                   if (ndim == 0)
12490                     make_cleanup (free_current_contents, &range_types);
12491                 }
12492               range_types[ndim++] = child_type;
12493             }
12494         }
12495       child_die = sibling_die (child_die);
12496     }
12497
12498   /* Dwarf2 dimensions are output from left to right, create the
12499      necessary array types in backwards order.  */
12500
12501   type = element_type;
12502
12503   if (read_array_order (die, cu) == DW_ORD_col_major)
12504     {
12505       int i = 0;
12506
12507       while (i < ndim)
12508         type = create_array_type (NULL, type, range_types[i++]);
12509     }
12510   else
12511     {
12512       while (ndim-- > 0)
12513         type = create_array_type (NULL, type, range_types[ndim]);
12514     }
12515
12516   /* Understand Dwarf2 support for vector types (like they occur on
12517      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12518      array type.  This is not part of the Dwarf2/3 standard yet, but a
12519      custom vendor extension.  The main difference between a regular
12520      array and the vector variant is that vectors are passed by value
12521      to functions.  */
12522   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12523   if (attr)
12524     make_vector_type (type);
12525
12526   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12527      implementation may choose to implement triple vectors using this
12528      attribute.  */
12529   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12530   if (attr)
12531     {
12532       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12533         TYPE_LENGTH (type) = DW_UNSND (attr);
12534       else
12535         complaint (&symfile_complaints,
12536                    _("DW_AT_byte_size for array type smaller "
12537                      "than the total size of elements"));
12538     }
12539
12540   name = dwarf2_name (die, cu);
12541   if (name)
12542     TYPE_NAME (type) = name;
12543
12544   /* Install the type in the die.  */
12545   set_die_type (die, type, cu);
12546
12547   /* set_die_type should be already done.  */
12548   set_descriptive_type (type, die, cu);
12549
12550   do_cleanups (back_to);
12551
12552   return type;
12553 }
12554
12555 static enum dwarf_array_dim_ordering
12556 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12557 {
12558   struct attribute *attr;
12559
12560   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12561
12562   if (attr) return DW_SND (attr);
12563
12564   /* GNU F77 is a special case, as at 08/2004 array type info is the
12565      opposite order to the dwarf2 specification, but data is still
12566      laid out as per normal fortran.
12567
12568      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12569      version checking.  */
12570
12571   if (cu->language == language_fortran
12572       && cu->producer && strstr (cu->producer, "GNU F77"))
12573     {
12574       return DW_ORD_row_major;
12575     }
12576
12577   switch (cu->language_defn->la_array_ordering)
12578     {
12579     case array_column_major:
12580       return DW_ORD_col_major;
12581     case array_row_major:
12582     default:
12583       return DW_ORD_row_major;
12584     };
12585 }
12586
12587 /* Extract all information from a DW_TAG_set_type DIE and put it in
12588    the DIE's type field.  */
12589
12590 static struct type *
12591 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12592 {
12593   struct type *domain_type, *set_type;
12594   struct attribute *attr;
12595
12596   domain_type = die_type (die, cu);
12597
12598   /* The die_type call above may have already set the type for this DIE.  */
12599   set_type = get_die_type (die, cu);
12600   if (set_type)
12601     return set_type;
12602
12603   set_type = create_set_type (NULL, domain_type);
12604
12605   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12606   if (attr)
12607     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12608
12609   return set_die_type (die, set_type, cu);
12610 }
12611
12612 /* A helper for read_common_block that creates a locexpr baton.
12613    SYM is the symbol which we are marking as computed.
12614    COMMON_DIE is the DIE for the common block.
12615    COMMON_LOC is the location expression attribute for the common
12616    block itself.
12617    MEMBER_LOC is the location expression attribute for the particular
12618    member of the common block that we are processing.
12619    CU is the CU from which the above come.  */
12620
12621 static void
12622 mark_common_block_symbol_computed (struct symbol *sym,
12623                                    struct die_info *common_die,
12624                                    struct attribute *common_loc,
12625                                    struct attribute *member_loc,
12626                                    struct dwarf2_cu *cu)
12627 {
12628   struct objfile *objfile = dwarf2_per_objfile->objfile;
12629   struct dwarf2_locexpr_baton *baton;
12630   gdb_byte *ptr;
12631   unsigned int cu_off;
12632   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12633   LONGEST offset = 0;
12634
12635   gdb_assert (common_loc && member_loc);
12636   gdb_assert (attr_form_is_block (common_loc));
12637   gdb_assert (attr_form_is_block (member_loc)
12638               || attr_form_is_constant (member_loc));
12639
12640   baton = obstack_alloc (&objfile->objfile_obstack,
12641                          sizeof (struct dwarf2_locexpr_baton));
12642   baton->per_cu = cu->per_cu;
12643   gdb_assert (baton->per_cu);
12644
12645   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12646
12647   if (attr_form_is_constant (member_loc))
12648     {
12649       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12650       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12651     }
12652   else
12653     baton->size += DW_BLOCK (member_loc)->size;
12654
12655   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12656   baton->data = ptr;
12657
12658   *ptr++ = DW_OP_call4;
12659   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12660   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12661   ptr += 4;
12662
12663   if (attr_form_is_constant (member_loc))
12664     {
12665       *ptr++ = DW_OP_addr;
12666       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12667       ptr += cu->header.addr_size;
12668     }
12669   else
12670     {
12671       /* We have to copy the data here, because DW_OP_call4 will only
12672          use a DW_AT_location attribute.  */
12673       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12674       ptr += DW_BLOCK (member_loc)->size;
12675     }
12676
12677   *ptr++ = DW_OP_plus;
12678   gdb_assert (ptr - baton->data == baton->size);
12679
12680   SYMBOL_LOCATION_BATON (sym) = baton;
12681   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12682 }
12683
12684 /* Create appropriate locally-scoped variables for all the
12685    DW_TAG_common_block entries.  Also create a struct common_block
12686    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12687    is used to sepate the common blocks name namespace from regular
12688    variable names.  */
12689
12690 static void
12691 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12692 {
12693   struct attribute *attr;
12694
12695   attr = dwarf2_attr (die, DW_AT_location, cu);
12696   if (attr)
12697     {
12698       /* Support the .debug_loc offsets.  */
12699       if (attr_form_is_block (attr))
12700         {
12701           /* Ok.  */
12702         }
12703       else if (attr_form_is_section_offset (attr))
12704         {
12705           dwarf2_complex_location_expr_complaint ();
12706           attr = NULL;
12707         }
12708       else
12709         {
12710           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12711                                                  "common block member");
12712           attr = NULL;
12713         }
12714     }
12715
12716   if (die->child != NULL)
12717     {
12718       struct objfile *objfile = cu->objfile;
12719       struct die_info *child_die;
12720       size_t n_entries = 0, size;
12721       struct common_block *common_block;
12722       struct symbol *sym;
12723
12724       for (child_die = die->child;
12725            child_die && child_die->tag;
12726            child_die = sibling_die (child_die))
12727         ++n_entries;
12728
12729       size = (sizeof (struct common_block)
12730               + (n_entries - 1) * sizeof (struct symbol *));
12731       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12732       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12733       common_block->n_entries = 0;
12734
12735       for (child_die = die->child;
12736            child_die && child_die->tag;
12737            child_die = sibling_die (child_die))
12738         {
12739           /* Create the symbol in the DW_TAG_common_block block in the current
12740              symbol scope.  */
12741           sym = new_symbol (child_die, NULL, cu);
12742           if (sym != NULL)
12743             {
12744               struct attribute *member_loc;
12745
12746               common_block->contents[common_block->n_entries++] = sym;
12747
12748               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12749                                         cu);
12750               if (member_loc)
12751                 {
12752                   /* GDB has handled this for a long time, but it is
12753                      not specified by DWARF.  It seems to have been
12754                      emitted by gfortran at least as recently as:
12755                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12756                   complaint (&symfile_complaints,
12757                              _("Variable in common block has "
12758                                "DW_AT_data_member_location "
12759                                "- DIE at 0x%x [in module %s]"),
12760                              child_die->offset.sect_off,
12761                              objfile_name (cu->objfile));
12762
12763                   if (attr_form_is_section_offset (member_loc))
12764                     dwarf2_complex_location_expr_complaint ();
12765                   else if (attr_form_is_constant (member_loc)
12766                            || attr_form_is_block (member_loc))
12767                     {
12768                       if (attr)
12769                         mark_common_block_symbol_computed (sym, die, attr,
12770                                                            member_loc, cu);
12771                     }
12772                   else
12773                     dwarf2_complex_location_expr_complaint ();
12774                 }
12775             }
12776         }
12777
12778       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12779       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12780     }
12781 }
12782
12783 /* Create a type for a C++ namespace.  */
12784
12785 static struct type *
12786 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12787 {
12788   struct objfile *objfile = cu->objfile;
12789   const char *previous_prefix, *name;
12790   int is_anonymous;
12791   struct type *type;
12792
12793   /* For extensions, reuse the type of the original namespace.  */
12794   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12795     {
12796       struct die_info *ext_die;
12797       struct dwarf2_cu *ext_cu = cu;
12798
12799       ext_die = dwarf2_extension (die, &ext_cu);
12800       type = read_type_die (ext_die, ext_cu);
12801
12802       /* EXT_CU may not be the same as CU.
12803          Ensure TYPE is recorded with CU in die_type_hash.  */
12804       return set_die_type (die, type, cu);
12805     }
12806
12807   name = namespace_name (die, &is_anonymous, cu);
12808
12809   /* Now build the name of the current namespace.  */
12810
12811   previous_prefix = determine_prefix (die, cu);
12812   if (previous_prefix[0] != '\0')
12813     name = typename_concat (&objfile->objfile_obstack,
12814                             previous_prefix, name, 0, cu);
12815
12816   /* Create the type.  */
12817   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12818                     objfile);
12819   TYPE_NAME (type) = name;
12820   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12821
12822   return set_die_type (die, type, cu);
12823 }
12824
12825 /* Read a C++ namespace.  */
12826
12827 static void
12828 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12829 {
12830   struct objfile *objfile = cu->objfile;
12831   int is_anonymous;
12832
12833   /* Add a symbol associated to this if we haven't seen the namespace
12834      before.  Also, add a using directive if it's an anonymous
12835      namespace.  */
12836
12837   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12838     {
12839       struct type *type;
12840
12841       type = read_type_die (die, cu);
12842       new_symbol (die, type, cu);
12843
12844       namespace_name (die, &is_anonymous, cu);
12845       if (is_anonymous)
12846         {
12847           const char *previous_prefix = determine_prefix (die, cu);
12848
12849           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12850                                   NULL, NULL, 0, &objfile->objfile_obstack);
12851         }
12852     }
12853
12854   if (die->child != NULL)
12855     {
12856       struct die_info *child_die = die->child;
12857
12858       while (child_die && child_die->tag)
12859         {
12860           process_die (child_die, cu);
12861           child_die = sibling_die (child_die);
12862         }
12863     }
12864 }
12865
12866 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12867    imported module.  Still we need that type as local Fortran "use ... only"
12868    declaration imports depend on the created type in determine_prefix.  */
12869
12870 static struct type *
12871 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12872 {
12873   struct objfile *objfile = cu->objfile;
12874   const char *module_name;
12875   struct type *type;
12876
12877   module_name = dwarf2_name (die, cu);
12878   if (!module_name)
12879     complaint (&symfile_complaints,
12880                _("DW_TAG_module has no name, offset 0x%x"),
12881                die->offset.sect_off);
12882   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12883
12884   /* determine_prefix uses TYPE_TAG_NAME.  */
12885   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12886
12887   return set_die_type (die, type, cu);
12888 }
12889
12890 /* Read a Fortran module.  */
12891
12892 static void
12893 read_module (struct die_info *die, struct dwarf2_cu *cu)
12894 {
12895   struct die_info *child_die = die->child;
12896
12897   while (child_die && child_die->tag)
12898     {
12899       process_die (child_die, cu);
12900       child_die = sibling_die (child_die);
12901     }
12902 }
12903
12904 /* Return the name of the namespace represented by DIE.  Set
12905    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12906    namespace.  */
12907
12908 static const char *
12909 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12910 {
12911   struct die_info *current_die;
12912   const char *name = NULL;
12913
12914   /* Loop through the extensions until we find a name.  */
12915
12916   for (current_die = die;
12917        current_die != NULL;
12918        current_die = dwarf2_extension (die, &cu))
12919     {
12920       name = dwarf2_name (current_die, cu);
12921       if (name != NULL)
12922         break;
12923     }
12924
12925   /* Is it an anonymous namespace?  */
12926
12927   *is_anonymous = (name == NULL);
12928   if (*is_anonymous)
12929     name = CP_ANONYMOUS_NAMESPACE_STR;
12930
12931   return name;
12932 }
12933
12934 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12935    the user defined type vector.  */
12936
12937 static struct type *
12938 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12939 {
12940   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12941   struct comp_unit_head *cu_header = &cu->header;
12942   struct type *type;
12943   struct attribute *attr_byte_size;
12944   struct attribute *attr_address_class;
12945   int byte_size, addr_class;
12946   struct type *target_type;
12947
12948   target_type = die_type (die, cu);
12949
12950   /* The die_type call above may have already set the type for this DIE.  */
12951   type = get_die_type (die, cu);
12952   if (type)
12953     return type;
12954
12955   type = lookup_pointer_type (target_type);
12956
12957   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12958   if (attr_byte_size)
12959     byte_size = DW_UNSND (attr_byte_size);
12960   else
12961     byte_size = cu_header->addr_size;
12962
12963   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12964   if (attr_address_class)
12965     addr_class = DW_UNSND (attr_address_class);
12966   else
12967     addr_class = DW_ADDR_none;
12968
12969   /* If the pointer size or address class is different than the
12970      default, create a type variant marked as such and set the
12971      length accordingly.  */
12972   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12973     {
12974       if (gdbarch_address_class_type_flags_p (gdbarch))
12975         {
12976           int type_flags;
12977
12978           type_flags = gdbarch_address_class_type_flags
12979                          (gdbarch, byte_size, addr_class);
12980           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12981                       == 0);
12982           type = make_type_with_address_space (type, type_flags);
12983         }
12984       else if (TYPE_LENGTH (type) != byte_size)
12985         {
12986           complaint (&symfile_complaints,
12987                      _("invalid pointer size %d"), byte_size);
12988         }
12989       else
12990         {
12991           /* Should we also complain about unhandled address classes?  */
12992         }
12993     }
12994
12995   TYPE_LENGTH (type) = byte_size;
12996   return set_die_type (die, type, cu);
12997 }
12998
12999 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
13000    the user defined type vector.  */
13001
13002 static struct type *
13003 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
13004 {
13005   struct type *type;
13006   struct type *to_type;
13007   struct type *domain;
13008
13009   to_type = die_type (die, cu);
13010   domain = die_containing_type (die, cu);
13011
13012   /* The calls above may have already set the type for this DIE.  */
13013   type = get_die_type (die, cu);
13014   if (type)
13015     return type;
13016
13017   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
13018     type = lookup_methodptr_type (to_type);
13019   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
13020     {
13021       struct type *new_type = alloc_type (cu->objfile);
13022
13023       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
13024                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
13025                             TYPE_VARARGS (to_type));
13026       type = lookup_methodptr_type (new_type);
13027     }
13028   else
13029     type = lookup_memberptr_type (to_type, domain);
13030
13031   return set_die_type (die, type, cu);
13032 }
13033
13034 /* Extract all information from a DW_TAG_reference_type DIE and add to
13035    the user defined type vector.  */
13036
13037 static struct type *
13038 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
13039 {
13040   struct comp_unit_head *cu_header = &cu->header;
13041   struct type *type, *target_type;
13042   struct attribute *attr;
13043
13044   target_type = die_type (die, cu);
13045
13046   /* The die_type call above may have already set the type for this DIE.  */
13047   type = get_die_type (die, cu);
13048   if (type)
13049     return type;
13050
13051   type = lookup_reference_type (target_type);
13052   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13053   if (attr)
13054     {
13055       TYPE_LENGTH (type) = DW_UNSND (attr);
13056     }
13057   else
13058     {
13059       TYPE_LENGTH (type) = cu_header->addr_size;
13060     }
13061   return set_die_type (die, type, cu);
13062 }
13063
13064 static struct type *
13065 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
13066 {
13067   struct type *base_type, *cv_type;
13068
13069   base_type = die_type (die, cu);
13070
13071   /* The die_type call above may have already set the type for this DIE.  */
13072   cv_type = get_die_type (die, cu);
13073   if (cv_type)
13074     return cv_type;
13075
13076   /* In case the const qualifier is applied to an array type, the element type
13077      is so qualified, not the array type (section 6.7.3 of C99).  */
13078   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
13079     {
13080       struct type *el_type, *inner_array;
13081
13082       base_type = copy_type (base_type);
13083       inner_array = base_type;
13084
13085       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
13086         {
13087           TYPE_TARGET_TYPE (inner_array) =
13088             copy_type (TYPE_TARGET_TYPE (inner_array));
13089           inner_array = TYPE_TARGET_TYPE (inner_array);
13090         }
13091
13092       el_type = TYPE_TARGET_TYPE (inner_array);
13093       TYPE_TARGET_TYPE (inner_array) =
13094         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
13095
13096       return set_die_type (die, base_type, cu);
13097     }
13098
13099   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13100   return set_die_type (die, cv_type, cu);
13101 }
13102
13103 static struct type *
13104 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13105 {
13106   struct type *base_type, *cv_type;
13107
13108   base_type = die_type (die, cu);
13109
13110   /* The die_type call above may have already set the type for this DIE.  */
13111   cv_type = get_die_type (die, cu);
13112   if (cv_type)
13113     return cv_type;
13114
13115   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13116   return set_die_type (die, cv_type, cu);
13117 }
13118
13119 /* Handle DW_TAG_restrict_type.  */
13120
13121 static struct type *
13122 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13123 {
13124   struct type *base_type, *cv_type;
13125
13126   base_type = die_type (die, cu);
13127
13128   /* The die_type call above may have already set the type for this DIE.  */
13129   cv_type = get_die_type (die, cu);
13130   if (cv_type)
13131     return cv_type;
13132
13133   cv_type = make_restrict_type (base_type);
13134   return set_die_type (die, cv_type, cu);
13135 }
13136
13137 /* Extract all information from a DW_TAG_string_type DIE and add to
13138    the user defined type vector.  It isn't really a user defined type,
13139    but it behaves like one, with other DIE's using an AT_user_def_type
13140    attribute to reference it.  */
13141
13142 static struct type *
13143 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13144 {
13145   struct objfile *objfile = cu->objfile;
13146   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13147   struct type *type, *range_type, *index_type, *char_type;
13148   struct attribute *attr;
13149   unsigned int length;
13150
13151   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13152   if (attr)
13153     {
13154       length = DW_UNSND (attr);
13155     }
13156   else
13157     {
13158       /* Check for the DW_AT_byte_size attribute.  */
13159       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13160       if (attr)
13161         {
13162           length = DW_UNSND (attr);
13163         }
13164       else
13165         {
13166           length = 1;
13167         }
13168     }
13169
13170   index_type = objfile_type (objfile)->builtin_int;
13171   range_type = create_range_type (NULL, index_type, 1, length);
13172   char_type = language_string_char_type (cu->language_defn, gdbarch);
13173   type = create_string_type (NULL, char_type, range_type);
13174
13175   return set_die_type (die, type, cu);
13176 }
13177
13178 /* Assuming that DIE corresponds to a function, returns nonzero
13179    if the function is prototyped.  */
13180
13181 static int
13182 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13183 {
13184   struct attribute *attr;
13185
13186   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13187   if (attr && (DW_UNSND (attr) != 0))
13188     return 1;
13189
13190   /* The DWARF standard implies that the DW_AT_prototyped attribute
13191      is only meaninful for C, but the concept also extends to other
13192      languages that allow unprototyped functions (Eg: Objective C).
13193      For all other languages, assume that functions are always
13194      prototyped.  */
13195   if (cu->language != language_c
13196       && cu->language != language_objc
13197       && cu->language != language_opencl)
13198     return 1;
13199
13200   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13201      prototyped and unprototyped functions; default to prototyped,
13202      since that is more common in modern code (and RealView warns
13203      about unprototyped functions).  */
13204   if (producer_is_realview (cu->producer))
13205     return 1;
13206
13207   return 0;
13208 }
13209
13210 /* Handle DIES due to C code like:
13211
13212    struct foo
13213    {
13214    int (*funcp)(int a, long l);
13215    int b;
13216    };
13217
13218    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13219
13220 static struct type *
13221 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13222 {
13223   struct objfile *objfile = cu->objfile;
13224   struct type *type;            /* Type that this function returns.  */
13225   struct type *ftype;           /* Function that returns above type.  */
13226   struct attribute *attr;
13227
13228   type = die_type (die, cu);
13229
13230   /* The die_type call above may have already set the type for this DIE.  */
13231   ftype = get_die_type (die, cu);
13232   if (ftype)
13233     return ftype;
13234
13235   ftype = lookup_function_type (type);
13236
13237   if (prototyped_function_p (die, cu))
13238     TYPE_PROTOTYPED (ftype) = 1;
13239
13240   /* Store the calling convention in the type if it's available in
13241      the subroutine die.  Otherwise set the calling convention to
13242      the default value DW_CC_normal.  */
13243   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13244   if (attr)
13245     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13246   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13247     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13248   else
13249     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13250
13251   /* We need to add the subroutine type to the die immediately so
13252      we don't infinitely recurse when dealing with parameters
13253      declared as the same subroutine type.  */
13254   set_die_type (die, ftype, cu);
13255
13256   if (die->child != NULL)
13257     {
13258       struct type *void_type = objfile_type (objfile)->builtin_void;
13259       struct die_info *child_die;
13260       int nparams, iparams;
13261
13262       /* Count the number of parameters.
13263          FIXME: GDB currently ignores vararg functions, but knows about
13264          vararg member functions.  */
13265       nparams = 0;
13266       child_die = die->child;
13267       while (child_die && child_die->tag)
13268         {
13269           if (child_die->tag == DW_TAG_formal_parameter)
13270             nparams++;
13271           else if (child_die->tag == DW_TAG_unspecified_parameters)
13272             TYPE_VARARGS (ftype) = 1;
13273           child_die = sibling_die (child_die);
13274         }
13275
13276       /* Allocate storage for parameters and fill them in.  */
13277       TYPE_NFIELDS (ftype) = nparams;
13278       TYPE_FIELDS (ftype) = (struct field *)
13279         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13280
13281       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13282          even if we error out during the parameters reading below.  */
13283       for (iparams = 0; iparams < nparams; iparams++)
13284         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13285
13286       iparams = 0;
13287       child_die = die->child;
13288       while (child_die && child_die->tag)
13289         {
13290           if (child_die->tag == DW_TAG_formal_parameter)
13291             {
13292               struct type *arg_type;
13293
13294               /* DWARF version 2 has no clean way to discern C++
13295                  static and non-static member functions.  G++ helps
13296                  GDB by marking the first parameter for non-static
13297                  member functions (which is the this pointer) as
13298                  artificial.  We pass this information to
13299                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13300
13301                  DWARF version 3 added DW_AT_object_pointer, which GCC
13302                  4.5 does not yet generate.  */
13303               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13304               if (attr)
13305                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13306               else
13307                 {
13308                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13309
13310                   /* GCC/43521: In java, the formal parameter
13311                      "this" is sometimes not marked with DW_AT_artificial.  */
13312                   if (cu->language == language_java)
13313                     {
13314                       const char *name = dwarf2_name (child_die, cu);
13315
13316                       if (name && !strcmp (name, "this"))
13317                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13318                     }
13319                 }
13320               arg_type = die_type (child_die, cu);
13321
13322               /* RealView does not mark THIS as const, which the testsuite
13323                  expects.  GCC marks THIS as const in method definitions,
13324                  but not in the class specifications (GCC PR 43053).  */
13325               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13326                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13327                 {
13328                   int is_this = 0;
13329                   struct dwarf2_cu *arg_cu = cu;
13330                   const char *name = dwarf2_name (child_die, cu);
13331
13332                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13333                   if (attr)
13334                     {
13335                       /* If the compiler emits this, use it.  */
13336                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13337                         is_this = 1;
13338                     }
13339                   else if (name && strcmp (name, "this") == 0)
13340                     /* Function definitions will have the argument names.  */
13341                     is_this = 1;
13342                   else if (name == NULL && iparams == 0)
13343                     /* Declarations may not have the names, so like
13344                        elsewhere in GDB, assume an artificial first
13345                        argument is "this".  */
13346                     is_this = 1;
13347
13348                   if (is_this)
13349                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13350                                              arg_type, 0);
13351                 }
13352
13353               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13354               iparams++;
13355             }
13356           child_die = sibling_die (child_die);
13357         }
13358     }
13359
13360   return ftype;
13361 }
13362
13363 static struct type *
13364 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13365 {
13366   struct objfile *objfile = cu->objfile;
13367   const char *name = NULL;
13368   struct type *this_type, *target_type;
13369
13370   name = dwarf2_full_name (NULL, die, cu);
13371   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13372                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13373   TYPE_NAME (this_type) = name;
13374   set_die_type (die, this_type, cu);
13375   target_type = die_type (die, cu);
13376   if (target_type != this_type)
13377     TYPE_TARGET_TYPE (this_type) = target_type;
13378   else
13379     {
13380       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13381          spec and cause infinite loops in GDB.  */
13382       complaint (&symfile_complaints,
13383                  _("Self-referential DW_TAG_typedef "
13384                    "- DIE at 0x%x [in module %s]"),
13385                  die->offset.sect_off, objfile_name (objfile));
13386       TYPE_TARGET_TYPE (this_type) = NULL;
13387     }
13388   return this_type;
13389 }
13390
13391 /* Find a representation of a given base type and install
13392    it in the TYPE field of the die.  */
13393
13394 static struct type *
13395 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13396 {
13397   struct objfile *objfile = cu->objfile;
13398   struct type *type;
13399   struct attribute *attr;
13400   int encoding = 0, size = 0;
13401   const char *name;
13402   enum type_code code = TYPE_CODE_INT;
13403   int type_flags = 0;
13404   struct type *target_type = NULL;
13405
13406   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13407   if (attr)
13408     {
13409       encoding = DW_UNSND (attr);
13410     }
13411   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13412   if (attr)
13413     {
13414       size = DW_UNSND (attr);
13415     }
13416   name = dwarf2_name (die, cu);
13417   if (!name)
13418     {
13419       complaint (&symfile_complaints,
13420                  _("DW_AT_name missing from DW_TAG_base_type"));
13421     }
13422
13423   switch (encoding)
13424     {
13425       case DW_ATE_address:
13426         /* Turn DW_ATE_address into a void * pointer.  */
13427         code = TYPE_CODE_PTR;
13428         type_flags |= TYPE_FLAG_UNSIGNED;
13429         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13430         break;
13431       case DW_ATE_boolean:
13432         code = TYPE_CODE_BOOL;
13433         type_flags |= TYPE_FLAG_UNSIGNED;
13434         break;
13435       case DW_ATE_complex_float:
13436         code = TYPE_CODE_COMPLEX;
13437         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13438         break;
13439       case DW_ATE_decimal_float:
13440         code = TYPE_CODE_DECFLOAT;
13441         break;
13442       case DW_ATE_float:
13443         code = TYPE_CODE_FLT;
13444         break;
13445       case DW_ATE_signed:
13446         break;
13447       case DW_ATE_unsigned:
13448         type_flags |= TYPE_FLAG_UNSIGNED;
13449         if (cu->language == language_fortran
13450             && name
13451             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13452           code = TYPE_CODE_CHAR;
13453         break;
13454       case DW_ATE_signed_char:
13455         if (cu->language == language_ada || cu->language == language_m2
13456             || cu->language == language_pascal
13457             || cu->language == language_fortran)
13458           code = TYPE_CODE_CHAR;
13459         break;
13460       case DW_ATE_unsigned_char:
13461         if (cu->language == language_ada || cu->language == language_m2
13462             || cu->language == language_pascal
13463             || cu->language == language_fortran)
13464           code = TYPE_CODE_CHAR;
13465         type_flags |= TYPE_FLAG_UNSIGNED;
13466         break;
13467       case DW_ATE_UTF:
13468         /* We just treat this as an integer and then recognize the
13469            type by name elsewhere.  */
13470         break;
13471
13472       default:
13473         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13474                    dwarf_type_encoding_name (encoding));
13475         break;
13476     }
13477
13478   type = init_type (code, size, type_flags, NULL, objfile);
13479   TYPE_NAME (type) = name;
13480   TYPE_TARGET_TYPE (type) = target_type;
13481
13482   if (name && strcmp (name, "char") == 0)
13483     TYPE_NOSIGN (type) = 1;
13484
13485   return set_die_type (die, type, cu);
13486 }
13487
13488 /* Read the given DW_AT_subrange DIE.  */
13489
13490 static struct type *
13491 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13492 {
13493   struct type *base_type, *orig_base_type;
13494   struct type *range_type;
13495   struct attribute *attr;
13496   LONGEST low, high;
13497   int low_default_is_valid;
13498   const char *name;
13499   LONGEST negative_mask;
13500
13501   orig_base_type = die_type (die, cu);
13502   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13503      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13504      creating the range type, but we use the result of check_typedef
13505      when examining properties of the type.  */
13506   base_type = check_typedef (orig_base_type);
13507
13508   /* The die_type call above may have already set the type for this DIE.  */
13509   range_type = get_die_type (die, cu);
13510   if (range_type)
13511     return range_type;
13512
13513   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13514      omitting DW_AT_lower_bound.  */
13515   switch (cu->language)
13516     {
13517     case language_c:
13518     case language_cplus:
13519       low = 0;
13520       low_default_is_valid = 1;
13521       break;
13522     case language_fortran:
13523       low = 1;
13524       low_default_is_valid = 1;
13525       break;
13526     case language_d:
13527     case language_java:
13528     case language_objc:
13529       low = 0;
13530       low_default_is_valid = (cu->header.version >= 4);
13531       break;
13532     case language_ada:
13533     case language_m2:
13534     case language_pascal:
13535       low = 1;
13536       low_default_is_valid = (cu->header.version >= 4);
13537       break;
13538     default:
13539       low = 0;
13540       low_default_is_valid = 0;
13541       break;
13542     }
13543
13544   /* FIXME: For variable sized arrays either of these could be
13545      a variable rather than a constant value.  We'll allow it,
13546      but we don't know how to handle it.  */
13547   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13548   if (attr)
13549     low = dwarf2_get_attr_constant_value (attr, low);
13550   else if (!low_default_is_valid)
13551     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13552                                       "- DIE at 0x%x [in module %s]"),
13553                die->offset.sect_off, objfile_name (cu->objfile));
13554
13555   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13556   if (attr)
13557     {
13558       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
13559         {
13560           /* GCC encodes arrays with unspecified or dynamic length
13561              with a DW_FORM_block1 attribute or a reference attribute.
13562              FIXME: GDB does not yet know how to handle dynamic
13563              arrays properly, treat them as arrays with unspecified
13564              length for now.
13565
13566              FIXME: jimb/2003-09-22: GDB does not really know
13567              how to handle arrays of unspecified length
13568              either; we just represent them as zero-length
13569              arrays.  Choose an appropriate upper bound given
13570              the lower bound we've computed above.  */
13571           high = low - 1;
13572         }
13573       else
13574         high = dwarf2_get_attr_constant_value (attr, 1);
13575     }
13576   else
13577     {
13578       attr = dwarf2_attr (die, DW_AT_count, cu);
13579       if (attr)
13580         {
13581           int count = dwarf2_get_attr_constant_value (attr, 1);
13582           high = low + count - 1;
13583         }
13584       else
13585         {
13586           /* Unspecified array length.  */
13587           high = low - 1;
13588         }
13589     }
13590
13591   /* Dwarf-2 specifications explicitly allows to create subrange types
13592      without specifying a base type.
13593      In that case, the base type must be set to the type of
13594      the lower bound, upper bound or count, in that order, if any of these
13595      three attributes references an object that has a type.
13596      If no base type is found, the Dwarf-2 specifications say that
13597      a signed integer type of size equal to the size of an address should
13598      be used.
13599      For the following C code: `extern char gdb_int [];'
13600      GCC produces an empty range DIE.
13601      FIXME: muller/2010-05-28: Possible references to object for low bound,
13602      high bound or count are not yet handled by this code.  */
13603   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13604     {
13605       struct objfile *objfile = cu->objfile;
13606       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13607       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13608       struct type *int_type = objfile_type (objfile)->builtin_int;
13609
13610       /* Test "int", "long int", and "long long int" objfile types,
13611          and select the first one having a size above or equal to the
13612          architecture address size.  */
13613       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13614         base_type = int_type;
13615       else
13616         {
13617           int_type = objfile_type (objfile)->builtin_long;
13618           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13619             base_type = int_type;
13620           else
13621             {
13622               int_type = objfile_type (objfile)->builtin_long_long;
13623               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13624                 base_type = int_type;
13625             }
13626         }
13627     }
13628
13629   negative_mask =
13630     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13631   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13632     low |= negative_mask;
13633   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13634     high |= negative_mask;
13635
13636   range_type = create_range_type (NULL, orig_base_type, low, high);
13637
13638   /* Mark arrays with dynamic length at least as an array of unspecified
13639      length.  GDB could check the boundary but before it gets implemented at
13640      least allow accessing the array elements.  */
13641   if (attr && attr_form_is_block (attr))
13642     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13643
13644   /* Ada expects an empty array on no boundary attributes.  */
13645   if (attr == NULL && cu->language != language_ada)
13646     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13647
13648   name = dwarf2_name (die, cu);
13649   if (name)
13650     TYPE_NAME (range_type) = name;
13651
13652   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13653   if (attr)
13654     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13655
13656   set_die_type (die, range_type, cu);
13657
13658   /* set_die_type should be already done.  */
13659   set_descriptive_type (range_type, die, cu);
13660
13661   return range_type;
13662 }
13663
13664 static struct type *
13665 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13666 {
13667   struct type *type;
13668
13669   /* For now, we only support the C meaning of an unspecified type: void.  */
13670
13671   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13672   TYPE_NAME (type) = dwarf2_name (die, cu);
13673
13674   return set_die_type (die, type, cu);
13675 }
13676
13677 /* Read a single die and all its descendents.  Set the die's sibling
13678    field to NULL; set other fields in the die correctly, and set all
13679    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13680    location of the info_ptr after reading all of those dies.  PARENT
13681    is the parent of the die in question.  */
13682
13683 static struct die_info *
13684 read_die_and_children (const struct die_reader_specs *reader,
13685                        const gdb_byte *info_ptr,
13686                        const gdb_byte **new_info_ptr,
13687                        struct die_info *parent)
13688 {
13689   struct die_info *die;
13690   const gdb_byte *cur_ptr;
13691   int has_children;
13692
13693   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13694   if (die == NULL)
13695     {
13696       *new_info_ptr = cur_ptr;
13697       return NULL;
13698     }
13699   store_in_ref_table (die, reader->cu);
13700
13701   if (has_children)
13702     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13703   else
13704     {
13705       die->child = NULL;
13706       *new_info_ptr = cur_ptr;
13707     }
13708
13709   die->sibling = NULL;
13710   die->parent = parent;
13711   return die;
13712 }
13713
13714 /* Read a die, all of its descendents, and all of its siblings; set
13715    all of the fields of all of the dies correctly.  Arguments are as
13716    in read_die_and_children.  */
13717
13718 static struct die_info *
13719 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13720                          const gdb_byte *info_ptr,
13721                          const gdb_byte **new_info_ptr,
13722                          struct die_info *parent)
13723 {
13724   struct die_info *first_die, *last_sibling;
13725   const gdb_byte *cur_ptr;
13726
13727   cur_ptr = info_ptr;
13728   first_die = last_sibling = NULL;
13729
13730   while (1)
13731     {
13732       struct die_info *die
13733         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13734
13735       if (die == NULL)
13736         {
13737           *new_info_ptr = cur_ptr;
13738           return first_die;
13739         }
13740
13741       if (!first_die)
13742         first_die = die;
13743       else
13744         last_sibling->sibling = die;
13745
13746       last_sibling = die;
13747     }
13748 }
13749
13750 /* Read a die, all of its descendents, and all of its siblings; set
13751    all of the fields of all of the dies correctly.  Arguments are as
13752    in read_die_and_children.
13753    This the main entry point for reading a DIE and all its children.  */
13754
13755 static struct die_info *
13756 read_die_and_siblings (const struct die_reader_specs *reader,
13757                        const gdb_byte *info_ptr,
13758                        const gdb_byte **new_info_ptr,
13759                        struct die_info *parent)
13760 {
13761   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13762                                                   new_info_ptr, parent);
13763
13764   if (dwarf2_die_debug)
13765     {
13766       fprintf_unfiltered (gdb_stdlog,
13767                           "Read die from %s@0x%x of %s:\n",
13768                           get_section_name (reader->die_section),
13769                           (unsigned) (info_ptr - reader->die_section->buffer),
13770                           bfd_get_filename (reader->abfd));
13771       dump_die (die, dwarf2_die_debug);
13772     }
13773
13774   return die;
13775 }
13776
13777 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13778    attributes.
13779    The caller is responsible for filling in the extra attributes
13780    and updating (*DIEP)->num_attrs.
13781    Set DIEP to point to a newly allocated die with its information,
13782    except for its child, sibling, and parent fields.
13783    Set HAS_CHILDREN to tell whether the die has children or not.  */
13784
13785 static const gdb_byte *
13786 read_full_die_1 (const struct die_reader_specs *reader,
13787                  struct die_info **diep, const gdb_byte *info_ptr,
13788                  int *has_children, int num_extra_attrs)
13789 {
13790   unsigned int abbrev_number, bytes_read, i;
13791   sect_offset offset;
13792   struct abbrev_info *abbrev;
13793   struct die_info *die;
13794   struct dwarf2_cu *cu = reader->cu;
13795   bfd *abfd = reader->abfd;
13796
13797   offset.sect_off = info_ptr - reader->buffer;
13798   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13799   info_ptr += bytes_read;
13800   if (!abbrev_number)
13801     {
13802       *diep = NULL;
13803       *has_children = 0;
13804       return info_ptr;
13805     }
13806
13807   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13808   if (!abbrev)
13809     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13810            abbrev_number,
13811            bfd_get_filename (abfd));
13812
13813   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13814   die->offset = offset;
13815   die->tag = abbrev->tag;
13816   die->abbrev = abbrev_number;
13817
13818   /* Make the result usable.
13819      The caller needs to update num_attrs after adding the extra
13820      attributes.  */
13821   die->num_attrs = abbrev->num_attrs;
13822
13823   for (i = 0; i < abbrev->num_attrs; ++i)
13824     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13825                                info_ptr);
13826
13827   *diep = die;
13828   *has_children = abbrev->has_children;
13829   return info_ptr;
13830 }
13831
13832 /* Read a die and all its attributes.
13833    Set DIEP to point to a newly allocated die with its information,
13834    except for its child, sibling, and parent fields.
13835    Set HAS_CHILDREN to tell whether the die has children or not.  */
13836
13837 static const gdb_byte *
13838 read_full_die (const struct die_reader_specs *reader,
13839                struct die_info **diep, const gdb_byte *info_ptr,
13840                int *has_children)
13841 {
13842   const gdb_byte *result;
13843
13844   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13845
13846   if (dwarf2_die_debug)
13847     {
13848       fprintf_unfiltered (gdb_stdlog,
13849                           "Read die from %s@0x%x of %s:\n",
13850                           get_section_name (reader->die_section),
13851                           (unsigned) (info_ptr - reader->die_section->buffer),
13852                           bfd_get_filename (reader->abfd));
13853       dump_die (*diep, dwarf2_die_debug);
13854     }
13855
13856   return result;
13857 }
13858 \f
13859 /* Abbreviation tables.
13860
13861    In DWARF version 2, the description of the debugging information is
13862    stored in a separate .debug_abbrev section.  Before we read any
13863    dies from a section we read in all abbreviations and install them
13864    in a hash table.  */
13865
13866 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13867
13868 static struct abbrev_info *
13869 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13870 {
13871   struct abbrev_info *abbrev;
13872
13873   abbrev = (struct abbrev_info *)
13874     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13875   memset (abbrev, 0, sizeof (struct abbrev_info));
13876   return abbrev;
13877 }
13878
13879 /* Add an abbreviation to the table.  */
13880
13881 static void
13882 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13883                          unsigned int abbrev_number,
13884                          struct abbrev_info *abbrev)
13885 {
13886   unsigned int hash_number;
13887
13888   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13889   abbrev->next = abbrev_table->abbrevs[hash_number];
13890   abbrev_table->abbrevs[hash_number] = abbrev;
13891 }
13892
13893 /* Look up an abbrev in the table.
13894    Returns NULL if the abbrev is not found.  */
13895
13896 static struct abbrev_info *
13897 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13898                             unsigned int abbrev_number)
13899 {
13900   unsigned int hash_number;
13901   struct abbrev_info *abbrev;
13902
13903   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13904   abbrev = abbrev_table->abbrevs[hash_number];
13905
13906   while (abbrev)
13907     {
13908       if (abbrev->number == abbrev_number)
13909         return abbrev;
13910       abbrev = abbrev->next;
13911     }
13912   return NULL;
13913 }
13914
13915 /* Read in an abbrev table.  */
13916
13917 static struct abbrev_table *
13918 abbrev_table_read_table (struct dwarf2_section_info *section,
13919                          sect_offset offset)
13920 {
13921   struct objfile *objfile = dwarf2_per_objfile->objfile;
13922   bfd *abfd = get_section_bfd_owner (section);
13923   struct abbrev_table *abbrev_table;
13924   const gdb_byte *abbrev_ptr;
13925   struct abbrev_info *cur_abbrev;
13926   unsigned int abbrev_number, bytes_read, abbrev_name;
13927   unsigned int abbrev_form;
13928   struct attr_abbrev *cur_attrs;
13929   unsigned int allocated_attrs;
13930
13931   abbrev_table = XMALLOC (struct abbrev_table);
13932   abbrev_table->offset = offset;
13933   obstack_init (&abbrev_table->abbrev_obstack);
13934   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13935                                          (ABBREV_HASH_SIZE
13936                                           * sizeof (struct abbrev_info *)));
13937   memset (abbrev_table->abbrevs, 0,
13938           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13939
13940   dwarf2_read_section (objfile, section);
13941   abbrev_ptr = section->buffer + offset.sect_off;
13942   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13943   abbrev_ptr += bytes_read;
13944
13945   allocated_attrs = ATTR_ALLOC_CHUNK;
13946   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13947
13948   /* Loop until we reach an abbrev number of 0.  */
13949   while (abbrev_number)
13950     {
13951       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13952
13953       /* read in abbrev header */
13954       cur_abbrev->number = abbrev_number;
13955       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13956       abbrev_ptr += bytes_read;
13957       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13958       abbrev_ptr += 1;
13959
13960       /* now read in declarations */
13961       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13962       abbrev_ptr += bytes_read;
13963       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13964       abbrev_ptr += bytes_read;
13965       while (abbrev_name)
13966         {
13967           if (cur_abbrev->num_attrs == allocated_attrs)
13968             {
13969               allocated_attrs += ATTR_ALLOC_CHUNK;
13970               cur_attrs
13971                 = xrealloc (cur_attrs, (allocated_attrs
13972                                         * sizeof (struct attr_abbrev)));
13973             }
13974
13975           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13976           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13977           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13978           abbrev_ptr += bytes_read;
13979           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13980           abbrev_ptr += bytes_read;
13981         }
13982
13983       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13984                                          (cur_abbrev->num_attrs
13985                                           * sizeof (struct attr_abbrev)));
13986       memcpy (cur_abbrev->attrs, cur_attrs,
13987               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13988
13989       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13990
13991       /* Get next abbreviation.
13992          Under Irix6 the abbreviations for a compilation unit are not
13993          always properly terminated with an abbrev number of 0.
13994          Exit loop if we encounter an abbreviation which we have
13995          already read (which means we are about to read the abbreviations
13996          for the next compile unit) or if the end of the abbreviation
13997          table is reached.  */
13998       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13999         break;
14000       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14001       abbrev_ptr += bytes_read;
14002       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
14003         break;
14004     }
14005
14006   xfree (cur_attrs);
14007   return abbrev_table;
14008 }
14009
14010 /* Free the resources held by ABBREV_TABLE.  */
14011
14012 static void
14013 abbrev_table_free (struct abbrev_table *abbrev_table)
14014 {
14015   obstack_free (&abbrev_table->abbrev_obstack, NULL);
14016   xfree (abbrev_table);
14017 }
14018
14019 /* Same as abbrev_table_free but as a cleanup.
14020    We pass in a pointer to the pointer to the table so that we can
14021    set the pointer to NULL when we're done.  It also simplifies
14022    build_type_unit_groups.  */
14023
14024 static void
14025 abbrev_table_free_cleanup (void *table_ptr)
14026 {
14027   struct abbrev_table **abbrev_table_ptr = table_ptr;
14028
14029   if (*abbrev_table_ptr != NULL)
14030     abbrev_table_free (*abbrev_table_ptr);
14031   *abbrev_table_ptr = NULL;
14032 }
14033
14034 /* Read the abbrev table for CU from ABBREV_SECTION.  */
14035
14036 static void
14037 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
14038                      struct dwarf2_section_info *abbrev_section)
14039 {
14040   cu->abbrev_table =
14041     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
14042 }
14043
14044 /* Release the memory used by the abbrev table for a compilation unit.  */
14045
14046 static void
14047 dwarf2_free_abbrev_table (void *ptr_to_cu)
14048 {
14049   struct dwarf2_cu *cu = ptr_to_cu;
14050
14051   if (cu->abbrev_table != NULL)
14052     abbrev_table_free (cu->abbrev_table);
14053   /* Set this to NULL so that we SEGV if we try to read it later,
14054      and also because free_comp_unit verifies this is NULL.  */
14055   cu->abbrev_table = NULL;
14056 }
14057 \f
14058 /* Returns nonzero if TAG represents a type that we might generate a partial
14059    symbol for.  */
14060
14061 static int
14062 is_type_tag_for_partial (int tag)
14063 {
14064   switch (tag)
14065     {
14066 #if 0
14067     /* Some types that would be reasonable to generate partial symbols for,
14068        that we don't at present.  */
14069     case DW_TAG_array_type:
14070     case DW_TAG_file_type:
14071     case DW_TAG_ptr_to_member_type:
14072     case DW_TAG_set_type:
14073     case DW_TAG_string_type:
14074     case DW_TAG_subroutine_type:
14075 #endif
14076     case DW_TAG_base_type:
14077     case DW_TAG_class_type:
14078     case DW_TAG_interface_type:
14079     case DW_TAG_enumeration_type:
14080     case DW_TAG_structure_type:
14081     case DW_TAG_subrange_type:
14082     case DW_TAG_typedef:
14083     case DW_TAG_union_type:
14084       return 1;
14085     default:
14086       return 0;
14087     }
14088 }
14089
14090 /* Load all DIEs that are interesting for partial symbols into memory.  */
14091
14092 static struct partial_die_info *
14093 load_partial_dies (const struct die_reader_specs *reader,
14094                    const gdb_byte *info_ptr, int building_psymtab)
14095 {
14096   struct dwarf2_cu *cu = reader->cu;
14097   struct objfile *objfile = cu->objfile;
14098   struct partial_die_info *part_die;
14099   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14100   struct abbrev_info *abbrev;
14101   unsigned int bytes_read;
14102   unsigned int load_all = 0;
14103   int nesting_level = 1;
14104
14105   parent_die = NULL;
14106   last_die = NULL;
14107
14108   gdb_assert (cu->per_cu != NULL);
14109   if (cu->per_cu->load_all_dies)
14110     load_all = 1;
14111
14112   cu->partial_dies
14113     = htab_create_alloc_ex (cu->header.length / 12,
14114                             partial_die_hash,
14115                             partial_die_eq,
14116                             NULL,
14117                             &cu->comp_unit_obstack,
14118                             hashtab_obstack_allocate,
14119                             dummy_obstack_deallocate);
14120
14121   part_die = obstack_alloc (&cu->comp_unit_obstack,
14122                             sizeof (struct partial_die_info));
14123
14124   while (1)
14125     {
14126       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14127
14128       /* A NULL abbrev means the end of a series of children.  */
14129       if (abbrev == NULL)
14130         {
14131           if (--nesting_level == 0)
14132             {
14133               /* PART_DIE was probably the last thing allocated on the
14134                  comp_unit_obstack, so we could call obstack_free
14135                  here.  We don't do that because the waste is small,
14136                  and will be cleaned up when we're done with this
14137                  compilation unit.  This way, we're also more robust
14138                  against other users of the comp_unit_obstack.  */
14139               return first_die;
14140             }
14141           info_ptr += bytes_read;
14142           last_die = parent_die;
14143           parent_die = parent_die->die_parent;
14144           continue;
14145         }
14146
14147       /* Check for template arguments.  We never save these; if
14148          they're seen, we just mark the parent, and go on our way.  */
14149       if (parent_die != NULL
14150           && cu->language == language_cplus
14151           && (abbrev->tag == DW_TAG_template_type_param
14152               || abbrev->tag == DW_TAG_template_value_param))
14153         {
14154           parent_die->has_template_arguments = 1;
14155
14156           if (!load_all)
14157             {
14158               /* We don't need a partial DIE for the template argument.  */
14159               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14160               continue;
14161             }
14162         }
14163
14164       /* We only recurse into c++ subprograms looking for template arguments.
14165          Skip their other children.  */
14166       if (!load_all
14167           && cu->language == language_cplus
14168           && parent_die != NULL
14169           && parent_die->tag == DW_TAG_subprogram)
14170         {
14171           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14172           continue;
14173         }
14174
14175       /* Check whether this DIE is interesting enough to save.  Normally
14176          we would not be interested in members here, but there may be
14177          later variables referencing them via DW_AT_specification (for
14178          static members).  */
14179       if (!load_all
14180           && !is_type_tag_for_partial (abbrev->tag)
14181           && abbrev->tag != DW_TAG_constant
14182           && abbrev->tag != DW_TAG_enumerator
14183           && abbrev->tag != DW_TAG_subprogram
14184           && abbrev->tag != DW_TAG_lexical_block
14185           && abbrev->tag != DW_TAG_variable
14186           && abbrev->tag != DW_TAG_namespace
14187           && abbrev->tag != DW_TAG_module
14188           && abbrev->tag != DW_TAG_member
14189           && abbrev->tag != DW_TAG_imported_unit)
14190         {
14191           /* Otherwise we skip to the next sibling, if any.  */
14192           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14193           continue;
14194         }
14195
14196       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14197                                    info_ptr);
14198
14199       /* This two-pass algorithm for processing partial symbols has a
14200          high cost in cache pressure.  Thus, handle some simple cases
14201          here which cover the majority of C partial symbols.  DIEs
14202          which neither have specification tags in them, nor could have
14203          specification tags elsewhere pointing at them, can simply be
14204          processed and discarded.
14205
14206          This segment is also optional; scan_partial_symbols and
14207          add_partial_symbol will handle these DIEs if we chain
14208          them in normally.  When compilers which do not emit large
14209          quantities of duplicate debug information are more common,
14210          this code can probably be removed.  */
14211
14212       /* Any complete simple types at the top level (pretty much all
14213          of them, for a language without namespaces), can be processed
14214          directly.  */
14215       if (parent_die == NULL
14216           && part_die->has_specification == 0
14217           && part_die->is_declaration == 0
14218           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14219               || part_die->tag == DW_TAG_base_type
14220               || part_die->tag == DW_TAG_subrange_type))
14221         {
14222           if (building_psymtab && part_die->name != NULL)
14223             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14224                                  VAR_DOMAIN, LOC_TYPEDEF,
14225                                  &objfile->static_psymbols,
14226                                  0, (CORE_ADDR) 0, cu->language, objfile);
14227           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14228           continue;
14229         }
14230
14231       /* The exception for DW_TAG_typedef with has_children above is
14232          a workaround of GCC PR debug/47510.  In the case of this complaint
14233          type_name_no_tag_or_error will error on such types later.
14234
14235          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14236          it could not find the child DIEs referenced later, this is checked
14237          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14238
14239       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14240         complaint (&symfile_complaints,
14241                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14242                      "- DIE at 0x%x [in module %s]"),
14243                    part_die->offset.sect_off, objfile_name (objfile));
14244
14245       /* If we're at the second level, and we're an enumerator, and
14246          our parent has no specification (meaning possibly lives in a
14247          namespace elsewhere), then we can add the partial symbol now
14248          instead of queueing it.  */
14249       if (part_die->tag == DW_TAG_enumerator
14250           && parent_die != NULL
14251           && parent_die->die_parent == NULL
14252           && parent_die->tag == DW_TAG_enumeration_type
14253           && parent_die->has_specification == 0)
14254         {
14255           if (part_die->name == NULL)
14256             complaint (&symfile_complaints,
14257                        _("malformed enumerator DIE ignored"));
14258           else if (building_psymtab)
14259             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14260                                  VAR_DOMAIN, LOC_CONST,
14261                                  (cu->language == language_cplus
14262                                   || cu->language == language_java)
14263                                  ? &objfile->global_psymbols
14264                                  : &objfile->static_psymbols,
14265                                  0, (CORE_ADDR) 0, cu->language, objfile);
14266
14267           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14268           continue;
14269         }
14270
14271       /* We'll save this DIE so link it in.  */
14272       part_die->die_parent = parent_die;
14273       part_die->die_sibling = NULL;
14274       part_die->die_child = NULL;
14275
14276       if (last_die && last_die == parent_die)
14277         last_die->die_child = part_die;
14278       else if (last_die)
14279         last_die->die_sibling = part_die;
14280
14281       last_die = part_die;
14282
14283       if (first_die == NULL)
14284         first_die = part_die;
14285
14286       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14287          find interesting need to be in the hash table, because we
14288          also have the parent/sibling/child chains; only those that we
14289          might refer to by offset later during partial symbol reading.
14290
14291          For now this means things that might have be the target of a
14292          DW_AT_specification, DW_AT_abstract_origin, or
14293          DW_AT_extension.  DW_AT_extension will refer only to
14294          namespaces; DW_AT_abstract_origin refers to functions (and
14295          many things under the function DIE, but we do not recurse
14296          into function DIEs during partial symbol reading) and
14297          possibly variables as well; DW_AT_specification refers to
14298          declarations.  Declarations ought to have the DW_AT_declaration
14299          flag.  It happens that GCC forgets to put it in sometimes, but
14300          only for functions, not for types.
14301
14302          Adding more things than necessary to the hash table is harmless
14303          except for the performance cost.  Adding too few will result in
14304          wasted time in find_partial_die, when we reread the compilation
14305          unit with load_all_dies set.  */
14306
14307       if (load_all
14308           || abbrev->tag == DW_TAG_constant
14309           || abbrev->tag == DW_TAG_subprogram
14310           || abbrev->tag == DW_TAG_variable
14311           || abbrev->tag == DW_TAG_namespace
14312           || part_die->is_declaration)
14313         {
14314           void **slot;
14315
14316           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14317                                            part_die->offset.sect_off, INSERT);
14318           *slot = part_die;
14319         }
14320
14321       part_die = obstack_alloc (&cu->comp_unit_obstack,
14322                                 sizeof (struct partial_die_info));
14323
14324       /* For some DIEs we want to follow their children (if any).  For C
14325          we have no reason to follow the children of structures; for other
14326          languages we have to, so that we can get at method physnames
14327          to infer fully qualified class names, for DW_AT_specification,
14328          and for C++ template arguments.  For C++, we also look one level
14329          inside functions to find template arguments (if the name of the
14330          function does not already contain the template arguments).
14331
14332          For Ada, we need to scan the children of subprograms and lexical
14333          blocks as well because Ada allows the definition of nested
14334          entities that could be interesting for the debugger, such as
14335          nested subprograms for instance.  */
14336       if (last_die->has_children
14337           && (load_all
14338               || last_die->tag == DW_TAG_namespace
14339               || last_die->tag == DW_TAG_module
14340               || last_die->tag == DW_TAG_enumeration_type
14341               || (cu->language == language_cplus
14342                   && last_die->tag == DW_TAG_subprogram
14343                   && (last_die->name == NULL
14344                       || strchr (last_die->name, '<') == NULL))
14345               || (cu->language != language_c
14346                   && (last_die->tag == DW_TAG_class_type
14347                       || last_die->tag == DW_TAG_interface_type
14348                       || last_die->tag == DW_TAG_structure_type
14349                       || last_die->tag == DW_TAG_union_type))
14350               || (cu->language == language_ada
14351                   && (last_die->tag == DW_TAG_subprogram
14352                       || last_die->tag == DW_TAG_lexical_block))))
14353         {
14354           nesting_level++;
14355           parent_die = last_die;
14356           continue;
14357         }
14358
14359       /* Otherwise we skip to the next sibling, if any.  */
14360       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14361
14362       /* Back to the top, do it again.  */
14363     }
14364 }
14365
14366 /* Read a minimal amount of information into the minimal die structure.  */
14367
14368 static const gdb_byte *
14369 read_partial_die (const struct die_reader_specs *reader,
14370                   struct partial_die_info *part_die,
14371                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14372                   const gdb_byte *info_ptr)
14373 {
14374   struct dwarf2_cu *cu = reader->cu;
14375   struct objfile *objfile = cu->objfile;
14376   const gdb_byte *buffer = reader->buffer;
14377   unsigned int i;
14378   struct attribute attr;
14379   int has_low_pc_attr = 0;
14380   int has_high_pc_attr = 0;
14381   int high_pc_relative = 0;
14382
14383   memset (part_die, 0, sizeof (struct partial_die_info));
14384
14385   part_die->offset.sect_off = info_ptr - buffer;
14386
14387   info_ptr += abbrev_len;
14388
14389   if (abbrev == NULL)
14390     return info_ptr;
14391
14392   part_die->tag = abbrev->tag;
14393   part_die->has_children = abbrev->has_children;
14394
14395   for (i = 0; i < abbrev->num_attrs; ++i)
14396     {
14397       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14398
14399       /* Store the data if it is of an attribute we want to keep in a
14400          partial symbol table.  */
14401       switch (attr.name)
14402         {
14403         case DW_AT_name:
14404           switch (part_die->tag)
14405             {
14406             case DW_TAG_compile_unit:
14407             case DW_TAG_partial_unit:
14408             case DW_TAG_type_unit:
14409               /* Compilation units have a DW_AT_name that is a filename, not
14410                  a source language identifier.  */
14411             case DW_TAG_enumeration_type:
14412             case DW_TAG_enumerator:
14413               /* These tags always have simple identifiers already; no need
14414                  to canonicalize them.  */
14415               part_die->name = DW_STRING (&attr);
14416               break;
14417             default:
14418               part_die->name
14419                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14420                                             &objfile->objfile_obstack);
14421               break;
14422             }
14423           break;
14424         case DW_AT_linkage_name:
14425         case DW_AT_MIPS_linkage_name:
14426           /* Note that both forms of linkage name might appear.  We
14427              assume they will be the same, and we only store the last
14428              one we see.  */
14429           if (cu->language == language_ada)
14430             part_die->name = DW_STRING (&attr);
14431           part_die->linkage_name = DW_STRING (&attr);
14432           break;
14433         case DW_AT_low_pc:
14434           has_low_pc_attr = 1;
14435           part_die->lowpc = DW_ADDR (&attr);
14436           break;
14437         case DW_AT_high_pc:
14438           has_high_pc_attr = 1;
14439           if (attr.form == DW_FORM_addr
14440               || attr.form == DW_FORM_GNU_addr_index)
14441             part_die->highpc = DW_ADDR (&attr);
14442           else
14443             {
14444               high_pc_relative = 1;
14445               part_die->highpc = DW_UNSND (&attr);
14446             }
14447           break;
14448         case DW_AT_location:
14449           /* Support the .debug_loc offsets.  */
14450           if (attr_form_is_block (&attr))
14451             {
14452                part_die->d.locdesc = DW_BLOCK (&attr);
14453             }
14454           else if (attr_form_is_section_offset (&attr))
14455             {
14456               dwarf2_complex_location_expr_complaint ();
14457             }
14458           else
14459             {
14460               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14461                                                      "partial symbol information");
14462             }
14463           break;
14464         case DW_AT_external:
14465           part_die->is_external = DW_UNSND (&attr);
14466           break;
14467         case DW_AT_declaration:
14468           part_die->is_declaration = DW_UNSND (&attr);
14469           break;
14470         case DW_AT_type:
14471           part_die->has_type = 1;
14472           break;
14473         case DW_AT_abstract_origin:
14474         case DW_AT_specification:
14475         case DW_AT_extension:
14476           part_die->has_specification = 1;
14477           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14478           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14479                                    || cu->per_cu->is_dwz);
14480           break;
14481         case DW_AT_sibling:
14482           /* Ignore absolute siblings, they might point outside of
14483              the current compile unit.  */
14484           if (attr.form == DW_FORM_ref_addr)
14485             complaint (&symfile_complaints,
14486                        _("ignoring absolute DW_AT_sibling"));
14487           else
14488             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14489           break;
14490         case DW_AT_byte_size:
14491           part_die->has_byte_size = 1;
14492           break;
14493         case DW_AT_calling_convention:
14494           /* DWARF doesn't provide a way to identify a program's source-level
14495              entry point.  DW_AT_calling_convention attributes are only meant
14496              to describe functions' calling conventions.
14497
14498              However, because it's a necessary piece of information in
14499              Fortran, and because DW_CC_program is the only piece of debugging
14500              information whose definition refers to a 'main program' at all,
14501              several compilers have begun marking Fortran main programs with
14502              DW_CC_program --- even when those functions use the standard
14503              calling conventions.
14504
14505              So until DWARF specifies a way to provide this information and
14506              compilers pick up the new representation, we'll support this
14507              practice.  */
14508           if (DW_UNSND (&attr) == DW_CC_program
14509               && cu->language == language_fortran)
14510             {
14511               set_main_name (part_die->name);
14512
14513               /* As this DIE has a static linkage the name would be difficult
14514                  to look up later.  */
14515               language_of_main = language_fortran;
14516             }
14517           break;
14518         case DW_AT_inline:
14519           if (DW_UNSND (&attr) == DW_INL_inlined
14520               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14521             part_die->may_be_inlined = 1;
14522           break;
14523
14524         case DW_AT_import:
14525           if (part_die->tag == DW_TAG_imported_unit)
14526             {
14527               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14528               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14529                                   || cu->per_cu->is_dwz);
14530             }
14531           break;
14532
14533         default:
14534           break;
14535         }
14536     }
14537
14538   if (high_pc_relative)
14539     part_die->highpc += part_die->lowpc;
14540
14541   if (has_low_pc_attr && has_high_pc_attr)
14542     {
14543       /* When using the GNU linker, .gnu.linkonce. sections are used to
14544          eliminate duplicate copies of functions and vtables and such.
14545          The linker will arbitrarily choose one and discard the others.
14546          The AT_*_pc values for such functions refer to local labels in
14547          these sections.  If the section from that file was discarded, the
14548          labels are not in the output, so the relocs get a value of 0.
14549          If this is a discarded function, mark the pc bounds as invalid,
14550          so that GDB will ignore it.  */
14551       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14552         {
14553           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14554
14555           complaint (&symfile_complaints,
14556                      _("DW_AT_low_pc %s is zero "
14557                        "for DIE at 0x%x [in module %s]"),
14558                      paddress (gdbarch, part_die->lowpc),
14559                      part_die->offset.sect_off, objfile_name (objfile));
14560         }
14561       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14562       else if (part_die->lowpc >= part_die->highpc)
14563         {
14564           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14565
14566           complaint (&symfile_complaints,
14567                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14568                        "for DIE at 0x%x [in module %s]"),
14569                      paddress (gdbarch, part_die->lowpc),
14570                      paddress (gdbarch, part_die->highpc),
14571                      part_die->offset.sect_off, objfile_name (objfile));
14572         }
14573       else
14574         part_die->has_pc_info = 1;
14575     }
14576
14577   return info_ptr;
14578 }
14579
14580 /* Find a cached partial DIE at OFFSET in CU.  */
14581
14582 static struct partial_die_info *
14583 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14584 {
14585   struct partial_die_info *lookup_die = NULL;
14586   struct partial_die_info part_die;
14587
14588   part_die.offset = offset;
14589   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14590                                     offset.sect_off);
14591
14592   return lookup_die;
14593 }
14594
14595 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14596    except in the case of .debug_types DIEs which do not reference
14597    outside their CU (they do however referencing other types via
14598    DW_FORM_ref_sig8).  */
14599
14600 static struct partial_die_info *
14601 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14602 {
14603   struct objfile *objfile = cu->objfile;
14604   struct dwarf2_per_cu_data *per_cu = NULL;
14605   struct partial_die_info *pd = NULL;
14606
14607   if (offset_in_dwz == cu->per_cu->is_dwz
14608       && offset_in_cu_p (&cu->header, offset))
14609     {
14610       pd = find_partial_die_in_comp_unit (offset, cu);
14611       if (pd != NULL)
14612         return pd;
14613       /* We missed recording what we needed.
14614          Load all dies and try again.  */
14615       per_cu = cu->per_cu;
14616     }
14617   else
14618     {
14619       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14620       if (cu->per_cu->is_debug_types)
14621         {
14622           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14623                    " external reference to offset 0x%lx [in module %s].\n"),
14624                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14625                  bfd_get_filename (objfile->obfd));
14626         }
14627       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14628                                                  objfile);
14629
14630       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14631         load_partial_comp_unit (per_cu);
14632
14633       per_cu->cu->last_used = 0;
14634       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14635     }
14636
14637   /* If we didn't find it, and not all dies have been loaded,
14638      load them all and try again.  */
14639
14640   if (pd == NULL && per_cu->load_all_dies == 0)
14641     {
14642       per_cu->load_all_dies = 1;
14643
14644       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14645          THIS_CU->cu may already be in use.  So we can't just free it and
14646          replace its DIEs with the ones we read in.  Instead, we leave those
14647          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14648          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14649          set.  */
14650       load_partial_comp_unit (per_cu);
14651
14652       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14653     }
14654
14655   if (pd == NULL)
14656     internal_error (__FILE__, __LINE__,
14657                     _("could not find partial DIE 0x%x "
14658                       "in cache [from module %s]\n"),
14659                     offset.sect_off, bfd_get_filename (objfile->obfd));
14660   return pd;
14661 }
14662
14663 /* See if we can figure out if the class lives in a namespace.  We do
14664    this by looking for a member function; its demangled name will
14665    contain namespace info, if there is any.  */
14666
14667 static void
14668 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14669                                   struct dwarf2_cu *cu)
14670 {
14671   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14672      what template types look like, because the demangler
14673      frequently doesn't give the same name as the debug info.  We
14674      could fix this by only using the demangled name to get the
14675      prefix (but see comment in read_structure_type).  */
14676
14677   struct partial_die_info *real_pdi;
14678   struct partial_die_info *child_pdi;
14679
14680   /* If this DIE (this DIE's specification, if any) has a parent, then
14681      we should not do this.  We'll prepend the parent's fully qualified
14682      name when we create the partial symbol.  */
14683
14684   real_pdi = struct_pdi;
14685   while (real_pdi->has_specification)
14686     real_pdi = find_partial_die (real_pdi->spec_offset,
14687                                  real_pdi->spec_is_dwz, cu);
14688
14689   if (real_pdi->die_parent != NULL)
14690     return;
14691
14692   for (child_pdi = struct_pdi->die_child;
14693        child_pdi != NULL;
14694        child_pdi = child_pdi->die_sibling)
14695     {
14696       if (child_pdi->tag == DW_TAG_subprogram
14697           && child_pdi->linkage_name != NULL)
14698         {
14699           char *actual_class_name
14700             = language_class_name_from_physname (cu->language_defn,
14701                                                  child_pdi->linkage_name);
14702           if (actual_class_name != NULL)
14703             {
14704               struct_pdi->name
14705                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14706                                  actual_class_name,
14707                                  strlen (actual_class_name));
14708               xfree (actual_class_name);
14709             }
14710           break;
14711         }
14712     }
14713 }
14714
14715 /* Adjust PART_DIE before generating a symbol for it.  This function
14716    may set the is_external flag or change the DIE's name.  */
14717
14718 static void
14719 fixup_partial_die (struct partial_die_info *part_die,
14720                    struct dwarf2_cu *cu)
14721 {
14722   /* Once we've fixed up a die, there's no point in doing so again.
14723      This also avoids a memory leak if we were to call
14724      guess_partial_die_structure_name multiple times.  */
14725   if (part_die->fixup_called)
14726     return;
14727
14728   /* If we found a reference attribute and the DIE has no name, try
14729      to find a name in the referred to DIE.  */
14730
14731   if (part_die->name == NULL && part_die->has_specification)
14732     {
14733       struct partial_die_info *spec_die;
14734
14735       spec_die = find_partial_die (part_die->spec_offset,
14736                                    part_die->spec_is_dwz, cu);
14737
14738       fixup_partial_die (spec_die, cu);
14739
14740       if (spec_die->name)
14741         {
14742           part_die->name = spec_die->name;
14743
14744           /* Copy DW_AT_external attribute if it is set.  */
14745           if (spec_die->is_external)
14746             part_die->is_external = spec_die->is_external;
14747         }
14748     }
14749
14750   /* Set default names for some unnamed DIEs.  */
14751
14752   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14753     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14754
14755   /* If there is no parent die to provide a namespace, and there are
14756      children, see if we can determine the namespace from their linkage
14757      name.  */
14758   if (cu->language == language_cplus
14759       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14760       && part_die->die_parent == NULL
14761       && part_die->has_children
14762       && (part_die->tag == DW_TAG_class_type
14763           || part_die->tag == DW_TAG_structure_type
14764           || part_die->tag == DW_TAG_union_type))
14765     guess_partial_die_structure_name (part_die, cu);
14766
14767   /* GCC might emit a nameless struct or union that has a linkage
14768      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14769   if (part_die->name == NULL
14770       && (part_die->tag == DW_TAG_class_type
14771           || part_die->tag == DW_TAG_interface_type
14772           || part_die->tag == DW_TAG_structure_type
14773           || part_die->tag == DW_TAG_union_type)
14774       && part_die->linkage_name != NULL)
14775     {
14776       char *demangled;
14777
14778       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14779       if (demangled)
14780         {
14781           const char *base;
14782
14783           /* Strip any leading namespaces/classes, keep only the base name.
14784              DW_AT_name for named DIEs does not contain the prefixes.  */
14785           base = strrchr (demangled, ':');
14786           if (base && base > demangled && base[-1] == ':')
14787             base++;
14788           else
14789             base = demangled;
14790
14791           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14792                                           base, strlen (base));
14793           xfree (demangled);
14794         }
14795     }
14796
14797   part_die->fixup_called = 1;
14798 }
14799
14800 /* Read an attribute value described by an attribute form.  */
14801
14802 static const gdb_byte *
14803 read_attribute_value (const struct die_reader_specs *reader,
14804                       struct attribute *attr, unsigned form,
14805                       const gdb_byte *info_ptr)
14806 {
14807   struct dwarf2_cu *cu = reader->cu;
14808   bfd *abfd = reader->abfd;
14809   struct comp_unit_head *cu_header = &cu->header;
14810   unsigned int bytes_read;
14811   struct dwarf_block *blk;
14812
14813   attr->form = form;
14814   switch (form)
14815     {
14816     case DW_FORM_ref_addr:
14817       if (cu->header.version == 2)
14818         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14819       else
14820         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14821                                        &cu->header, &bytes_read);
14822       info_ptr += bytes_read;
14823       break;
14824     case DW_FORM_GNU_ref_alt:
14825       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14826       info_ptr += bytes_read;
14827       break;
14828     case DW_FORM_addr:
14829       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14830       info_ptr += bytes_read;
14831       break;
14832     case DW_FORM_block2:
14833       blk = dwarf_alloc_block (cu);
14834       blk->size = read_2_bytes (abfd, info_ptr);
14835       info_ptr += 2;
14836       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14837       info_ptr += blk->size;
14838       DW_BLOCK (attr) = blk;
14839       break;
14840     case DW_FORM_block4:
14841       blk = dwarf_alloc_block (cu);
14842       blk->size = read_4_bytes (abfd, info_ptr);
14843       info_ptr += 4;
14844       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14845       info_ptr += blk->size;
14846       DW_BLOCK (attr) = blk;
14847       break;
14848     case DW_FORM_data2:
14849       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14850       info_ptr += 2;
14851       break;
14852     case DW_FORM_data4:
14853       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14854       info_ptr += 4;
14855       break;
14856     case DW_FORM_data8:
14857       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14858       info_ptr += 8;
14859       break;
14860     case DW_FORM_sec_offset:
14861       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14862       info_ptr += bytes_read;
14863       break;
14864     case DW_FORM_string:
14865       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14866       DW_STRING_IS_CANONICAL (attr) = 0;
14867       info_ptr += bytes_read;
14868       break;
14869     case DW_FORM_strp:
14870       if (!cu->per_cu->is_dwz)
14871         {
14872           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14873                                                    &bytes_read);
14874           DW_STRING_IS_CANONICAL (attr) = 0;
14875           info_ptr += bytes_read;
14876           break;
14877         }
14878       /* FALLTHROUGH */
14879     case DW_FORM_GNU_strp_alt:
14880       {
14881         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14882         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14883                                           &bytes_read);
14884
14885         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14886         DW_STRING_IS_CANONICAL (attr) = 0;
14887         info_ptr += bytes_read;
14888       }
14889       break;
14890     case DW_FORM_exprloc:
14891     case DW_FORM_block:
14892       blk = dwarf_alloc_block (cu);
14893       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14894       info_ptr += bytes_read;
14895       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14896       info_ptr += blk->size;
14897       DW_BLOCK (attr) = blk;
14898       break;
14899     case DW_FORM_block1:
14900       blk = dwarf_alloc_block (cu);
14901       blk->size = read_1_byte (abfd, info_ptr);
14902       info_ptr += 1;
14903       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14904       info_ptr += blk->size;
14905       DW_BLOCK (attr) = blk;
14906       break;
14907     case DW_FORM_data1:
14908       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14909       info_ptr += 1;
14910       break;
14911     case DW_FORM_flag:
14912       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14913       info_ptr += 1;
14914       break;
14915     case DW_FORM_flag_present:
14916       DW_UNSND (attr) = 1;
14917       break;
14918     case DW_FORM_sdata:
14919       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14920       info_ptr += bytes_read;
14921       break;
14922     case DW_FORM_udata:
14923       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14924       info_ptr += bytes_read;
14925       break;
14926     case DW_FORM_ref1:
14927       DW_UNSND (attr) = (cu->header.offset.sect_off
14928                          + read_1_byte (abfd, info_ptr));
14929       info_ptr += 1;
14930       break;
14931     case DW_FORM_ref2:
14932       DW_UNSND (attr) = (cu->header.offset.sect_off
14933                          + read_2_bytes (abfd, info_ptr));
14934       info_ptr += 2;
14935       break;
14936     case DW_FORM_ref4:
14937       DW_UNSND (attr) = (cu->header.offset.sect_off
14938                          + read_4_bytes (abfd, info_ptr));
14939       info_ptr += 4;
14940       break;
14941     case DW_FORM_ref8:
14942       DW_UNSND (attr) = (cu->header.offset.sect_off
14943                          + read_8_bytes (abfd, info_ptr));
14944       info_ptr += 8;
14945       break;
14946     case DW_FORM_ref_sig8:
14947       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14948       info_ptr += 8;
14949       break;
14950     case DW_FORM_ref_udata:
14951       DW_UNSND (attr) = (cu->header.offset.sect_off
14952                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14953       info_ptr += bytes_read;
14954       break;
14955     case DW_FORM_indirect:
14956       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14957       info_ptr += bytes_read;
14958       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14959       break;
14960     case DW_FORM_GNU_addr_index:
14961       if (reader->dwo_file == NULL)
14962         {
14963           /* For now flag a hard error.
14964              Later we can turn this into a complaint.  */
14965           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14966                  dwarf_form_name (form),
14967                  bfd_get_filename (abfd));
14968         }
14969       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14970       info_ptr += bytes_read;
14971       break;
14972     case DW_FORM_GNU_str_index:
14973       if (reader->dwo_file == NULL)
14974         {
14975           /* For now flag a hard error.
14976              Later we can turn this into a complaint if warranted.  */
14977           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14978                  dwarf_form_name (form),
14979                  bfd_get_filename (abfd));
14980         }
14981       {
14982         ULONGEST str_index =
14983           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14984
14985         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14986         DW_STRING_IS_CANONICAL (attr) = 0;
14987         info_ptr += bytes_read;
14988       }
14989       break;
14990     default:
14991       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14992              dwarf_form_name (form),
14993              bfd_get_filename (abfd));
14994     }
14995
14996   /* Super hack.  */
14997   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
14998     attr->form = DW_FORM_GNU_ref_alt;
14999
15000   /* We have seen instances where the compiler tried to emit a byte
15001      size attribute of -1 which ended up being encoded as an unsigned
15002      0xffffffff.  Although 0xffffffff is technically a valid size value,
15003      an object of this size seems pretty unlikely so we can relatively
15004      safely treat these cases as if the size attribute was invalid and
15005      treat them as zero by default.  */
15006   if (attr->name == DW_AT_byte_size
15007       && form == DW_FORM_data4
15008       && DW_UNSND (attr) >= 0xffffffff)
15009     {
15010       complaint
15011         (&symfile_complaints,
15012          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
15013          hex_string (DW_UNSND (attr)));
15014       DW_UNSND (attr) = 0;
15015     }
15016
15017   return info_ptr;
15018 }
15019
15020 /* Read an attribute described by an abbreviated attribute.  */
15021
15022 static const gdb_byte *
15023 read_attribute (const struct die_reader_specs *reader,
15024                 struct attribute *attr, struct attr_abbrev *abbrev,
15025                 const gdb_byte *info_ptr)
15026 {
15027   attr->name = abbrev->name;
15028   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
15029 }
15030
15031 /* Read dwarf information from a buffer.  */
15032
15033 static unsigned int
15034 read_1_byte (bfd *abfd, const gdb_byte *buf)
15035 {
15036   return bfd_get_8 (abfd, buf);
15037 }
15038
15039 static int
15040 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
15041 {
15042   return bfd_get_signed_8 (abfd, buf);
15043 }
15044
15045 static unsigned int
15046 read_2_bytes (bfd *abfd, const gdb_byte *buf)
15047 {
15048   return bfd_get_16 (abfd, buf);
15049 }
15050
15051 static int
15052 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
15053 {
15054   return bfd_get_signed_16 (abfd, buf);
15055 }
15056
15057 static unsigned int
15058 read_4_bytes (bfd *abfd, const gdb_byte *buf)
15059 {
15060   return bfd_get_32 (abfd, buf);
15061 }
15062
15063 static int
15064 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
15065 {
15066   return bfd_get_signed_32 (abfd, buf);
15067 }
15068
15069 static ULONGEST
15070 read_8_bytes (bfd *abfd, const gdb_byte *buf)
15071 {
15072   return bfd_get_64 (abfd, buf);
15073 }
15074
15075 static CORE_ADDR
15076 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
15077               unsigned int *bytes_read)
15078 {
15079   struct comp_unit_head *cu_header = &cu->header;
15080   CORE_ADDR retval = 0;
15081
15082   if (cu_header->signed_addr_p)
15083     {
15084       switch (cu_header->addr_size)
15085         {
15086         case 2:
15087           retval = bfd_get_signed_16 (abfd, buf);
15088           break;
15089         case 4:
15090           retval = bfd_get_signed_32 (abfd, buf);
15091           break;
15092         case 8:
15093           retval = bfd_get_signed_64 (abfd, buf);
15094           break;
15095         default:
15096           internal_error (__FILE__, __LINE__,
15097                           _("read_address: bad switch, signed [in module %s]"),
15098                           bfd_get_filename (abfd));
15099         }
15100     }
15101   else
15102     {
15103       switch (cu_header->addr_size)
15104         {
15105         case 2:
15106           retval = bfd_get_16 (abfd, buf);
15107           break;
15108         case 4:
15109           retval = bfd_get_32 (abfd, buf);
15110           break;
15111         case 8:
15112           retval = bfd_get_64 (abfd, buf);
15113           break;
15114         default:
15115           internal_error (__FILE__, __LINE__,
15116                           _("read_address: bad switch, "
15117                             "unsigned [in module %s]"),
15118                           bfd_get_filename (abfd));
15119         }
15120     }
15121
15122   *bytes_read = cu_header->addr_size;
15123   return retval;
15124 }
15125
15126 /* Read the initial length from a section.  The (draft) DWARF 3
15127    specification allows the initial length to take up either 4 bytes
15128    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15129    bytes describe the length and all offsets will be 8 bytes in length
15130    instead of 4.
15131
15132    An older, non-standard 64-bit format is also handled by this
15133    function.  The older format in question stores the initial length
15134    as an 8-byte quantity without an escape value.  Lengths greater
15135    than 2^32 aren't very common which means that the initial 4 bytes
15136    is almost always zero.  Since a length value of zero doesn't make
15137    sense for the 32-bit format, this initial zero can be considered to
15138    be an escape value which indicates the presence of the older 64-bit
15139    format.  As written, the code can't detect (old format) lengths
15140    greater than 4GB.  If it becomes necessary to handle lengths
15141    somewhat larger than 4GB, we could allow other small values (such
15142    as the non-sensical values of 1, 2, and 3) to also be used as
15143    escape values indicating the presence of the old format.
15144
15145    The value returned via bytes_read should be used to increment the
15146    relevant pointer after calling read_initial_length().
15147
15148    [ Note:  read_initial_length() and read_offset() are based on the
15149      document entitled "DWARF Debugging Information Format", revision
15150      3, draft 8, dated November 19, 2001.  This document was obtained
15151      from:
15152
15153         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15154
15155      This document is only a draft and is subject to change.  (So beware.)
15156
15157      Details regarding the older, non-standard 64-bit format were
15158      determined empirically by examining 64-bit ELF files produced by
15159      the SGI toolchain on an IRIX 6.5 machine.
15160
15161      - Kevin, July 16, 2002
15162    ] */
15163
15164 static LONGEST
15165 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15166 {
15167   LONGEST length = bfd_get_32 (abfd, buf);
15168
15169   if (length == 0xffffffff)
15170     {
15171       length = bfd_get_64 (abfd, buf + 4);
15172       *bytes_read = 12;
15173     }
15174   else if (length == 0)
15175     {
15176       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15177       length = bfd_get_64 (abfd, buf);
15178       *bytes_read = 8;
15179     }
15180   else
15181     {
15182       *bytes_read = 4;
15183     }
15184
15185   return length;
15186 }
15187
15188 /* Cover function for read_initial_length.
15189    Returns the length of the object at BUF, and stores the size of the
15190    initial length in *BYTES_READ and stores the size that offsets will be in
15191    *OFFSET_SIZE.
15192    If the initial length size is not equivalent to that specified in
15193    CU_HEADER then issue a complaint.
15194    This is useful when reading non-comp-unit headers.  */
15195
15196 static LONGEST
15197 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15198                                         const struct comp_unit_head *cu_header,
15199                                         unsigned int *bytes_read,
15200                                         unsigned int *offset_size)
15201 {
15202   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15203
15204   gdb_assert (cu_header->initial_length_size == 4
15205               || cu_header->initial_length_size == 8
15206               || cu_header->initial_length_size == 12);
15207
15208   if (cu_header->initial_length_size != *bytes_read)
15209     complaint (&symfile_complaints,
15210                _("intermixed 32-bit and 64-bit DWARF sections"));
15211
15212   *offset_size = (*bytes_read == 4) ? 4 : 8;
15213   return length;
15214 }
15215
15216 /* Read an offset from the data stream.  The size of the offset is
15217    given by cu_header->offset_size.  */
15218
15219 static LONGEST
15220 read_offset (bfd *abfd, const gdb_byte *buf,
15221              const struct comp_unit_head *cu_header,
15222              unsigned int *bytes_read)
15223 {
15224   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15225
15226   *bytes_read = cu_header->offset_size;
15227   return offset;
15228 }
15229
15230 /* Read an offset from the data stream.  */
15231
15232 static LONGEST
15233 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15234 {
15235   LONGEST retval = 0;
15236
15237   switch (offset_size)
15238     {
15239     case 4:
15240       retval = bfd_get_32 (abfd, buf);
15241       break;
15242     case 8:
15243       retval = bfd_get_64 (abfd, buf);
15244       break;
15245     default:
15246       internal_error (__FILE__, __LINE__,
15247                       _("read_offset_1: bad switch [in module %s]"),
15248                       bfd_get_filename (abfd));
15249     }
15250
15251   return retval;
15252 }
15253
15254 static const gdb_byte *
15255 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15256 {
15257   /* If the size of a host char is 8 bits, we can return a pointer
15258      to the buffer, otherwise we have to copy the data to a buffer
15259      allocated on the temporary obstack.  */
15260   gdb_assert (HOST_CHAR_BIT == 8);
15261   return buf;
15262 }
15263
15264 static const char *
15265 read_direct_string (bfd *abfd, const gdb_byte *buf,
15266                     unsigned int *bytes_read_ptr)
15267 {
15268   /* If the size of a host char is 8 bits, we can return a pointer
15269      to the string, otherwise we have to copy the string to a buffer
15270      allocated on the temporary obstack.  */
15271   gdb_assert (HOST_CHAR_BIT == 8);
15272   if (*buf == '\0')
15273     {
15274       *bytes_read_ptr = 1;
15275       return NULL;
15276     }
15277   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15278   return (const char *) buf;
15279 }
15280
15281 static const char *
15282 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15283 {
15284   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15285   if (dwarf2_per_objfile->str.buffer == NULL)
15286     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15287            bfd_get_filename (abfd));
15288   if (str_offset >= dwarf2_per_objfile->str.size)
15289     error (_("DW_FORM_strp pointing outside of "
15290              ".debug_str section [in module %s]"),
15291            bfd_get_filename (abfd));
15292   gdb_assert (HOST_CHAR_BIT == 8);
15293   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15294     return NULL;
15295   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15296 }
15297
15298 /* Read a string at offset STR_OFFSET in the .debug_str section from
15299    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15300    the string consists of a single NUL byte, return NULL; otherwise
15301    return a pointer to the string.  */
15302
15303 static const char *
15304 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15305 {
15306   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15307
15308   if (dwz->str.buffer == NULL)
15309     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15310              "section [in module %s]"),
15311            bfd_get_filename (dwz->dwz_bfd));
15312   if (str_offset >= dwz->str.size)
15313     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15314              ".debug_str section [in module %s]"),
15315            bfd_get_filename (dwz->dwz_bfd));
15316   gdb_assert (HOST_CHAR_BIT == 8);
15317   if (dwz->str.buffer[str_offset] == '\0')
15318     return NULL;
15319   return (const char *) (dwz->str.buffer + str_offset);
15320 }
15321
15322 static const char *
15323 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15324                       const struct comp_unit_head *cu_header,
15325                       unsigned int *bytes_read_ptr)
15326 {
15327   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15328
15329   return read_indirect_string_at_offset (abfd, str_offset);
15330 }
15331
15332 static ULONGEST
15333 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15334                       unsigned int *bytes_read_ptr)
15335 {
15336   ULONGEST result;
15337   unsigned int num_read;
15338   int i, shift;
15339   unsigned char byte;
15340
15341   result = 0;
15342   shift = 0;
15343   num_read = 0;
15344   i = 0;
15345   while (1)
15346     {
15347       byte = bfd_get_8 (abfd, buf);
15348       buf++;
15349       num_read++;
15350       result |= ((ULONGEST) (byte & 127) << shift);
15351       if ((byte & 128) == 0)
15352         {
15353           break;
15354         }
15355       shift += 7;
15356     }
15357   *bytes_read_ptr = num_read;
15358   return result;
15359 }
15360
15361 static LONGEST
15362 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15363                     unsigned int *bytes_read_ptr)
15364 {
15365   LONGEST result;
15366   int i, shift, num_read;
15367   unsigned char byte;
15368
15369   result = 0;
15370   shift = 0;
15371   num_read = 0;
15372   i = 0;
15373   while (1)
15374     {
15375       byte = bfd_get_8 (abfd, buf);
15376       buf++;
15377       num_read++;
15378       result |= ((LONGEST) (byte & 127) << shift);
15379       shift += 7;
15380       if ((byte & 128) == 0)
15381         {
15382           break;
15383         }
15384     }
15385   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15386     result |= -(((LONGEST) 1) << shift);
15387   *bytes_read_ptr = num_read;
15388   return result;
15389 }
15390
15391 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15392    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15393    ADDR_SIZE is the size of addresses from the CU header.  */
15394
15395 static CORE_ADDR
15396 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15397 {
15398   struct objfile *objfile = dwarf2_per_objfile->objfile;
15399   bfd *abfd = objfile->obfd;
15400   const gdb_byte *info_ptr;
15401
15402   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15403   if (dwarf2_per_objfile->addr.buffer == NULL)
15404     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15405            objfile_name (objfile));
15406   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15407     error (_("DW_FORM_addr_index pointing outside of "
15408              ".debug_addr section [in module %s]"),
15409            objfile_name (objfile));
15410   info_ptr = (dwarf2_per_objfile->addr.buffer
15411               + addr_base + addr_index * addr_size);
15412   if (addr_size == 4)
15413     return bfd_get_32 (abfd, info_ptr);
15414   else
15415     return bfd_get_64 (abfd, info_ptr);
15416 }
15417
15418 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15419
15420 static CORE_ADDR
15421 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15422 {
15423   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15424 }
15425
15426 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15427
15428 static CORE_ADDR
15429 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15430                              unsigned int *bytes_read)
15431 {
15432   bfd *abfd = cu->objfile->obfd;
15433   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15434
15435   return read_addr_index (cu, addr_index);
15436 }
15437
15438 /* Data structure to pass results from dwarf2_read_addr_index_reader
15439    back to dwarf2_read_addr_index.  */
15440
15441 struct dwarf2_read_addr_index_data
15442 {
15443   ULONGEST addr_base;
15444   int addr_size;
15445 };
15446
15447 /* die_reader_func for dwarf2_read_addr_index.  */
15448
15449 static void
15450 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15451                                const gdb_byte *info_ptr,
15452                                struct die_info *comp_unit_die,
15453                                int has_children,
15454                                void *data)
15455 {
15456   struct dwarf2_cu *cu = reader->cu;
15457   struct dwarf2_read_addr_index_data *aidata =
15458     (struct dwarf2_read_addr_index_data *) data;
15459
15460   aidata->addr_base = cu->addr_base;
15461   aidata->addr_size = cu->header.addr_size;
15462 }
15463
15464 /* Given an index in .debug_addr, fetch the value.
15465    NOTE: This can be called during dwarf expression evaluation,
15466    long after the debug information has been read, and thus per_cu->cu
15467    may no longer exist.  */
15468
15469 CORE_ADDR
15470 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15471                         unsigned int addr_index)
15472 {
15473   struct objfile *objfile = per_cu->objfile;
15474   struct dwarf2_cu *cu = per_cu->cu;
15475   ULONGEST addr_base;
15476   int addr_size;
15477
15478   /* This is intended to be called from outside this file.  */
15479   dw2_setup (objfile);
15480
15481   /* We need addr_base and addr_size.
15482      If we don't have PER_CU->cu, we have to get it.
15483      Nasty, but the alternative is storing the needed info in PER_CU,
15484      which at this point doesn't seem justified: it's not clear how frequently
15485      it would get used and it would increase the size of every PER_CU.
15486      Entry points like dwarf2_per_cu_addr_size do a similar thing
15487      so we're not in uncharted territory here.
15488      Alas we need to be a bit more complicated as addr_base is contained
15489      in the DIE.
15490
15491      We don't need to read the entire CU(/TU).
15492      We just need the header and top level die.
15493
15494      IWBN to use the aging mechanism to let us lazily later discard the CU.
15495      For now we skip this optimization.  */
15496
15497   if (cu != NULL)
15498     {
15499       addr_base = cu->addr_base;
15500       addr_size = cu->header.addr_size;
15501     }
15502   else
15503     {
15504       struct dwarf2_read_addr_index_data aidata;
15505
15506       /* Note: We can't use init_cutu_and_read_dies_simple here,
15507          we need addr_base.  */
15508       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15509                                dwarf2_read_addr_index_reader, &aidata);
15510       addr_base = aidata.addr_base;
15511       addr_size = aidata.addr_size;
15512     }
15513
15514   return read_addr_index_1 (addr_index, addr_base, addr_size);
15515 }
15516
15517 /* Given a DW_FORM_GNU_str_index, fetch the string.
15518    This is only used by the Fission support.  */
15519
15520 static const char *
15521 read_str_index (const struct die_reader_specs *reader,
15522                 struct dwarf2_cu *cu, ULONGEST str_index)
15523 {
15524   struct objfile *objfile = dwarf2_per_objfile->objfile;
15525   const char *dwo_name = objfile_name (objfile);
15526   bfd *abfd = objfile->obfd;
15527   struct dwo_sections *sections = &reader->dwo_file->sections;
15528   const gdb_byte *info_ptr;
15529   ULONGEST str_offset;
15530   static const char form_name[] = "DW_FORM_GNU_str_index";
15531
15532   dwarf2_read_section (objfile, &sections->str);
15533   dwarf2_read_section (objfile, &sections->str_offsets);
15534   if (sections->str.buffer == NULL)
15535     error (_("%s used without .debug_str.dwo section"
15536              " in CU at offset 0x%lx [in module %s]"),
15537            form_name, (long) cu->header.offset.sect_off, dwo_name);
15538   if (sections->str_offsets.buffer == NULL)
15539     error (_("%s used without .debug_str_offsets.dwo section"
15540              " in CU at offset 0x%lx [in module %s]"),
15541            form_name, (long) cu->header.offset.sect_off, dwo_name);
15542   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15543     error (_("%s pointing outside of .debug_str_offsets.dwo"
15544              " section in CU at offset 0x%lx [in module %s]"),
15545            form_name, (long) cu->header.offset.sect_off, dwo_name);
15546   info_ptr = (sections->str_offsets.buffer
15547               + str_index * cu->header.offset_size);
15548   if (cu->header.offset_size == 4)
15549     str_offset = bfd_get_32 (abfd, info_ptr);
15550   else
15551     str_offset = bfd_get_64 (abfd, info_ptr);
15552   if (str_offset >= sections->str.size)
15553     error (_("Offset from %s pointing outside of"
15554              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15555            form_name, (long) cu->header.offset.sect_off, dwo_name);
15556   return (const char *) (sections->str.buffer + str_offset);
15557 }
15558
15559 /* Return the length of an LEB128 number in BUF.  */
15560
15561 static int
15562 leb128_size (const gdb_byte *buf)
15563 {
15564   const gdb_byte *begin = buf;
15565   gdb_byte byte;
15566
15567   while (1)
15568     {
15569       byte = *buf++;
15570       if ((byte & 128) == 0)
15571         return buf - begin;
15572     }
15573 }
15574
15575 static void
15576 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15577 {
15578   switch (lang)
15579     {
15580     case DW_LANG_C89:
15581     case DW_LANG_C99:
15582     case DW_LANG_C:
15583     case DW_LANG_UPC:
15584       cu->language = language_c;
15585       break;
15586     case DW_LANG_C_plus_plus:
15587       cu->language = language_cplus;
15588       break;
15589     case DW_LANG_D:
15590       cu->language = language_d;
15591       break;
15592     case DW_LANG_Fortran77:
15593     case DW_LANG_Fortran90:
15594     case DW_LANG_Fortran95:
15595       cu->language = language_fortran;
15596       break;
15597     case DW_LANG_Go:
15598       cu->language = language_go;
15599       break;
15600     case DW_LANG_Mips_Assembler:
15601       cu->language = language_asm;
15602       break;
15603     case DW_LANG_Java:
15604       cu->language = language_java;
15605       break;
15606     case DW_LANG_Ada83:
15607     case DW_LANG_Ada95:
15608       cu->language = language_ada;
15609       break;
15610     case DW_LANG_Modula2:
15611       cu->language = language_m2;
15612       break;
15613     case DW_LANG_Pascal83:
15614       cu->language = language_pascal;
15615       break;
15616     case DW_LANG_ObjC:
15617       cu->language = language_objc;
15618       break;
15619     case DW_LANG_Cobol74:
15620     case DW_LANG_Cobol85:
15621     default:
15622       cu->language = language_minimal;
15623       break;
15624     }
15625   cu->language_defn = language_def (cu->language);
15626 }
15627
15628 /* Return the named attribute or NULL if not there.  */
15629
15630 static struct attribute *
15631 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15632 {
15633   for (;;)
15634     {
15635       unsigned int i;
15636       struct attribute *spec = NULL;
15637
15638       for (i = 0; i < die->num_attrs; ++i)
15639         {
15640           if (die->attrs[i].name == name)
15641             return &die->attrs[i];
15642           if (die->attrs[i].name == DW_AT_specification
15643               || die->attrs[i].name == DW_AT_abstract_origin)
15644             spec = &die->attrs[i];
15645         }
15646
15647       if (!spec)
15648         break;
15649
15650       die = follow_die_ref (die, spec, &cu);
15651     }
15652
15653   return NULL;
15654 }
15655
15656 /* Return the named attribute or NULL if not there,
15657    but do not follow DW_AT_specification, etc.
15658    This is for use in contexts where we're reading .debug_types dies.
15659    Following DW_AT_specification, DW_AT_abstract_origin will take us
15660    back up the chain, and we want to go down.  */
15661
15662 static struct attribute *
15663 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15664 {
15665   unsigned int i;
15666
15667   for (i = 0; i < die->num_attrs; ++i)
15668     if (die->attrs[i].name == name)
15669       return &die->attrs[i];
15670
15671   return NULL;
15672 }
15673
15674 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15675    and holds a non-zero value.  This function should only be used for
15676    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15677
15678 static int
15679 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15680 {
15681   struct attribute *attr = dwarf2_attr (die, name, cu);
15682
15683   return (attr && DW_UNSND (attr));
15684 }
15685
15686 static int
15687 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15688 {
15689   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15690      which value is non-zero.  However, we have to be careful with
15691      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15692      (via dwarf2_flag_true_p) follows this attribute.  So we may
15693      end up accidently finding a declaration attribute that belongs
15694      to a different DIE referenced by the specification attribute,
15695      even though the given DIE does not have a declaration attribute.  */
15696   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15697           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15698 }
15699
15700 /* Return the die giving the specification for DIE, if there is
15701    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15702    containing the return value on output.  If there is no
15703    specification, but there is an abstract origin, that is
15704    returned.  */
15705
15706 static struct die_info *
15707 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15708 {
15709   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15710                                              *spec_cu);
15711
15712   if (spec_attr == NULL)
15713     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15714
15715   if (spec_attr == NULL)
15716     return NULL;
15717   else
15718     return follow_die_ref (die, spec_attr, spec_cu);
15719 }
15720
15721 /* Free the line_header structure *LH, and any arrays and strings it
15722    refers to.
15723    NOTE: This is also used as a "cleanup" function.  */
15724
15725 static void
15726 free_line_header (struct line_header *lh)
15727 {
15728   if (lh->standard_opcode_lengths)
15729     xfree (lh->standard_opcode_lengths);
15730
15731   /* Remember that all the lh->file_names[i].name pointers are
15732      pointers into debug_line_buffer, and don't need to be freed.  */
15733   if (lh->file_names)
15734     xfree (lh->file_names);
15735
15736   /* Similarly for the include directory names.  */
15737   if (lh->include_dirs)
15738     xfree (lh->include_dirs);
15739
15740   xfree (lh);
15741 }
15742
15743 /* Add an entry to LH's include directory table.  */
15744
15745 static void
15746 add_include_dir (struct line_header *lh, const char *include_dir)
15747 {
15748   /* Grow the array if necessary.  */
15749   if (lh->include_dirs_size == 0)
15750     {
15751       lh->include_dirs_size = 1; /* for testing */
15752       lh->include_dirs = xmalloc (lh->include_dirs_size
15753                                   * sizeof (*lh->include_dirs));
15754     }
15755   else if (lh->num_include_dirs >= lh->include_dirs_size)
15756     {
15757       lh->include_dirs_size *= 2;
15758       lh->include_dirs = xrealloc (lh->include_dirs,
15759                                    (lh->include_dirs_size
15760                                     * sizeof (*lh->include_dirs)));
15761     }
15762
15763   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15764 }
15765
15766 /* Add an entry to LH's file name table.  */
15767
15768 static void
15769 add_file_name (struct line_header *lh,
15770                const char *name,
15771                unsigned int dir_index,
15772                unsigned int mod_time,
15773                unsigned int length)
15774 {
15775   struct file_entry *fe;
15776
15777   /* Grow the array if necessary.  */
15778   if (lh->file_names_size == 0)
15779     {
15780       lh->file_names_size = 1; /* for testing */
15781       lh->file_names = xmalloc (lh->file_names_size
15782                                 * sizeof (*lh->file_names));
15783     }
15784   else if (lh->num_file_names >= lh->file_names_size)
15785     {
15786       lh->file_names_size *= 2;
15787       lh->file_names = xrealloc (lh->file_names,
15788                                  (lh->file_names_size
15789                                   * sizeof (*lh->file_names)));
15790     }
15791
15792   fe = &lh->file_names[lh->num_file_names++];
15793   fe->name = name;
15794   fe->dir_index = dir_index;
15795   fe->mod_time = mod_time;
15796   fe->length = length;
15797   fe->included_p = 0;
15798   fe->symtab = NULL;
15799 }
15800
15801 /* A convenience function to find the proper .debug_line section for a
15802    CU.  */
15803
15804 static struct dwarf2_section_info *
15805 get_debug_line_section (struct dwarf2_cu *cu)
15806 {
15807   struct dwarf2_section_info *section;
15808
15809   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15810      DWO file.  */
15811   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15812     section = &cu->dwo_unit->dwo_file->sections.line;
15813   else if (cu->per_cu->is_dwz)
15814     {
15815       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15816
15817       section = &dwz->line;
15818     }
15819   else
15820     section = &dwarf2_per_objfile->line;
15821
15822   return section;
15823 }
15824
15825 /* Read the statement program header starting at OFFSET in
15826    .debug_line, or .debug_line.dwo.  Return a pointer
15827    to a struct line_header, allocated using xmalloc.
15828
15829    NOTE: the strings in the include directory and file name tables of
15830    the returned object point into the dwarf line section buffer,
15831    and must not be freed.  */
15832
15833 static struct line_header *
15834 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15835 {
15836   struct cleanup *back_to;
15837   struct line_header *lh;
15838   const gdb_byte *line_ptr;
15839   unsigned int bytes_read, offset_size;
15840   int i;
15841   const char *cur_dir, *cur_file;
15842   struct dwarf2_section_info *section;
15843   bfd *abfd;
15844
15845   section = get_debug_line_section (cu);
15846   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15847   if (section->buffer == NULL)
15848     {
15849       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15850         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15851       else
15852         complaint (&symfile_complaints, _("missing .debug_line section"));
15853       return 0;
15854     }
15855
15856   /* We can't do this until we know the section is non-empty.
15857      Only then do we know we have such a section.  */
15858   abfd = get_section_bfd_owner (section);
15859
15860   /* Make sure that at least there's room for the total_length field.
15861      That could be 12 bytes long, but we're just going to fudge that.  */
15862   if (offset + 4 >= section->size)
15863     {
15864       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15865       return 0;
15866     }
15867
15868   lh = xmalloc (sizeof (*lh));
15869   memset (lh, 0, sizeof (*lh));
15870   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15871                           (void *) lh);
15872
15873   line_ptr = section->buffer + offset;
15874
15875   /* Read in the header.  */
15876   lh->total_length =
15877     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15878                                             &bytes_read, &offset_size);
15879   line_ptr += bytes_read;
15880   if (line_ptr + lh->total_length > (section->buffer + section->size))
15881     {
15882       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15883       do_cleanups (back_to);
15884       return 0;
15885     }
15886   lh->statement_program_end = line_ptr + lh->total_length;
15887   lh->version = read_2_bytes (abfd, line_ptr);
15888   line_ptr += 2;
15889   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15890   line_ptr += offset_size;
15891   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15892   line_ptr += 1;
15893   if (lh->version >= 4)
15894     {
15895       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15896       line_ptr += 1;
15897     }
15898   else
15899     lh->maximum_ops_per_instruction = 1;
15900
15901   if (lh->maximum_ops_per_instruction == 0)
15902     {
15903       lh->maximum_ops_per_instruction = 1;
15904       complaint (&symfile_complaints,
15905                  _("invalid maximum_ops_per_instruction "
15906                    "in `.debug_line' section"));
15907     }
15908
15909   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15910   line_ptr += 1;
15911   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15912   line_ptr += 1;
15913   lh->line_range = read_1_byte (abfd, line_ptr);
15914   line_ptr += 1;
15915   lh->opcode_base = read_1_byte (abfd, line_ptr);
15916   line_ptr += 1;
15917   lh->standard_opcode_lengths
15918     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15919
15920   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15921   for (i = 1; i < lh->opcode_base; ++i)
15922     {
15923       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15924       line_ptr += 1;
15925     }
15926
15927   /* Read directory table.  */
15928   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15929     {
15930       line_ptr += bytes_read;
15931       add_include_dir (lh, cur_dir);
15932     }
15933   line_ptr += bytes_read;
15934
15935   /* Read file name table.  */
15936   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15937     {
15938       unsigned int dir_index, mod_time, length;
15939
15940       line_ptr += bytes_read;
15941       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15942       line_ptr += bytes_read;
15943       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15944       line_ptr += bytes_read;
15945       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15946       line_ptr += bytes_read;
15947
15948       add_file_name (lh, cur_file, dir_index, mod_time, length);
15949     }
15950   line_ptr += bytes_read;
15951   lh->statement_program_start = line_ptr;
15952
15953   if (line_ptr > (section->buffer + section->size))
15954     complaint (&symfile_complaints,
15955                _("line number info header doesn't "
15956                  "fit in `.debug_line' section"));
15957
15958   discard_cleanups (back_to);
15959   return lh;
15960 }
15961
15962 /* Subroutine of dwarf_decode_lines to simplify it.
15963    Return the file name of the psymtab for included file FILE_INDEX
15964    in line header LH of PST.
15965    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15966    If space for the result is malloc'd, it will be freed by a cleanup.
15967    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15968
15969    The function creates dangling cleanup registration.  */
15970
15971 static const char *
15972 psymtab_include_file_name (const struct line_header *lh, int file_index,
15973                            const struct partial_symtab *pst,
15974                            const char *comp_dir)
15975 {
15976   const struct file_entry fe = lh->file_names [file_index];
15977   const char *include_name = fe.name;
15978   const char *include_name_to_compare = include_name;
15979   const char *dir_name = NULL;
15980   const char *pst_filename;
15981   char *copied_name = NULL;
15982   int file_is_pst;
15983
15984   if (fe.dir_index)
15985     dir_name = lh->include_dirs[fe.dir_index - 1];
15986
15987   if (!IS_ABSOLUTE_PATH (include_name)
15988       && (dir_name != NULL || comp_dir != NULL))
15989     {
15990       /* Avoid creating a duplicate psymtab for PST.
15991          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15992          Before we do the comparison, however, we need to account
15993          for DIR_NAME and COMP_DIR.
15994          First prepend dir_name (if non-NULL).  If we still don't
15995          have an absolute path prepend comp_dir (if non-NULL).
15996          However, the directory we record in the include-file's
15997          psymtab does not contain COMP_DIR (to match the
15998          corresponding symtab(s)).
15999
16000          Example:
16001
16002          bash$ cd /tmp
16003          bash$ gcc -g ./hello.c
16004          include_name = "hello.c"
16005          dir_name = "."
16006          DW_AT_comp_dir = comp_dir = "/tmp"
16007          DW_AT_name = "./hello.c"  */
16008
16009       if (dir_name != NULL)
16010         {
16011           char *tem = concat (dir_name, SLASH_STRING,
16012                               include_name, (char *)NULL);
16013
16014           make_cleanup (xfree, tem);
16015           include_name = tem;
16016           include_name_to_compare = include_name;
16017         }
16018       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
16019         {
16020           char *tem = concat (comp_dir, SLASH_STRING,
16021                               include_name, (char *)NULL);
16022
16023           make_cleanup (xfree, tem);
16024           include_name_to_compare = tem;
16025         }
16026     }
16027
16028   pst_filename = pst->filename;
16029   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
16030     {
16031       copied_name = concat (pst->dirname, SLASH_STRING,
16032                             pst_filename, (char *)NULL);
16033       pst_filename = copied_name;
16034     }
16035
16036   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
16037
16038   if (copied_name != NULL)
16039     xfree (copied_name);
16040
16041   if (file_is_pst)
16042     return NULL;
16043   return include_name;
16044 }
16045
16046 /* Ignore this record_line request.  */
16047
16048 static void
16049 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
16050 {
16051   return;
16052 }
16053
16054 /* Subroutine of dwarf_decode_lines to simplify it.
16055    Process the line number information in LH.  */
16056
16057 static void
16058 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
16059                       struct dwarf2_cu *cu, struct partial_symtab *pst)
16060 {
16061   const gdb_byte *line_ptr, *extended_end;
16062   const gdb_byte *line_end;
16063   unsigned int bytes_read, extended_len;
16064   unsigned char op_code, extended_op, adj_opcode;
16065   CORE_ADDR baseaddr;
16066   struct objfile *objfile = cu->objfile;
16067   bfd *abfd = objfile->obfd;
16068   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16069   const int decode_for_pst_p = (pst != NULL);
16070   struct subfile *last_subfile = NULL;
16071   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
16072     = record_line;
16073
16074   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16075
16076   line_ptr = lh->statement_program_start;
16077   line_end = lh->statement_program_end;
16078
16079   /* Read the statement sequences until there's nothing left.  */
16080   while (line_ptr < line_end)
16081     {
16082       /* state machine registers  */
16083       CORE_ADDR address = 0;
16084       unsigned int file = 1;
16085       unsigned int line = 1;
16086       unsigned int column = 0;
16087       int is_stmt = lh->default_is_stmt;
16088       int basic_block = 0;
16089       int end_sequence = 0;
16090       CORE_ADDR addr;
16091       unsigned char op_index = 0;
16092
16093       if (!decode_for_pst_p && lh->num_file_names >= file)
16094         {
16095           /* Start a subfile for the current file of the state machine.  */
16096           /* lh->include_dirs and lh->file_names are 0-based, but the
16097              directory and file name numbers in the statement program
16098              are 1-based.  */
16099           struct file_entry *fe = &lh->file_names[file - 1];
16100           const char *dir = NULL;
16101
16102           if (fe->dir_index)
16103             dir = lh->include_dirs[fe->dir_index - 1];
16104
16105           dwarf2_start_subfile (fe->name, dir, comp_dir);
16106         }
16107
16108       /* Decode the table.  */
16109       while (!end_sequence)
16110         {
16111           op_code = read_1_byte (abfd, line_ptr);
16112           line_ptr += 1;
16113           if (line_ptr > line_end)
16114             {
16115               dwarf2_debug_line_missing_end_sequence_complaint ();
16116               break;
16117             }
16118
16119           if (op_code >= lh->opcode_base)
16120             {
16121               /* Special operand.  */
16122               adj_opcode = op_code - lh->opcode_base;
16123               address += (((op_index + (adj_opcode / lh->line_range))
16124                            / lh->maximum_ops_per_instruction)
16125                           * lh->minimum_instruction_length);
16126               op_index = ((op_index + (adj_opcode / lh->line_range))
16127                           % lh->maximum_ops_per_instruction);
16128               line += lh->line_base + (adj_opcode % lh->line_range);
16129               if (lh->num_file_names < file || file == 0)
16130                 dwarf2_debug_line_missing_file_complaint ();
16131               /* For now we ignore lines not starting on an
16132                  instruction boundary.  */
16133               else if (op_index == 0)
16134                 {
16135                   lh->file_names[file - 1].included_p = 1;
16136                   if (!decode_for_pst_p && is_stmt)
16137                     {
16138                       if (last_subfile != current_subfile)
16139                         {
16140                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16141                           if (last_subfile)
16142                             (*p_record_line) (last_subfile, 0, addr);
16143                           last_subfile = current_subfile;
16144                         }
16145                       /* Append row to matrix using current values.  */
16146                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16147                       (*p_record_line) (current_subfile, line, addr);
16148                     }
16149                 }
16150               basic_block = 0;
16151             }
16152           else switch (op_code)
16153             {
16154             case DW_LNS_extended_op:
16155               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16156                                                    &bytes_read);
16157               line_ptr += bytes_read;
16158               extended_end = line_ptr + extended_len;
16159               extended_op = read_1_byte (abfd, line_ptr);
16160               line_ptr += 1;
16161               switch (extended_op)
16162                 {
16163                 case DW_LNE_end_sequence:
16164                   p_record_line = record_line;
16165                   end_sequence = 1;
16166                   break;
16167                 case DW_LNE_set_address:
16168                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16169
16170                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16171                     {
16172                       /* This line table is for a function which has been
16173                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16174
16175                       long line_offset
16176                         = line_ptr - get_debug_line_section (cu)->buffer;
16177
16178                       complaint (&symfile_complaints,
16179                                  _(".debug_line address at offset 0x%lx is 0 "
16180                                    "[in module %s]"),
16181                                  line_offset, objfile_name (objfile));
16182                       p_record_line = noop_record_line;
16183                     }
16184
16185                   op_index = 0;
16186                   line_ptr += bytes_read;
16187                   address += baseaddr;
16188                   break;
16189                 case DW_LNE_define_file:
16190                   {
16191                     const char *cur_file;
16192                     unsigned int dir_index, mod_time, length;
16193
16194                     cur_file = read_direct_string (abfd, line_ptr,
16195                                                    &bytes_read);
16196                     line_ptr += bytes_read;
16197                     dir_index =
16198                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16199                     line_ptr += bytes_read;
16200                     mod_time =
16201                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16202                     line_ptr += bytes_read;
16203                     length =
16204                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16205                     line_ptr += bytes_read;
16206                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16207                   }
16208                   break;
16209                 case DW_LNE_set_discriminator:
16210                   /* The discriminator is not interesting to the debugger;
16211                      just ignore it.  */
16212                   line_ptr = extended_end;
16213                   break;
16214                 default:
16215                   complaint (&symfile_complaints,
16216                              _("mangled .debug_line section"));
16217                   return;
16218                 }
16219               /* Make sure that we parsed the extended op correctly.  If e.g.
16220                  we expected a different address size than the producer used,
16221                  we may have read the wrong number of bytes.  */
16222               if (line_ptr != extended_end)
16223                 {
16224                   complaint (&symfile_complaints,
16225                              _("mangled .debug_line section"));
16226                   return;
16227                 }
16228               break;
16229             case DW_LNS_copy:
16230               if (lh->num_file_names < file || file == 0)
16231                 dwarf2_debug_line_missing_file_complaint ();
16232               else
16233                 {
16234                   lh->file_names[file - 1].included_p = 1;
16235                   if (!decode_for_pst_p && is_stmt)
16236                     {
16237                       if (last_subfile != current_subfile)
16238                         {
16239                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16240                           if (last_subfile)
16241                             (*p_record_line) (last_subfile, 0, addr);
16242                           last_subfile = current_subfile;
16243                         }
16244                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16245                       (*p_record_line) (current_subfile, line, addr);
16246                     }
16247                 }
16248               basic_block = 0;
16249               break;
16250             case DW_LNS_advance_pc:
16251               {
16252                 CORE_ADDR adjust
16253                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16254
16255                 address += (((op_index + adjust)
16256                              / lh->maximum_ops_per_instruction)
16257                             * lh->minimum_instruction_length);
16258                 op_index = ((op_index + adjust)
16259                             % lh->maximum_ops_per_instruction);
16260                 line_ptr += bytes_read;
16261               }
16262               break;
16263             case DW_LNS_advance_line:
16264               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16265               line_ptr += bytes_read;
16266               break;
16267             case DW_LNS_set_file:
16268               {
16269                 /* The arrays lh->include_dirs and lh->file_names are
16270                    0-based, but the directory and file name numbers in
16271                    the statement program are 1-based.  */
16272                 struct file_entry *fe;
16273                 const char *dir = NULL;
16274
16275                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16276                 line_ptr += bytes_read;
16277                 if (lh->num_file_names < file || file == 0)
16278                   dwarf2_debug_line_missing_file_complaint ();
16279                 else
16280                   {
16281                     fe = &lh->file_names[file - 1];
16282                     if (fe->dir_index)
16283                       dir = lh->include_dirs[fe->dir_index - 1];
16284                     if (!decode_for_pst_p)
16285                       {
16286                         last_subfile = current_subfile;
16287                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16288                       }
16289                   }
16290               }
16291               break;
16292             case DW_LNS_set_column:
16293               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16294               line_ptr += bytes_read;
16295               break;
16296             case DW_LNS_negate_stmt:
16297               is_stmt = (!is_stmt);
16298               break;
16299             case DW_LNS_set_basic_block:
16300               basic_block = 1;
16301               break;
16302             /* Add to the address register of the state machine the
16303                address increment value corresponding to special opcode
16304                255.  I.e., this value is scaled by the minimum
16305                instruction length since special opcode 255 would have
16306                scaled the increment.  */
16307             case DW_LNS_const_add_pc:
16308               {
16309                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16310
16311                 address += (((op_index + adjust)
16312                              / lh->maximum_ops_per_instruction)
16313                             * lh->minimum_instruction_length);
16314                 op_index = ((op_index + adjust)
16315                             % lh->maximum_ops_per_instruction);
16316               }
16317               break;
16318             case DW_LNS_fixed_advance_pc:
16319               address += read_2_bytes (abfd, line_ptr);
16320               op_index = 0;
16321               line_ptr += 2;
16322               break;
16323             default:
16324               {
16325                 /* Unknown standard opcode, ignore it.  */
16326                 int i;
16327
16328                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16329                   {
16330                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16331                     line_ptr += bytes_read;
16332                   }
16333               }
16334             }
16335         }
16336       if (lh->num_file_names < file || file == 0)
16337         dwarf2_debug_line_missing_file_complaint ();
16338       else
16339         {
16340           lh->file_names[file - 1].included_p = 1;
16341           if (!decode_for_pst_p)
16342             {
16343               addr = gdbarch_addr_bits_remove (gdbarch, address);
16344               (*p_record_line) (current_subfile, 0, addr);
16345             }
16346         }
16347     }
16348 }
16349
16350 /* Decode the Line Number Program (LNP) for the given line_header
16351    structure and CU.  The actual information extracted and the type
16352    of structures created from the LNP depends on the value of PST.
16353
16354    1. If PST is NULL, then this procedure uses the data from the program
16355       to create all necessary symbol tables, and their linetables.
16356
16357    2. If PST is not NULL, this procedure reads the program to determine
16358       the list of files included by the unit represented by PST, and
16359       builds all the associated partial symbol tables.
16360
16361    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16362    It is used for relative paths in the line table.
16363    NOTE: When processing partial symtabs (pst != NULL),
16364    comp_dir == pst->dirname.
16365
16366    NOTE: It is important that psymtabs have the same file name (via strcmp)
16367    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16368    symtab we don't use it in the name of the psymtabs we create.
16369    E.g. expand_line_sal requires this when finding psymtabs to expand.
16370    A good testcase for this is mb-inline.exp.  */
16371
16372 static void
16373 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16374                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16375                     int want_line_info)
16376 {
16377   struct objfile *objfile = cu->objfile;
16378   const int decode_for_pst_p = (pst != NULL);
16379   struct subfile *first_subfile = current_subfile;
16380
16381   if (want_line_info)
16382     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16383
16384   if (decode_for_pst_p)
16385     {
16386       int file_index;
16387
16388       /* Now that we're done scanning the Line Header Program, we can
16389          create the psymtab of each included file.  */
16390       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16391         if (lh->file_names[file_index].included_p == 1)
16392           {
16393             const char *include_name =
16394               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16395             if (include_name != NULL)
16396               dwarf2_create_include_psymtab (include_name, pst, objfile);
16397           }
16398     }
16399   else
16400     {
16401       /* Make sure a symtab is created for every file, even files
16402          which contain only variables (i.e. no code with associated
16403          line numbers).  */
16404       int i;
16405
16406       for (i = 0; i < lh->num_file_names; i++)
16407         {
16408           const char *dir = NULL;
16409           struct file_entry *fe;
16410
16411           fe = &lh->file_names[i];
16412           if (fe->dir_index)
16413             dir = lh->include_dirs[fe->dir_index - 1];
16414           dwarf2_start_subfile (fe->name, dir, comp_dir);
16415
16416           /* Skip the main file; we don't need it, and it must be
16417              allocated last, so that it will show up before the
16418              non-primary symtabs in the objfile's symtab list.  */
16419           if (current_subfile == first_subfile)
16420             continue;
16421
16422           if (current_subfile->symtab == NULL)
16423             current_subfile->symtab = allocate_symtab (current_subfile->name,
16424                                                        objfile);
16425           fe->symtab = current_subfile->symtab;
16426         }
16427     }
16428 }
16429
16430 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16431    DIRNAME the name of the source directory which contains FILENAME
16432    or NULL if not known.  COMP_DIR is the compilation directory for the
16433    linetable's compilation unit or NULL if not known.
16434    This routine tries to keep line numbers from identical absolute and
16435    relative file names in a common subfile.
16436
16437    Using the `list' example from the GDB testsuite, which resides in
16438    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16439    of /srcdir/list0.c yields the following debugging information for list0.c:
16440
16441    DW_AT_name:          /srcdir/list0.c
16442    DW_AT_comp_dir:              /compdir
16443    files.files[0].name: list0.h
16444    files.files[0].dir:  /srcdir
16445    files.files[1].name: list0.c
16446    files.files[1].dir:  /srcdir
16447
16448    The line number information for list0.c has to end up in a single
16449    subfile, so that `break /srcdir/list0.c:1' works as expected.
16450    start_subfile will ensure that this happens provided that we pass the
16451    concatenation of files.files[1].dir and files.files[1].name as the
16452    subfile's name.  */
16453
16454 static void
16455 dwarf2_start_subfile (const char *filename, const char *dirname,
16456                       const char *comp_dir)
16457 {
16458   char *copy = NULL;
16459
16460   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16461      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16462      second argument to start_subfile.  To be consistent, we do the
16463      same here.  In order not to lose the line information directory,
16464      we concatenate it to the filename when it makes sense.
16465      Note that the Dwarf3 standard says (speaking of filenames in line
16466      information): ``The directory index is ignored for file names
16467      that represent full path names''.  Thus ignoring dirname in the
16468      `else' branch below isn't an issue.  */
16469
16470   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16471     {
16472       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16473       filename = copy;
16474     }
16475
16476   start_subfile (filename, comp_dir);
16477
16478   if (copy != NULL)
16479     xfree (copy);
16480 }
16481
16482 /* Start a symtab for DWARF.
16483    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16484
16485 static void
16486 dwarf2_start_symtab (struct dwarf2_cu *cu,
16487                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16488 {
16489   start_symtab (name, comp_dir, low_pc);
16490   record_debugformat ("DWARF 2");
16491   record_producer (cu->producer);
16492
16493   /* We assume that we're processing GCC output.  */
16494   processing_gcc_compilation = 2;
16495
16496   cu->processing_has_namespace_info = 0;
16497 }
16498
16499 static void
16500 var_decode_location (struct attribute *attr, struct symbol *sym,
16501                      struct dwarf2_cu *cu)
16502 {
16503   struct objfile *objfile = cu->objfile;
16504   struct comp_unit_head *cu_header = &cu->header;
16505
16506   /* NOTE drow/2003-01-30: There used to be a comment and some special
16507      code here to turn a symbol with DW_AT_external and a
16508      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16509      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16510      with some versions of binutils) where shared libraries could have
16511      relocations against symbols in their debug information - the
16512      minimal symbol would have the right address, but the debug info
16513      would not.  It's no longer necessary, because we will explicitly
16514      apply relocations when we read in the debug information now.  */
16515
16516   /* A DW_AT_location attribute with no contents indicates that a
16517      variable has been optimized away.  */
16518   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16519     {
16520       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16521       return;
16522     }
16523
16524   /* Handle one degenerate form of location expression specially, to
16525      preserve GDB's previous behavior when section offsets are
16526      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16527      then mark this symbol as LOC_STATIC.  */
16528
16529   if (attr_form_is_block (attr)
16530       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16531            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16532           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16533               && (DW_BLOCK (attr)->size
16534                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16535     {
16536       unsigned int dummy;
16537
16538       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16539         SYMBOL_VALUE_ADDRESS (sym) =
16540           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16541       else
16542         SYMBOL_VALUE_ADDRESS (sym) =
16543           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16544       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16545       fixup_symbol_section (sym, objfile);
16546       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16547                                               SYMBOL_SECTION (sym));
16548       return;
16549     }
16550
16551   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16552      expression evaluator, and use LOC_COMPUTED only when necessary
16553      (i.e. when the value of a register or memory location is
16554      referenced, or a thread-local block, etc.).  Then again, it might
16555      not be worthwhile.  I'm assuming that it isn't unless performance
16556      or memory numbers show me otherwise.  */
16557
16558   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16559
16560   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16561     cu->has_loclist = 1;
16562 }
16563
16564 /* Given a pointer to a DWARF information entry, figure out if we need
16565    to make a symbol table entry for it, and if so, create a new entry
16566    and return a pointer to it.
16567    If TYPE is NULL, determine symbol type from the die, otherwise
16568    used the passed type.
16569    If SPACE is not NULL, use it to hold the new symbol.  If it is
16570    NULL, allocate a new symbol on the objfile's obstack.  */
16571
16572 static struct symbol *
16573 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16574                  struct symbol *space)
16575 {
16576   struct objfile *objfile = cu->objfile;
16577   struct symbol *sym = NULL;
16578   const char *name;
16579   struct attribute *attr = NULL;
16580   struct attribute *attr2 = NULL;
16581   CORE_ADDR baseaddr;
16582   struct pending **list_to_add = NULL;
16583
16584   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16585
16586   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16587
16588   name = dwarf2_name (die, cu);
16589   if (name)
16590     {
16591       const char *linkagename;
16592       int suppress_add = 0;
16593
16594       if (space)
16595         sym = space;
16596       else
16597         sym = allocate_symbol (objfile);
16598       OBJSTAT (objfile, n_syms++);
16599
16600       /* Cache this symbol's name and the name's demangled form (if any).  */
16601       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16602       linkagename = dwarf2_physname (name, die, cu);
16603       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16604
16605       /* Fortran does not have mangling standard and the mangling does differ
16606          between gfortran, iFort etc.  */
16607       if (cu->language == language_fortran
16608           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16609         symbol_set_demangled_name (&(sym->ginfo),
16610                                    dwarf2_full_name (name, die, cu),
16611                                    NULL);
16612
16613       /* Default assumptions.
16614          Use the passed type or decode it from the die.  */
16615       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16616       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16617       if (type != NULL)
16618         SYMBOL_TYPE (sym) = type;
16619       else
16620         SYMBOL_TYPE (sym) = die_type (die, cu);
16621       attr = dwarf2_attr (die,
16622                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16623                           cu);
16624       if (attr)
16625         {
16626           SYMBOL_LINE (sym) = DW_UNSND (attr);
16627         }
16628
16629       attr = dwarf2_attr (die,
16630                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16631                           cu);
16632       if (attr)
16633         {
16634           int file_index = DW_UNSND (attr);
16635
16636           if (cu->line_header == NULL
16637               || file_index > cu->line_header->num_file_names)
16638             complaint (&symfile_complaints,
16639                        _("file index out of range"));
16640           else if (file_index > 0)
16641             {
16642               struct file_entry *fe;
16643
16644               fe = &cu->line_header->file_names[file_index - 1];
16645               SYMBOL_SYMTAB (sym) = fe->symtab;
16646             }
16647         }
16648
16649       switch (die->tag)
16650         {
16651         case DW_TAG_label:
16652           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16653           if (attr)
16654             {
16655               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16656             }
16657           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16658           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16659           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16660           add_symbol_to_list (sym, cu->list_in_scope);
16661           break;
16662         case DW_TAG_subprogram:
16663           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16664              finish_block.  */
16665           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16666           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16667           if ((attr2 && (DW_UNSND (attr2) != 0))
16668               || cu->language == language_ada)
16669             {
16670               /* Subprograms marked external are stored as a global symbol.
16671                  Ada subprograms, whether marked external or not, are always
16672                  stored as a global symbol, because we want to be able to
16673                  access them globally.  For instance, we want to be able
16674                  to break on a nested subprogram without having to
16675                  specify the context.  */
16676               list_to_add = &global_symbols;
16677             }
16678           else
16679             {
16680               list_to_add = cu->list_in_scope;
16681             }
16682           break;
16683         case DW_TAG_inlined_subroutine:
16684           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16685              finish_block.  */
16686           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16687           SYMBOL_INLINED (sym) = 1;
16688           list_to_add = cu->list_in_scope;
16689           break;
16690         case DW_TAG_template_value_param:
16691           suppress_add = 1;
16692           /* Fall through.  */
16693         case DW_TAG_constant:
16694         case DW_TAG_variable:
16695         case DW_TAG_member:
16696           /* Compilation with minimal debug info may result in
16697              variables with missing type entries.  Change the
16698              misleading `void' type to something sensible.  */
16699           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16700             SYMBOL_TYPE (sym)
16701               = objfile_type (objfile)->nodebug_data_symbol;
16702
16703           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16704           /* In the case of DW_TAG_member, we should only be called for
16705              static const members.  */
16706           if (die->tag == DW_TAG_member)
16707             {
16708               /* dwarf2_add_field uses die_is_declaration,
16709                  so we do the same.  */
16710               gdb_assert (die_is_declaration (die, cu));
16711               gdb_assert (attr);
16712             }
16713           if (attr)
16714             {
16715               dwarf2_const_value (attr, sym, cu);
16716               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16717               if (!suppress_add)
16718                 {
16719                   if (attr2 && (DW_UNSND (attr2) != 0))
16720                     list_to_add = &global_symbols;
16721                   else
16722                     list_to_add = cu->list_in_scope;
16723                 }
16724               break;
16725             }
16726           attr = dwarf2_attr (die, DW_AT_location, cu);
16727           if (attr)
16728             {
16729               var_decode_location (attr, sym, cu);
16730               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16731
16732               /* Fortran explicitly imports any global symbols to the local
16733                  scope by DW_TAG_common_block.  */
16734               if (cu->language == language_fortran && die->parent
16735                   && die->parent->tag == DW_TAG_common_block)
16736                 attr2 = NULL;
16737
16738               if (SYMBOL_CLASS (sym) == LOC_STATIC
16739                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16740                   && !dwarf2_per_objfile->has_section_at_zero)
16741                 {
16742                   /* When a static variable is eliminated by the linker,
16743                      the corresponding debug information is not stripped
16744                      out, but the variable address is set to null;
16745                      do not add such variables into symbol table.  */
16746                 }
16747               else if (attr2 && (DW_UNSND (attr2) != 0))
16748                 {
16749                   /* Workaround gfortran PR debug/40040 - it uses
16750                      DW_AT_location for variables in -fPIC libraries which may
16751                      get overriden by other libraries/executable and get
16752                      a different address.  Resolve it by the minimal symbol
16753                      which may come from inferior's executable using copy
16754                      relocation.  Make this workaround only for gfortran as for
16755                      other compilers GDB cannot guess the minimal symbol
16756                      Fortran mangling kind.  */
16757                   if (cu->language == language_fortran && die->parent
16758                       && die->parent->tag == DW_TAG_module
16759                       && cu->producer
16760                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16761                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16762
16763                   /* A variable with DW_AT_external is never static,
16764                      but it may be block-scoped.  */
16765                   list_to_add = (cu->list_in_scope == &file_symbols
16766                                  ? &global_symbols : cu->list_in_scope);
16767                 }
16768               else
16769                 list_to_add = cu->list_in_scope;
16770             }
16771           else
16772             {
16773               /* We do not know the address of this symbol.
16774                  If it is an external symbol and we have type information
16775                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16776                  The address of the variable will then be determined from
16777                  the minimal symbol table whenever the variable is
16778                  referenced.  */
16779               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16780
16781               /* Fortran explicitly imports any global symbols to the local
16782                  scope by DW_TAG_common_block.  */
16783               if (cu->language == language_fortran && die->parent
16784                   && die->parent->tag == DW_TAG_common_block)
16785                 {
16786                   /* SYMBOL_CLASS doesn't matter here because
16787                      read_common_block is going to reset it.  */
16788                   if (!suppress_add)
16789                     list_to_add = cu->list_in_scope;
16790                 }
16791               else if (attr2 && (DW_UNSND (attr2) != 0)
16792                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16793                 {
16794                   /* A variable with DW_AT_external is never static, but it
16795                      may be block-scoped.  */
16796                   list_to_add = (cu->list_in_scope == &file_symbols
16797                                  ? &global_symbols : cu->list_in_scope);
16798
16799                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16800                 }
16801               else if (!die_is_declaration (die, cu))
16802                 {
16803                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16804                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16805                   if (!suppress_add)
16806                     list_to_add = cu->list_in_scope;
16807                 }
16808             }
16809           break;
16810         case DW_TAG_formal_parameter:
16811           /* If we are inside a function, mark this as an argument.  If
16812              not, we might be looking at an argument to an inlined function
16813              when we do not have enough information to show inlined frames;
16814              pretend it's a local variable in that case so that the user can
16815              still see it.  */
16816           if (context_stack_depth > 0
16817               && context_stack[context_stack_depth - 1].name != NULL)
16818             SYMBOL_IS_ARGUMENT (sym) = 1;
16819           attr = dwarf2_attr (die, DW_AT_location, cu);
16820           if (attr)
16821             {
16822               var_decode_location (attr, sym, cu);
16823             }
16824           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16825           if (attr)
16826             {
16827               dwarf2_const_value (attr, sym, cu);
16828             }
16829
16830           list_to_add = cu->list_in_scope;
16831           break;
16832         case DW_TAG_unspecified_parameters:
16833           /* From varargs functions; gdb doesn't seem to have any
16834              interest in this information, so just ignore it for now.
16835              (FIXME?) */
16836           break;
16837         case DW_TAG_template_type_param:
16838           suppress_add = 1;
16839           /* Fall through.  */
16840         case DW_TAG_class_type:
16841         case DW_TAG_interface_type:
16842         case DW_TAG_structure_type:
16843         case DW_TAG_union_type:
16844         case DW_TAG_set_type:
16845         case DW_TAG_enumeration_type:
16846           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16847           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16848
16849           {
16850             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16851                really ever be static objects: otherwise, if you try
16852                to, say, break of a class's method and you're in a file
16853                which doesn't mention that class, it won't work unless
16854                the check for all static symbols in lookup_symbol_aux
16855                saves you.  See the OtherFileClass tests in
16856                gdb.c++/namespace.exp.  */
16857
16858             if (!suppress_add)
16859               {
16860                 list_to_add = (cu->list_in_scope == &file_symbols
16861                                && (cu->language == language_cplus
16862                                    || cu->language == language_java)
16863                                ? &global_symbols : cu->list_in_scope);
16864
16865                 /* The semantics of C++ state that "struct foo {
16866                    ... }" also defines a typedef for "foo".  A Java
16867                    class declaration also defines a typedef for the
16868                    class.  */
16869                 if (cu->language == language_cplus
16870                     || cu->language == language_java
16871                     || cu->language == language_ada)
16872                   {
16873                     /* The symbol's name is already allocated along
16874                        with this objfile, so we don't need to
16875                        duplicate it for the type.  */
16876                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16877                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16878                   }
16879               }
16880           }
16881           break;
16882         case DW_TAG_typedef:
16883           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16884           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16885           list_to_add = cu->list_in_scope;
16886           break;
16887         case DW_TAG_base_type:
16888         case DW_TAG_subrange_type:
16889           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16890           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16891           list_to_add = cu->list_in_scope;
16892           break;
16893         case DW_TAG_enumerator:
16894           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16895           if (attr)
16896             {
16897               dwarf2_const_value (attr, sym, cu);
16898             }
16899           {
16900             /* NOTE: carlton/2003-11-10: See comment above in the
16901                DW_TAG_class_type, etc. block.  */
16902
16903             list_to_add = (cu->list_in_scope == &file_symbols
16904                            && (cu->language == language_cplus
16905                                || cu->language == language_java)
16906                            ? &global_symbols : cu->list_in_scope);
16907           }
16908           break;
16909         case DW_TAG_namespace:
16910           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16911           list_to_add = &global_symbols;
16912           break;
16913         case DW_TAG_common_block:
16914           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16915           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16916           add_symbol_to_list (sym, cu->list_in_scope);
16917           break;
16918         default:
16919           /* Not a tag we recognize.  Hopefully we aren't processing
16920              trash data, but since we must specifically ignore things
16921              we don't recognize, there is nothing else we should do at
16922              this point.  */
16923           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16924                      dwarf_tag_name (die->tag));
16925           break;
16926         }
16927
16928       if (suppress_add)
16929         {
16930           sym->hash_next = objfile->template_symbols;
16931           objfile->template_symbols = sym;
16932           list_to_add = NULL;
16933         }
16934
16935       if (list_to_add != NULL)
16936         add_symbol_to_list (sym, list_to_add);
16937
16938       /* For the benefit of old versions of GCC, check for anonymous
16939          namespaces based on the demangled name.  */
16940       if (!cu->processing_has_namespace_info
16941           && cu->language == language_cplus)
16942         cp_scan_for_anonymous_namespaces (sym, objfile);
16943     }
16944   return (sym);
16945 }
16946
16947 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16948
16949 static struct symbol *
16950 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16951 {
16952   return new_symbol_full (die, type, cu, NULL);
16953 }
16954
16955 /* Given an attr with a DW_FORM_dataN value in host byte order,
16956    zero-extend it as appropriate for the symbol's type.  The DWARF
16957    standard (v4) is not entirely clear about the meaning of using
16958    DW_FORM_dataN for a constant with a signed type, where the type is
16959    wider than the data.  The conclusion of a discussion on the DWARF
16960    list was that this is unspecified.  We choose to always zero-extend
16961    because that is the interpretation long in use by GCC.  */
16962
16963 static gdb_byte *
16964 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
16965                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16966 {
16967   struct objfile *objfile = cu->objfile;
16968   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16969                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16970   LONGEST l = DW_UNSND (attr);
16971
16972   if (bits < sizeof (*value) * 8)
16973     {
16974       l &= ((LONGEST) 1 << bits) - 1;
16975       *value = l;
16976     }
16977   else if (bits == sizeof (*value) * 8)
16978     *value = l;
16979   else
16980     {
16981       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16982       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16983       return bytes;
16984     }
16985
16986   return NULL;
16987 }
16988
16989 /* Read a constant value from an attribute.  Either set *VALUE, or if
16990    the value does not fit in *VALUE, set *BYTES - either already
16991    allocated on the objfile obstack, or newly allocated on OBSTACK,
16992    or, set *BATON, if we translated the constant to a location
16993    expression.  */
16994
16995 static void
16996 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
16997                          const char *name, struct obstack *obstack,
16998                          struct dwarf2_cu *cu,
16999                          LONGEST *value, const gdb_byte **bytes,
17000                          struct dwarf2_locexpr_baton **baton)
17001 {
17002   struct objfile *objfile = cu->objfile;
17003   struct comp_unit_head *cu_header = &cu->header;
17004   struct dwarf_block *blk;
17005   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
17006                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
17007
17008   *value = 0;
17009   *bytes = NULL;
17010   *baton = NULL;
17011
17012   switch (attr->form)
17013     {
17014     case DW_FORM_addr:
17015     case DW_FORM_GNU_addr_index:
17016       {
17017         gdb_byte *data;
17018
17019         if (TYPE_LENGTH (type) != cu_header->addr_size)
17020           dwarf2_const_value_length_mismatch_complaint (name,
17021                                                         cu_header->addr_size,
17022                                                         TYPE_LENGTH (type));
17023         /* Symbols of this form are reasonably rare, so we just
17024            piggyback on the existing location code rather than writing
17025            a new implementation of symbol_computed_ops.  */
17026         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
17027         (*baton)->per_cu = cu->per_cu;
17028         gdb_assert ((*baton)->per_cu);
17029
17030         (*baton)->size = 2 + cu_header->addr_size;
17031         data = obstack_alloc (obstack, (*baton)->size);
17032         (*baton)->data = data;
17033
17034         data[0] = DW_OP_addr;
17035         store_unsigned_integer (&data[1], cu_header->addr_size,
17036                                 byte_order, DW_ADDR (attr));
17037         data[cu_header->addr_size + 1] = DW_OP_stack_value;
17038       }
17039       break;
17040     case DW_FORM_string:
17041     case DW_FORM_strp:
17042     case DW_FORM_GNU_str_index:
17043     case DW_FORM_GNU_strp_alt:
17044       /* DW_STRING is already allocated on the objfile obstack, point
17045          directly to it.  */
17046       *bytes = (const gdb_byte *) DW_STRING (attr);
17047       break;
17048     case DW_FORM_block1:
17049     case DW_FORM_block2:
17050     case DW_FORM_block4:
17051     case DW_FORM_block:
17052     case DW_FORM_exprloc:
17053       blk = DW_BLOCK (attr);
17054       if (TYPE_LENGTH (type) != blk->size)
17055         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
17056                                                       TYPE_LENGTH (type));
17057       *bytes = blk->data;
17058       break;
17059
17060       /* The DW_AT_const_value attributes are supposed to carry the
17061          symbol's value "represented as it would be on the target
17062          architecture."  By the time we get here, it's already been
17063          converted to host endianness, so we just need to sign- or
17064          zero-extend it as appropriate.  */
17065     case DW_FORM_data1:
17066       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
17067       break;
17068     case DW_FORM_data2:
17069       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
17070       break;
17071     case DW_FORM_data4:
17072       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
17073       break;
17074     case DW_FORM_data8:
17075       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
17076       break;
17077
17078     case DW_FORM_sdata:
17079       *value = DW_SND (attr);
17080       break;
17081
17082     case DW_FORM_udata:
17083       *value = DW_UNSND (attr);
17084       break;
17085
17086     default:
17087       complaint (&symfile_complaints,
17088                  _("unsupported const value attribute form: '%s'"),
17089                  dwarf_form_name (attr->form));
17090       *value = 0;
17091       break;
17092     }
17093 }
17094
17095
17096 /* Copy constant value from an attribute to a symbol.  */
17097
17098 static void
17099 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17100                     struct dwarf2_cu *cu)
17101 {
17102   struct objfile *objfile = cu->objfile;
17103   struct comp_unit_head *cu_header = &cu->header;
17104   LONGEST value;
17105   const gdb_byte *bytes;
17106   struct dwarf2_locexpr_baton *baton;
17107
17108   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17109                            SYMBOL_PRINT_NAME (sym),
17110                            &objfile->objfile_obstack, cu,
17111                            &value, &bytes, &baton);
17112
17113   if (baton != NULL)
17114     {
17115       SYMBOL_LOCATION_BATON (sym) = baton;
17116       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17117     }
17118   else if (bytes != NULL)
17119      {
17120       SYMBOL_VALUE_BYTES (sym) = bytes;
17121       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17122     }
17123   else
17124     {
17125       SYMBOL_VALUE (sym) = value;
17126       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17127     }
17128 }
17129
17130 /* Return the type of the die in question using its DW_AT_type attribute.  */
17131
17132 static struct type *
17133 die_type (struct die_info *die, struct dwarf2_cu *cu)
17134 {
17135   struct attribute *type_attr;
17136
17137   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17138   if (!type_attr)
17139     {
17140       /* A missing DW_AT_type represents a void type.  */
17141       return objfile_type (cu->objfile)->builtin_void;
17142     }
17143
17144   return lookup_die_type (die, type_attr, cu);
17145 }
17146
17147 /* True iff CU's producer generates GNAT Ada auxiliary information
17148    that allows to find parallel types through that information instead
17149    of having to do expensive parallel lookups by type name.  */
17150
17151 static int
17152 need_gnat_info (struct dwarf2_cu *cu)
17153 {
17154   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17155      of GNAT produces this auxiliary information, without any indication
17156      that it is produced.  Part of enhancing the FSF version of GNAT
17157      to produce that information will be to put in place an indicator
17158      that we can use in order to determine whether the descriptive type
17159      info is available or not.  One suggestion that has been made is
17160      to use a new attribute, attached to the CU die.  For now, assume
17161      that the descriptive type info is not available.  */
17162   return 0;
17163 }
17164
17165 /* Return the auxiliary type of the die in question using its
17166    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17167    attribute is not present.  */
17168
17169 static struct type *
17170 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17171 {
17172   struct attribute *type_attr;
17173
17174   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17175   if (!type_attr)
17176     return NULL;
17177
17178   return lookup_die_type (die, type_attr, cu);
17179 }
17180
17181 /* If DIE has a descriptive_type attribute, then set the TYPE's
17182    descriptive type accordingly.  */
17183
17184 static void
17185 set_descriptive_type (struct type *type, struct die_info *die,
17186                       struct dwarf2_cu *cu)
17187 {
17188   struct type *descriptive_type = die_descriptive_type (die, cu);
17189
17190   if (descriptive_type)
17191     {
17192       ALLOCATE_GNAT_AUX_TYPE (type);
17193       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17194     }
17195 }
17196
17197 /* Return the containing type of the die in question using its
17198    DW_AT_containing_type attribute.  */
17199
17200 static struct type *
17201 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17202 {
17203   struct attribute *type_attr;
17204
17205   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17206   if (!type_attr)
17207     error (_("Dwarf Error: Problem turning containing type into gdb type "
17208              "[in module %s]"), objfile_name (cu->objfile));
17209
17210   return lookup_die_type (die, type_attr, cu);
17211 }
17212
17213 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17214
17215 static struct type *
17216 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17217 {
17218   struct objfile *objfile = dwarf2_per_objfile->objfile;
17219   char *message, *saved;
17220
17221   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17222                         objfile_name (objfile),
17223                         cu->header.offset.sect_off,
17224                         die->offset.sect_off);
17225   saved = obstack_copy0 (&objfile->objfile_obstack,
17226                          message, strlen (message));
17227   xfree (message);
17228
17229   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17230 }
17231
17232 /* Look up the type of DIE in CU using its type attribute ATTR.
17233    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17234    DW_AT_containing_type.
17235    If there is no type substitute an error marker.  */
17236
17237 static struct type *
17238 lookup_die_type (struct die_info *die, const struct attribute *attr,
17239                  struct dwarf2_cu *cu)
17240 {
17241   struct objfile *objfile = cu->objfile;
17242   struct type *this_type;
17243
17244   gdb_assert (attr->name == DW_AT_type
17245               || attr->name == DW_AT_GNAT_descriptive_type
17246               || attr->name == DW_AT_containing_type);
17247
17248   /* First see if we have it cached.  */
17249
17250   if (attr->form == DW_FORM_GNU_ref_alt)
17251     {
17252       struct dwarf2_per_cu_data *per_cu;
17253       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17254
17255       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17256       this_type = get_die_type_at_offset (offset, per_cu);
17257     }
17258   else if (attr_form_is_ref (attr))
17259     {
17260       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17261
17262       this_type = get_die_type_at_offset (offset, cu->per_cu);
17263     }
17264   else if (attr->form == DW_FORM_ref_sig8)
17265     {
17266       ULONGEST signature = DW_SIGNATURE (attr);
17267
17268       return get_signatured_type (die, signature, cu);
17269     }
17270   else
17271     {
17272       complaint (&symfile_complaints,
17273                  _("Dwarf Error: Bad type attribute %s in DIE"
17274                    " at 0x%x [in module %s]"),
17275                  dwarf_attr_name (attr->name), die->offset.sect_off,
17276                  objfile_name (objfile));
17277       return build_error_marker_type (cu, die);
17278     }
17279
17280   /* If not cached we need to read it in.  */
17281
17282   if (this_type == NULL)
17283     {
17284       struct die_info *type_die = NULL;
17285       struct dwarf2_cu *type_cu = cu;
17286
17287       if (attr_form_is_ref (attr))
17288         type_die = follow_die_ref (die, attr, &type_cu);
17289       if (type_die == NULL)
17290         return build_error_marker_type (cu, die);
17291       /* If we find the type now, it's probably because the type came
17292          from an inter-CU reference and the type's CU got expanded before
17293          ours.  */
17294       this_type = read_type_die (type_die, type_cu);
17295     }
17296
17297   /* If we still don't have a type use an error marker.  */
17298
17299   if (this_type == NULL)
17300     return build_error_marker_type (cu, die);
17301
17302   return this_type;
17303 }
17304
17305 /* Return the type in DIE, CU.
17306    Returns NULL for invalid types.
17307
17308    This first does a lookup in die_type_hash,
17309    and only reads the die in if necessary.
17310
17311    NOTE: This can be called when reading in partial or full symbols.  */
17312
17313 static struct type *
17314 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17315 {
17316   struct type *this_type;
17317
17318   this_type = get_die_type (die, cu);
17319   if (this_type)
17320     return this_type;
17321
17322   return read_type_die_1 (die, cu);
17323 }
17324
17325 /* Read the type in DIE, CU.
17326    Returns NULL for invalid types.  */
17327
17328 static struct type *
17329 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17330 {
17331   struct type *this_type = NULL;
17332
17333   switch (die->tag)
17334     {
17335     case DW_TAG_class_type:
17336     case DW_TAG_interface_type:
17337     case DW_TAG_structure_type:
17338     case DW_TAG_union_type:
17339       this_type = read_structure_type (die, cu);
17340       break;
17341     case DW_TAG_enumeration_type:
17342       this_type = read_enumeration_type (die, cu);
17343       break;
17344     case DW_TAG_subprogram:
17345     case DW_TAG_subroutine_type:
17346     case DW_TAG_inlined_subroutine:
17347       this_type = read_subroutine_type (die, cu);
17348       break;
17349     case DW_TAG_array_type:
17350       this_type = read_array_type (die, cu);
17351       break;
17352     case DW_TAG_set_type:
17353       this_type = read_set_type (die, cu);
17354       break;
17355     case DW_TAG_pointer_type:
17356       this_type = read_tag_pointer_type (die, cu);
17357       break;
17358     case DW_TAG_ptr_to_member_type:
17359       this_type = read_tag_ptr_to_member_type (die, cu);
17360       break;
17361     case DW_TAG_reference_type:
17362       this_type = read_tag_reference_type (die, cu);
17363       break;
17364     case DW_TAG_const_type:
17365       this_type = read_tag_const_type (die, cu);
17366       break;
17367     case DW_TAG_volatile_type:
17368       this_type = read_tag_volatile_type (die, cu);
17369       break;
17370     case DW_TAG_restrict_type:
17371       this_type = read_tag_restrict_type (die, cu);
17372       break;
17373     case DW_TAG_string_type:
17374       this_type = read_tag_string_type (die, cu);
17375       break;
17376     case DW_TAG_typedef:
17377       this_type = read_typedef (die, cu);
17378       break;
17379     case DW_TAG_subrange_type:
17380       this_type = read_subrange_type (die, cu);
17381       break;
17382     case DW_TAG_base_type:
17383       this_type = read_base_type (die, cu);
17384       break;
17385     case DW_TAG_unspecified_type:
17386       this_type = read_unspecified_type (die, cu);
17387       break;
17388     case DW_TAG_namespace:
17389       this_type = read_namespace_type (die, cu);
17390       break;
17391     case DW_TAG_module:
17392       this_type = read_module_type (die, cu);
17393       break;
17394     default:
17395       complaint (&symfile_complaints,
17396                  _("unexpected tag in read_type_die: '%s'"),
17397                  dwarf_tag_name (die->tag));
17398       break;
17399     }
17400
17401   return this_type;
17402 }
17403
17404 /* See if we can figure out if the class lives in a namespace.  We do
17405    this by looking for a member function; its demangled name will
17406    contain namespace info, if there is any.
17407    Return the computed name or NULL.
17408    Space for the result is allocated on the objfile's obstack.
17409    This is the full-die version of guess_partial_die_structure_name.
17410    In this case we know DIE has no useful parent.  */
17411
17412 static char *
17413 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17414 {
17415   struct die_info *spec_die;
17416   struct dwarf2_cu *spec_cu;
17417   struct die_info *child;
17418
17419   spec_cu = cu;
17420   spec_die = die_specification (die, &spec_cu);
17421   if (spec_die != NULL)
17422     {
17423       die = spec_die;
17424       cu = spec_cu;
17425     }
17426
17427   for (child = die->child;
17428        child != NULL;
17429        child = child->sibling)
17430     {
17431       if (child->tag == DW_TAG_subprogram)
17432         {
17433           struct attribute *attr;
17434
17435           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17436           if (attr == NULL)
17437             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17438           if (attr != NULL)
17439             {
17440               char *actual_name
17441                 = language_class_name_from_physname (cu->language_defn,
17442                                                      DW_STRING (attr));
17443               char *name = NULL;
17444
17445               if (actual_name != NULL)
17446                 {
17447                   const char *die_name = dwarf2_name (die, cu);
17448
17449                   if (die_name != NULL
17450                       && strcmp (die_name, actual_name) != 0)
17451                     {
17452                       /* Strip off the class name from the full name.
17453                          We want the prefix.  */
17454                       int die_name_len = strlen (die_name);
17455                       int actual_name_len = strlen (actual_name);
17456
17457                       /* Test for '::' as a sanity check.  */
17458                       if (actual_name_len > die_name_len + 2
17459                           && actual_name[actual_name_len
17460                                          - die_name_len - 1] == ':')
17461                         name =
17462                           obstack_copy0 (&cu->objfile->objfile_obstack,
17463                                          actual_name,
17464                                          actual_name_len - die_name_len - 2);
17465                     }
17466                 }
17467               xfree (actual_name);
17468               return name;
17469             }
17470         }
17471     }
17472
17473   return NULL;
17474 }
17475
17476 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17477    prefix part in such case.  See
17478    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17479
17480 static char *
17481 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17482 {
17483   struct attribute *attr;
17484   char *base;
17485
17486   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17487       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17488     return NULL;
17489
17490   attr = dwarf2_attr (die, DW_AT_name, cu);
17491   if (attr != NULL && DW_STRING (attr) != NULL)
17492     return NULL;
17493
17494   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17495   if (attr == NULL)
17496     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17497   if (attr == NULL || DW_STRING (attr) == NULL)
17498     return NULL;
17499
17500   /* dwarf2_name had to be already called.  */
17501   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17502
17503   /* Strip the base name, keep any leading namespaces/classes.  */
17504   base = strrchr (DW_STRING (attr), ':');
17505   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17506     return "";
17507
17508   return obstack_copy0 (&cu->objfile->objfile_obstack,
17509                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17510 }
17511
17512 /* Return the name of the namespace/class that DIE is defined within,
17513    or "" if we can't tell.  The caller should not xfree the result.
17514
17515    For example, if we're within the method foo() in the following
17516    code:
17517
17518    namespace N {
17519      class C {
17520        void foo () {
17521        }
17522      };
17523    }
17524
17525    then determine_prefix on foo's die will return "N::C".  */
17526
17527 static const char *
17528 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17529 {
17530   struct die_info *parent, *spec_die;
17531   struct dwarf2_cu *spec_cu;
17532   struct type *parent_type;
17533   char *retval;
17534
17535   if (cu->language != language_cplus && cu->language != language_java
17536       && cu->language != language_fortran)
17537     return "";
17538
17539   retval = anonymous_struct_prefix (die, cu);
17540   if (retval)
17541     return retval;
17542
17543   /* We have to be careful in the presence of DW_AT_specification.
17544      For example, with GCC 3.4, given the code
17545
17546      namespace N {
17547        void foo() {
17548          // Definition of N::foo.
17549        }
17550      }
17551
17552      then we'll have a tree of DIEs like this:
17553
17554      1: DW_TAG_compile_unit
17555        2: DW_TAG_namespace        // N
17556          3: DW_TAG_subprogram     // declaration of N::foo
17557        4: DW_TAG_subprogram       // definition of N::foo
17558             DW_AT_specification   // refers to die #3
17559
17560      Thus, when processing die #4, we have to pretend that we're in
17561      the context of its DW_AT_specification, namely the contex of die
17562      #3.  */
17563   spec_cu = cu;
17564   spec_die = die_specification (die, &spec_cu);
17565   if (spec_die == NULL)
17566     parent = die->parent;
17567   else
17568     {
17569       parent = spec_die->parent;
17570       cu = spec_cu;
17571     }
17572
17573   if (parent == NULL)
17574     return "";
17575   else if (parent->building_fullname)
17576     {
17577       const char *name;
17578       const char *parent_name;
17579
17580       /* It has been seen on RealView 2.2 built binaries,
17581          DW_TAG_template_type_param types actually _defined_ as
17582          children of the parent class:
17583
17584          enum E {};
17585          template class <class Enum> Class{};
17586          Class<enum E> class_e;
17587
17588          1: DW_TAG_class_type (Class)
17589            2: DW_TAG_enumeration_type (E)
17590              3: DW_TAG_enumerator (enum1:0)
17591              3: DW_TAG_enumerator (enum2:1)
17592              ...
17593            2: DW_TAG_template_type_param
17594               DW_AT_type  DW_FORM_ref_udata (E)
17595
17596          Besides being broken debug info, it can put GDB into an
17597          infinite loop.  Consider:
17598
17599          When we're building the full name for Class<E>, we'll start
17600          at Class, and go look over its template type parameters,
17601          finding E.  We'll then try to build the full name of E, and
17602          reach here.  We're now trying to build the full name of E,
17603          and look over the parent DIE for containing scope.  In the
17604          broken case, if we followed the parent DIE of E, we'd again
17605          find Class, and once again go look at its template type
17606          arguments, etc., etc.  Simply don't consider such parent die
17607          as source-level parent of this die (it can't be, the language
17608          doesn't allow it), and break the loop here.  */
17609       name = dwarf2_name (die, cu);
17610       parent_name = dwarf2_name (parent, cu);
17611       complaint (&symfile_complaints,
17612                  _("template param type '%s' defined within parent '%s'"),
17613                  name ? name : "<unknown>",
17614                  parent_name ? parent_name : "<unknown>");
17615       return "";
17616     }
17617   else
17618     switch (parent->tag)
17619       {
17620       case DW_TAG_namespace:
17621         parent_type = read_type_die (parent, cu);
17622         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17623            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17624            Work around this problem here.  */
17625         if (cu->language == language_cplus
17626             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17627           return "";
17628         /* We give a name to even anonymous namespaces.  */
17629         return TYPE_TAG_NAME (parent_type);
17630       case DW_TAG_class_type:
17631       case DW_TAG_interface_type:
17632       case DW_TAG_structure_type:
17633       case DW_TAG_union_type:
17634       case DW_TAG_module:
17635         parent_type = read_type_die (parent, cu);
17636         if (TYPE_TAG_NAME (parent_type) != NULL)
17637           return TYPE_TAG_NAME (parent_type);
17638         else
17639           /* An anonymous structure is only allowed non-static data
17640              members; no typedefs, no member functions, et cetera.
17641              So it does not need a prefix.  */
17642           return "";
17643       case DW_TAG_compile_unit:
17644       case DW_TAG_partial_unit:
17645         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17646         if (cu->language == language_cplus
17647             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17648             && die->child != NULL
17649             && (die->tag == DW_TAG_class_type
17650                 || die->tag == DW_TAG_structure_type
17651                 || die->tag == DW_TAG_union_type))
17652           {
17653             char *name = guess_full_die_structure_name (die, cu);
17654             if (name != NULL)
17655               return name;
17656           }
17657         return "";
17658       default:
17659         return determine_prefix (parent, cu);
17660       }
17661 }
17662
17663 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17664    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17665    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17666    an obconcat, otherwise allocate storage for the result.  The CU argument is
17667    used to determine the language and hence, the appropriate separator.  */
17668
17669 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17670
17671 static char *
17672 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17673                  int physname, struct dwarf2_cu *cu)
17674 {
17675   const char *lead = "";
17676   const char *sep;
17677
17678   if (suffix == NULL || suffix[0] == '\0'
17679       || prefix == NULL || prefix[0] == '\0')
17680     sep = "";
17681   else if (cu->language == language_java)
17682     sep = ".";
17683   else if (cu->language == language_fortran && physname)
17684     {
17685       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17686          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17687
17688       lead = "__";
17689       sep = "_MOD_";
17690     }
17691   else
17692     sep = "::";
17693
17694   if (prefix == NULL)
17695     prefix = "";
17696   if (suffix == NULL)
17697     suffix = "";
17698
17699   if (obs == NULL)
17700     {
17701       char *retval
17702         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17703
17704       strcpy (retval, lead);
17705       strcat (retval, prefix);
17706       strcat (retval, sep);
17707       strcat (retval, suffix);
17708       return retval;
17709     }
17710   else
17711     {
17712       /* We have an obstack.  */
17713       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17714     }
17715 }
17716
17717 /* Return sibling of die, NULL if no sibling.  */
17718
17719 static struct die_info *
17720 sibling_die (struct die_info *die)
17721 {
17722   return die->sibling;
17723 }
17724
17725 /* Get name of a die, return NULL if not found.  */
17726
17727 static const char *
17728 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17729                           struct obstack *obstack)
17730 {
17731   if (name && cu->language == language_cplus)
17732     {
17733       char *canon_name = cp_canonicalize_string (name);
17734
17735       if (canon_name != NULL)
17736         {
17737           if (strcmp (canon_name, name) != 0)
17738             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17739           xfree (canon_name);
17740         }
17741     }
17742
17743   return name;
17744 }
17745
17746 /* Get name of a die, return NULL if not found.  */
17747
17748 static const char *
17749 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17750 {
17751   struct attribute *attr;
17752
17753   attr = dwarf2_attr (die, DW_AT_name, cu);
17754   if ((!attr || !DW_STRING (attr))
17755       && die->tag != DW_TAG_class_type
17756       && die->tag != DW_TAG_interface_type
17757       && die->tag != DW_TAG_structure_type
17758       && die->tag != DW_TAG_union_type)
17759     return NULL;
17760
17761   switch (die->tag)
17762     {
17763     case DW_TAG_compile_unit:
17764     case DW_TAG_partial_unit:
17765       /* Compilation units have a DW_AT_name that is a filename, not
17766          a source language identifier.  */
17767     case DW_TAG_enumeration_type:
17768     case DW_TAG_enumerator:
17769       /* These tags always have simple identifiers already; no need
17770          to canonicalize them.  */
17771       return DW_STRING (attr);
17772
17773     case DW_TAG_subprogram:
17774       /* Java constructors will all be named "<init>", so return
17775          the class name when we see this special case.  */
17776       if (cu->language == language_java
17777           && DW_STRING (attr) != NULL
17778           && strcmp (DW_STRING (attr), "<init>") == 0)
17779         {
17780           struct dwarf2_cu *spec_cu = cu;
17781           struct die_info *spec_die;
17782
17783           /* GCJ will output '<init>' for Java constructor names.
17784              For this special case, return the name of the parent class.  */
17785
17786           /* GCJ may output suprogram DIEs with AT_specification set.
17787              If so, use the name of the specified DIE.  */
17788           spec_die = die_specification (die, &spec_cu);
17789           if (spec_die != NULL)
17790             return dwarf2_name (spec_die, spec_cu);
17791
17792           do
17793             {
17794               die = die->parent;
17795               if (die->tag == DW_TAG_class_type)
17796                 return dwarf2_name (die, cu);
17797             }
17798           while (die->tag != DW_TAG_compile_unit
17799                  && die->tag != DW_TAG_partial_unit);
17800         }
17801       break;
17802
17803     case DW_TAG_class_type:
17804     case DW_TAG_interface_type:
17805     case DW_TAG_structure_type:
17806     case DW_TAG_union_type:
17807       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17808          structures or unions.  These were of the form "._%d" in GCC 4.1,
17809          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17810          and GCC 4.4.  We work around this problem by ignoring these.  */
17811       if (attr && DW_STRING (attr)
17812           && (strncmp (DW_STRING (attr), "._", 2) == 0
17813               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17814         return NULL;
17815
17816       /* GCC might emit a nameless typedef that has a linkage name.  See
17817          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17818       if (!attr || DW_STRING (attr) == NULL)
17819         {
17820           char *demangled = NULL;
17821
17822           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17823           if (attr == NULL)
17824             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17825
17826           if (attr == NULL || DW_STRING (attr) == NULL)
17827             return NULL;
17828
17829           /* Avoid demangling DW_STRING (attr) the second time on a second
17830              call for the same DIE.  */
17831           if (!DW_STRING_IS_CANONICAL (attr))
17832             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17833
17834           if (demangled)
17835             {
17836               char *base;
17837
17838               /* FIXME: we already did this for the partial symbol... */
17839               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17840                                                 demangled, strlen (demangled));
17841               DW_STRING_IS_CANONICAL (attr) = 1;
17842               xfree (demangled);
17843
17844               /* Strip any leading namespaces/classes, keep only the base name.
17845                  DW_AT_name for named DIEs does not contain the prefixes.  */
17846               base = strrchr (DW_STRING (attr), ':');
17847               if (base && base > DW_STRING (attr) && base[-1] == ':')
17848                 return &base[1];
17849               else
17850                 return DW_STRING (attr);
17851             }
17852         }
17853       break;
17854
17855     default:
17856       break;
17857     }
17858
17859   if (!DW_STRING_IS_CANONICAL (attr))
17860     {
17861       DW_STRING (attr)
17862         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17863                                     &cu->objfile->objfile_obstack);
17864       DW_STRING_IS_CANONICAL (attr) = 1;
17865     }
17866   return DW_STRING (attr);
17867 }
17868
17869 /* Return the die that this die in an extension of, or NULL if there
17870    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17871    containing the return value on output.  */
17872
17873 static struct die_info *
17874 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17875 {
17876   struct attribute *attr;
17877
17878   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17879   if (attr == NULL)
17880     return NULL;
17881
17882   return follow_die_ref (die, attr, ext_cu);
17883 }
17884
17885 /* Convert a DIE tag into its string name.  */
17886
17887 static const char *
17888 dwarf_tag_name (unsigned tag)
17889 {
17890   const char *name = get_DW_TAG_name (tag);
17891
17892   if (name == NULL)
17893     return "DW_TAG_<unknown>";
17894
17895   return name;
17896 }
17897
17898 /* Convert a DWARF attribute code into its string name.  */
17899
17900 static const char *
17901 dwarf_attr_name (unsigned attr)
17902 {
17903   const char *name;
17904
17905 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17906   if (attr == DW_AT_MIPS_fde)
17907     return "DW_AT_MIPS_fde";
17908 #else
17909   if (attr == DW_AT_HP_block_index)
17910     return "DW_AT_HP_block_index";
17911 #endif
17912
17913   name = get_DW_AT_name (attr);
17914
17915   if (name == NULL)
17916     return "DW_AT_<unknown>";
17917
17918   return name;
17919 }
17920
17921 /* Convert a DWARF value form code into its string name.  */
17922
17923 static const char *
17924 dwarf_form_name (unsigned form)
17925 {
17926   const char *name = get_DW_FORM_name (form);
17927
17928   if (name == NULL)
17929     return "DW_FORM_<unknown>";
17930
17931   return name;
17932 }
17933
17934 static char *
17935 dwarf_bool_name (unsigned mybool)
17936 {
17937   if (mybool)
17938     return "TRUE";
17939   else
17940     return "FALSE";
17941 }
17942
17943 /* Convert a DWARF type code into its string name.  */
17944
17945 static const char *
17946 dwarf_type_encoding_name (unsigned enc)
17947 {
17948   const char *name = get_DW_ATE_name (enc);
17949
17950   if (name == NULL)
17951     return "DW_ATE_<unknown>";
17952
17953   return name;
17954 }
17955
17956 static void
17957 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17958 {
17959   unsigned int i;
17960
17961   print_spaces (indent, f);
17962   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17963            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17964
17965   if (die->parent != NULL)
17966     {
17967       print_spaces (indent, f);
17968       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17969                           die->parent->offset.sect_off);
17970     }
17971
17972   print_spaces (indent, f);
17973   fprintf_unfiltered (f, "  has children: %s\n",
17974            dwarf_bool_name (die->child != NULL));
17975
17976   print_spaces (indent, f);
17977   fprintf_unfiltered (f, "  attributes:\n");
17978
17979   for (i = 0; i < die->num_attrs; ++i)
17980     {
17981       print_spaces (indent, f);
17982       fprintf_unfiltered (f, "    %s (%s) ",
17983                dwarf_attr_name (die->attrs[i].name),
17984                dwarf_form_name (die->attrs[i].form));
17985
17986       switch (die->attrs[i].form)
17987         {
17988         case DW_FORM_addr:
17989         case DW_FORM_GNU_addr_index:
17990           fprintf_unfiltered (f, "address: ");
17991           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17992           break;
17993         case DW_FORM_block2:
17994         case DW_FORM_block4:
17995         case DW_FORM_block:
17996         case DW_FORM_block1:
17997           fprintf_unfiltered (f, "block: size %s",
17998                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17999           break;
18000         case DW_FORM_exprloc:
18001           fprintf_unfiltered (f, "expression: size %s",
18002                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18003           break;
18004         case DW_FORM_ref_addr:
18005           fprintf_unfiltered (f, "ref address: ");
18006           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18007           break;
18008         case DW_FORM_GNU_ref_alt:
18009           fprintf_unfiltered (f, "alt ref address: ");
18010           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18011           break;
18012         case DW_FORM_ref1:
18013         case DW_FORM_ref2:
18014         case DW_FORM_ref4:
18015         case DW_FORM_ref8:
18016         case DW_FORM_ref_udata:
18017           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
18018                               (long) (DW_UNSND (&die->attrs[i])));
18019           break;
18020         case DW_FORM_data1:
18021         case DW_FORM_data2:
18022         case DW_FORM_data4:
18023         case DW_FORM_data8:
18024         case DW_FORM_udata:
18025         case DW_FORM_sdata:
18026           fprintf_unfiltered (f, "constant: %s",
18027                               pulongest (DW_UNSND (&die->attrs[i])));
18028           break;
18029         case DW_FORM_sec_offset:
18030           fprintf_unfiltered (f, "section offset: %s",
18031                               pulongest (DW_UNSND (&die->attrs[i])));
18032           break;
18033         case DW_FORM_ref_sig8:
18034           fprintf_unfiltered (f, "signature: %s",
18035                               hex_string (DW_SIGNATURE (&die->attrs[i])));
18036           break;
18037         case DW_FORM_string:
18038         case DW_FORM_strp:
18039         case DW_FORM_GNU_str_index:
18040         case DW_FORM_GNU_strp_alt:
18041           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
18042                    DW_STRING (&die->attrs[i])
18043                    ? DW_STRING (&die->attrs[i]) : "",
18044                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
18045           break;
18046         case DW_FORM_flag:
18047           if (DW_UNSND (&die->attrs[i]))
18048             fprintf_unfiltered (f, "flag: TRUE");
18049           else
18050             fprintf_unfiltered (f, "flag: FALSE");
18051           break;
18052         case DW_FORM_flag_present:
18053           fprintf_unfiltered (f, "flag: TRUE");
18054           break;
18055         case DW_FORM_indirect:
18056           /* The reader will have reduced the indirect form to
18057              the "base form" so this form should not occur.  */
18058           fprintf_unfiltered (f, 
18059                               "unexpected attribute form: DW_FORM_indirect");
18060           break;
18061         default:
18062           fprintf_unfiltered (f, "unsupported attribute form: %d.",
18063                    die->attrs[i].form);
18064           break;
18065         }
18066       fprintf_unfiltered (f, "\n");
18067     }
18068 }
18069
18070 static void
18071 dump_die_for_error (struct die_info *die)
18072 {
18073   dump_die_shallow (gdb_stderr, 0, die);
18074 }
18075
18076 static void
18077 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
18078 {
18079   int indent = level * 4;
18080
18081   gdb_assert (die != NULL);
18082
18083   if (level >= max_level)
18084     return;
18085
18086   dump_die_shallow (f, indent, die);
18087
18088   if (die->child != NULL)
18089     {
18090       print_spaces (indent, f);
18091       fprintf_unfiltered (f, "  Children:");
18092       if (level + 1 < max_level)
18093         {
18094           fprintf_unfiltered (f, "\n");
18095           dump_die_1 (f, level + 1, max_level, die->child);
18096         }
18097       else
18098         {
18099           fprintf_unfiltered (f,
18100                               " [not printed, max nesting level reached]\n");
18101         }
18102     }
18103
18104   if (die->sibling != NULL && level > 0)
18105     {
18106       dump_die_1 (f, level, max_level, die->sibling);
18107     }
18108 }
18109
18110 /* This is called from the pdie macro in gdbinit.in.
18111    It's not static so gcc will keep a copy callable from gdb.  */
18112
18113 void
18114 dump_die (struct die_info *die, int max_level)
18115 {
18116   dump_die_1 (gdb_stdlog, 0, max_level, die);
18117 }
18118
18119 static void
18120 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18121 {
18122   void **slot;
18123
18124   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18125                                    INSERT);
18126
18127   *slot = die;
18128 }
18129
18130 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18131    required kind.  */
18132
18133 static sect_offset
18134 dwarf2_get_ref_die_offset (const struct attribute *attr)
18135 {
18136   sect_offset retval = { DW_UNSND (attr) };
18137
18138   if (attr_form_is_ref (attr))
18139     return retval;
18140
18141   retval.sect_off = 0;
18142   complaint (&symfile_complaints,
18143              _("unsupported die ref attribute form: '%s'"),
18144              dwarf_form_name (attr->form));
18145   return retval;
18146 }
18147
18148 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18149  * the value held by the attribute is not constant.  */
18150
18151 static LONGEST
18152 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18153 {
18154   if (attr->form == DW_FORM_sdata)
18155     return DW_SND (attr);
18156   else if (attr->form == DW_FORM_udata
18157            || attr->form == DW_FORM_data1
18158            || attr->form == DW_FORM_data2
18159            || attr->form == DW_FORM_data4
18160            || attr->form == DW_FORM_data8)
18161     return DW_UNSND (attr);
18162   else
18163     {
18164       complaint (&symfile_complaints,
18165                  _("Attribute value is not a constant (%s)"),
18166                  dwarf_form_name (attr->form));
18167       return default_value;
18168     }
18169 }
18170
18171 /* Follow reference or signature attribute ATTR of SRC_DIE.
18172    On entry *REF_CU is the CU of SRC_DIE.
18173    On exit *REF_CU is the CU of the result.  */
18174
18175 static struct die_info *
18176 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18177                        struct dwarf2_cu **ref_cu)
18178 {
18179   struct die_info *die;
18180
18181   if (attr_form_is_ref (attr))
18182     die = follow_die_ref (src_die, attr, ref_cu);
18183   else if (attr->form == DW_FORM_ref_sig8)
18184     die = follow_die_sig (src_die, attr, ref_cu);
18185   else
18186     {
18187       dump_die_for_error (src_die);
18188       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18189              objfile_name ((*ref_cu)->objfile));
18190     }
18191
18192   return die;
18193 }
18194
18195 /* Follow reference OFFSET.
18196    On entry *REF_CU is the CU of the source die referencing OFFSET.
18197    On exit *REF_CU is the CU of the result.
18198    Returns NULL if OFFSET is invalid.  */
18199
18200 static struct die_info *
18201 follow_die_offset (sect_offset offset, int offset_in_dwz,
18202                    struct dwarf2_cu **ref_cu)
18203 {
18204   struct die_info temp_die;
18205   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18206
18207   gdb_assert (cu->per_cu != NULL);
18208
18209   target_cu = cu;
18210
18211   if (cu->per_cu->is_debug_types)
18212     {
18213       /* .debug_types CUs cannot reference anything outside their CU.
18214          If they need to, they have to reference a signatured type via
18215          DW_FORM_ref_sig8.  */
18216       if (! offset_in_cu_p (&cu->header, offset))
18217         return NULL;
18218     }
18219   else if (offset_in_dwz != cu->per_cu->is_dwz
18220            || ! offset_in_cu_p (&cu->header, offset))
18221     {
18222       struct dwarf2_per_cu_data *per_cu;
18223
18224       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18225                                                  cu->objfile);
18226
18227       /* If necessary, add it to the queue and load its DIEs.  */
18228       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18229         load_full_comp_unit (per_cu, cu->language);
18230
18231       target_cu = per_cu->cu;
18232     }
18233   else if (cu->dies == NULL)
18234     {
18235       /* We're loading full DIEs during partial symbol reading.  */
18236       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18237       load_full_comp_unit (cu->per_cu, language_minimal);
18238     }
18239
18240   *ref_cu = target_cu;
18241   temp_die.offset = offset;
18242   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18243 }
18244
18245 /* Follow reference attribute ATTR of SRC_DIE.
18246    On entry *REF_CU is the CU of SRC_DIE.
18247    On exit *REF_CU is the CU of the result.  */
18248
18249 static struct die_info *
18250 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18251                 struct dwarf2_cu **ref_cu)
18252 {
18253   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18254   struct dwarf2_cu *cu = *ref_cu;
18255   struct die_info *die;
18256
18257   die = follow_die_offset (offset,
18258                            (attr->form == DW_FORM_GNU_ref_alt
18259                             || cu->per_cu->is_dwz),
18260                            ref_cu);
18261   if (!die)
18262     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18263            "at 0x%x [in module %s]"),
18264            offset.sect_off, src_die->offset.sect_off,
18265            objfile_name (cu->objfile));
18266
18267   return die;
18268 }
18269
18270 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18271    Returned value is intended for DW_OP_call*.  Returned
18272    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18273
18274 struct dwarf2_locexpr_baton
18275 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18276                                struct dwarf2_per_cu_data *per_cu,
18277                                CORE_ADDR (*get_frame_pc) (void *baton),
18278                                void *baton)
18279 {
18280   struct dwarf2_cu *cu;
18281   struct die_info *die;
18282   struct attribute *attr;
18283   struct dwarf2_locexpr_baton retval;
18284
18285   dw2_setup (per_cu->objfile);
18286
18287   if (per_cu->cu == NULL)
18288     load_cu (per_cu);
18289   cu = per_cu->cu;
18290
18291   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18292   if (!die)
18293     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18294            offset.sect_off, objfile_name (per_cu->objfile));
18295
18296   attr = dwarf2_attr (die, DW_AT_location, cu);
18297   if (!attr)
18298     {
18299       /* DWARF: "If there is no such attribute, then there is no effect.".
18300          DATA is ignored if SIZE is 0.  */
18301
18302       retval.data = NULL;
18303       retval.size = 0;
18304     }
18305   else if (attr_form_is_section_offset (attr))
18306     {
18307       struct dwarf2_loclist_baton loclist_baton;
18308       CORE_ADDR pc = (*get_frame_pc) (baton);
18309       size_t size;
18310
18311       fill_in_loclist_baton (cu, &loclist_baton, attr);
18312
18313       retval.data = dwarf2_find_location_expression (&loclist_baton,
18314                                                      &size, pc);
18315       retval.size = size;
18316     }
18317   else
18318     {
18319       if (!attr_form_is_block (attr))
18320         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18321                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18322                offset.sect_off, objfile_name (per_cu->objfile));
18323
18324       retval.data = DW_BLOCK (attr)->data;
18325       retval.size = DW_BLOCK (attr)->size;
18326     }
18327   retval.per_cu = cu->per_cu;
18328
18329   age_cached_comp_units ();
18330
18331   return retval;
18332 }
18333
18334 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18335    offset.  */
18336
18337 struct dwarf2_locexpr_baton
18338 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18339                              struct dwarf2_per_cu_data *per_cu,
18340                              CORE_ADDR (*get_frame_pc) (void *baton),
18341                              void *baton)
18342 {
18343   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18344
18345   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18346 }
18347
18348 /* Write a constant of a given type as target-ordered bytes into
18349    OBSTACK.  */
18350
18351 static const gdb_byte *
18352 write_constant_as_bytes (struct obstack *obstack,
18353                          enum bfd_endian byte_order,
18354                          struct type *type,
18355                          ULONGEST value,
18356                          LONGEST *len)
18357 {
18358   gdb_byte *result;
18359
18360   *len = TYPE_LENGTH (type);
18361   result = obstack_alloc (obstack, *len);
18362   store_unsigned_integer (result, *len, byte_order, value);
18363
18364   return result;
18365 }
18366
18367 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18368    pointer to the constant bytes and set LEN to the length of the
18369    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18370    does not have a DW_AT_const_value, return NULL.  */
18371
18372 const gdb_byte *
18373 dwarf2_fetch_constant_bytes (sect_offset offset,
18374                              struct dwarf2_per_cu_data *per_cu,
18375                              struct obstack *obstack,
18376                              LONGEST *len)
18377 {
18378   struct dwarf2_cu *cu;
18379   struct die_info *die;
18380   struct attribute *attr;
18381   const gdb_byte *result = NULL;
18382   struct type *type;
18383   LONGEST value;
18384   enum bfd_endian byte_order;
18385
18386   dw2_setup (per_cu->objfile);
18387
18388   if (per_cu->cu == NULL)
18389     load_cu (per_cu);
18390   cu = per_cu->cu;
18391
18392   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18393   if (!die)
18394     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18395            offset.sect_off, objfile_name (per_cu->objfile));
18396
18397
18398   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18399   if (attr == NULL)
18400     return NULL;
18401
18402   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18403                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18404
18405   switch (attr->form)
18406     {
18407     case DW_FORM_addr:
18408     case DW_FORM_GNU_addr_index:
18409       {
18410         gdb_byte *tem;
18411
18412         *len = cu->header.addr_size;
18413         tem = obstack_alloc (obstack, *len);
18414         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18415         result = tem;
18416       }
18417       break;
18418     case DW_FORM_string:
18419     case DW_FORM_strp:
18420     case DW_FORM_GNU_str_index:
18421     case DW_FORM_GNU_strp_alt:
18422       /* DW_STRING is already allocated on the objfile obstack, point
18423          directly to it.  */
18424       result = (const gdb_byte *) DW_STRING (attr);
18425       *len = strlen (DW_STRING (attr));
18426       break;
18427     case DW_FORM_block1:
18428     case DW_FORM_block2:
18429     case DW_FORM_block4:
18430     case DW_FORM_block:
18431     case DW_FORM_exprloc:
18432       result = DW_BLOCK (attr)->data;
18433       *len = DW_BLOCK (attr)->size;
18434       break;
18435
18436       /* The DW_AT_const_value attributes are supposed to carry the
18437          symbol's value "represented as it would be on the target
18438          architecture."  By the time we get here, it's already been
18439          converted to host endianness, so we just need to sign- or
18440          zero-extend it as appropriate.  */
18441     case DW_FORM_data1:
18442       type = die_type (die, cu);
18443       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18444       if (result == NULL)
18445         result = write_constant_as_bytes (obstack, byte_order,
18446                                           type, value, len);
18447       break;
18448     case DW_FORM_data2:
18449       type = die_type (die, cu);
18450       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18451       if (result == NULL)
18452         result = write_constant_as_bytes (obstack, byte_order,
18453                                           type, value, len);
18454       break;
18455     case DW_FORM_data4:
18456       type = die_type (die, cu);
18457       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18458       if (result == NULL)
18459         result = write_constant_as_bytes (obstack, byte_order,
18460                                           type, value, len);
18461       break;
18462     case DW_FORM_data8:
18463       type = die_type (die, cu);
18464       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18465       if (result == NULL)
18466         result = write_constant_as_bytes (obstack, byte_order,
18467                                           type, value, len);
18468       break;
18469
18470     case DW_FORM_sdata:
18471       type = die_type (die, cu);
18472       result = write_constant_as_bytes (obstack, byte_order,
18473                                         type, DW_SND (attr), len);
18474       break;
18475
18476     case DW_FORM_udata:
18477       type = die_type (die, cu);
18478       result = write_constant_as_bytes (obstack, byte_order,
18479                                         type, DW_UNSND (attr), len);
18480       break;
18481
18482     default:
18483       complaint (&symfile_complaints,
18484                  _("unsupported const value attribute form: '%s'"),
18485                  dwarf_form_name (attr->form));
18486       break;
18487     }
18488
18489   return result;
18490 }
18491
18492 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18493    PER_CU.  */
18494
18495 struct type *
18496 dwarf2_get_die_type (cu_offset die_offset,
18497                      struct dwarf2_per_cu_data *per_cu)
18498 {
18499   sect_offset die_offset_sect;
18500
18501   dw2_setup (per_cu->objfile);
18502
18503   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18504   return get_die_type_at_offset (die_offset_sect, per_cu);
18505 }
18506
18507 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18508    On entry *REF_CU is the CU of SRC_DIE.
18509    On exit *REF_CU is the CU of the result.
18510    Returns NULL if the referenced DIE isn't found.  */
18511
18512 static struct die_info *
18513 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18514                   struct dwarf2_cu **ref_cu)
18515 {
18516   struct objfile *objfile = (*ref_cu)->objfile;
18517   struct die_info temp_die;
18518   struct dwarf2_cu *sig_cu;
18519   struct die_info *die;
18520
18521   /* While it might be nice to assert sig_type->type == NULL here,
18522      we can get here for DW_AT_imported_declaration where we need
18523      the DIE not the type.  */
18524
18525   /* If necessary, add it to the queue and load its DIEs.  */
18526
18527   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18528     read_signatured_type (sig_type);
18529
18530   sig_cu = sig_type->per_cu.cu;
18531   gdb_assert (sig_cu != NULL);
18532   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18533   temp_die.offset = sig_type->type_offset_in_section;
18534   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18535                              temp_die.offset.sect_off);
18536   if (die)
18537     {
18538       /* For .gdb_index version 7 keep track of included TUs.
18539          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18540       if (dwarf2_per_objfile->index_table != NULL
18541           && dwarf2_per_objfile->index_table->version <= 7)
18542         {
18543           VEC_safe_push (dwarf2_per_cu_ptr,
18544                          (*ref_cu)->per_cu->imported_symtabs,
18545                          sig_cu->per_cu);
18546         }
18547
18548       *ref_cu = sig_cu;
18549       return die;
18550     }
18551
18552   return NULL;
18553 }
18554
18555 /* Follow signatured type referenced by ATTR in SRC_DIE.
18556    On entry *REF_CU is the CU of SRC_DIE.
18557    On exit *REF_CU is the CU of the result.
18558    The result is the DIE of the type.
18559    If the referenced type cannot be found an error is thrown.  */
18560
18561 static struct die_info *
18562 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
18563                 struct dwarf2_cu **ref_cu)
18564 {
18565   ULONGEST signature = DW_SIGNATURE (attr);
18566   struct signatured_type *sig_type;
18567   struct die_info *die;
18568
18569   gdb_assert (attr->form == DW_FORM_ref_sig8);
18570
18571   sig_type = lookup_signatured_type (*ref_cu, signature);
18572   /* sig_type will be NULL if the signatured type is missing from
18573      the debug info.  */
18574   if (sig_type == NULL)
18575     {
18576       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18577                " from DIE at 0x%x [in module %s]"),
18578              hex_string (signature), src_die->offset.sect_off,
18579              objfile_name ((*ref_cu)->objfile));
18580     }
18581
18582   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18583   if (die == NULL)
18584     {
18585       dump_die_for_error (src_die);
18586       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18587                " from DIE at 0x%x [in module %s]"),
18588              hex_string (signature), src_die->offset.sect_off,
18589              objfile_name ((*ref_cu)->objfile));
18590     }
18591
18592   return die;
18593 }
18594
18595 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18596    reading in and processing the type unit if necessary.  */
18597
18598 static struct type *
18599 get_signatured_type (struct die_info *die, ULONGEST signature,
18600                      struct dwarf2_cu *cu)
18601 {
18602   struct signatured_type *sig_type;
18603   struct dwarf2_cu *type_cu;
18604   struct die_info *type_die;
18605   struct type *type;
18606
18607   sig_type = lookup_signatured_type (cu, signature);
18608   /* sig_type will be NULL if the signatured type is missing from
18609      the debug info.  */
18610   if (sig_type == NULL)
18611     {
18612       complaint (&symfile_complaints,
18613                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18614                    " from DIE at 0x%x [in module %s]"),
18615                  hex_string (signature), die->offset.sect_off,
18616                  objfile_name (dwarf2_per_objfile->objfile));
18617       return build_error_marker_type (cu, die);
18618     }
18619
18620   /* If we already know the type we're done.  */
18621   if (sig_type->type != NULL)
18622     return sig_type->type;
18623
18624   type_cu = cu;
18625   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18626   if (type_die != NULL)
18627     {
18628       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18629          is created.  This is important, for example, because for c++ classes
18630          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18631       type = read_type_die (type_die, type_cu);
18632       if (type == NULL)
18633         {
18634           complaint (&symfile_complaints,
18635                      _("Dwarf Error: Cannot build signatured type %s"
18636                        " referenced from DIE at 0x%x [in module %s]"),
18637                      hex_string (signature), die->offset.sect_off,
18638                      objfile_name (dwarf2_per_objfile->objfile));
18639           type = build_error_marker_type (cu, die);
18640         }
18641     }
18642   else
18643     {
18644       complaint (&symfile_complaints,
18645                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18646                    " from DIE at 0x%x [in module %s]"),
18647                  hex_string (signature), die->offset.sect_off,
18648                  objfile_name (dwarf2_per_objfile->objfile));
18649       type = build_error_marker_type (cu, die);
18650     }
18651   sig_type->type = type;
18652
18653   return type;
18654 }
18655
18656 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18657    reading in and processing the type unit if necessary.  */
18658
18659 static struct type *
18660 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
18661                           struct dwarf2_cu *cu) /* ARI: editCase function */
18662 {
18663   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18664   if (attr_form_is_ref (attr))
18665     {
18666       struct dwarf2_cu *type_cu = cu;
18667       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18668
18669       return read_type_die (type_die, type_cu);
18670     }
18671   else if (attr->form == DW_FORM_ref_sig8)
18672     {
18673       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18674     }
18675   else
18676     {
18677       complaint (&symfile_complaints,
18678                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18679                    " at 0x%x [in module %s]"),
18680                  dwarf_form_name (attr->form), die->offset.sect_off,
18681                  objfile_name (dwarf2_per_objfile->objfile));
18682       return build_error_marker_type (cu, die);
18683     }
18684 }
18685
18686 /* Load the DIEs associated with type unit PER_CU into memory.  */
18687
18688 static void
18689 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18690 {
18691   struct signatured_type *sig_type;
18692
18693   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18694   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18695
18696   /* We have the per_cu, but we need the signatured_type.
18697      Fortunately this is an easy translation.  */
18698   gdb_assert (per_cu->is_debug_types);
18699   sig_type = (struct signatured_type *) per_cu;
18700
18701   gdb_assert (per_cu->cu == NULL);
18702
18703   read_signatured_type (sig_type);
18704
18705   gdb_assert (per_cu->cu != NULL);
18706 }
18707
18708 /* die_reader_func for read_signatured_type.
18709    This is identical to load_full_comp_unit_reader,
18710    but is kept separate for now.  */
18711
18712 static void
18713 read_signatured_type_reader (const struct die_reader_specs *reader,
18714                              const gdb_byte *info_ptr,
18715                              struct die_info *comp_unit_die,
18716                              int has_children,
18717                              void *data)
18718 {
18719   struct dwarf2_cu *cu = reader->cu;
18720
18721   gdb_assert (cu->die_hash == NULL);
18722   cu->die_hash =
18723     htab_create_alloc_ex (cu->header.length / 12,
18724                           die_hash,
18725                           die_eq,
18726                           NULL,
18727                           &cu->comp_unit_obstack,
18728                           hashtab_obstack_allocate,
18729                           dummy_obstack_deallocate);
18730
18731   if (has_children)
18732     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18733                                                   &info_ptr, comp_unit_die);
18734   cu->dies = comp_unit_die;
18735   /* comp_unit_die is not stored in die_hash, no need.  */
18736
18737   /* We try not to read any attributes in this function, because not
18738      all CUs needed for references have been loaded yet, and symbol
18739      table processing isn't initialized.  But we have to set the CU language,
18740      or we won't be able to build types correctly.
18741      Similarly, if we do not read the producer, we can not apply
18742      producer-specific interpretation.  */
18743   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18744 }
18745
18746 /* Read in a signatured type and build its CU and DIEs.
18747    If the type is a stub for the real type in a DWO file,
18748    read in the real type from the DWO file as well.  */
18749
18750 static void
18751 read_signatured_type (struct signatured_type *sig_type)
18752 {
18753   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18754
18755   gdb_assert (per_cu->is_debug_types);
18756   gdb_assert (per_cu->cu == NULL);
18757
18758   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18759                            read_signatured_type_reader, NULL);
18760   sig_type->per_cu.tu_read = 1;
18761 }
18762
18763 /* Decode simple location descriptions.
18764    Given a pointer to a dwarf block that defines a location, compute
18765    the location and return the value.
18766
18767    NOTE drow/2003-11-18: This function is called in two situations
18768    now: for the address of static or global variables (partial symbols
18769    only) and for offsets into structures which are expected to be
18770    (more or less) constant.  The partial symbol case should go away,
18771    and only the constant case should remain.  That will let this
18772    function complain more accurately.  A few special modes are allowed
18773    without complaint for global variables (for instance, global
18774    register values and thread-local values).
18775
18776    A location description containing no operations indicates that the
18777    object is optimized out.  The return value is 0 for that case.
18778    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18779    callers will only want a very basic result and this can become a
18780    complaint.
18781
18782    Note that stack[0] is unused except as a default error return.  */
18783
18784 static CORE_ADDR
18785 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18786 {
18787   struct objfile *objfile = cu->objfile;
18788   size_t i;
18789   size_t size = blk->size;
18790   const gdb_byte *data = blk->data;
18791   CORE_ADDR stack[64];
18792   int stacki;
18793   unsigned int bytes_read, unsnd;
18794   gdb_byte op;
18795
18796   i = 0;
18797   stacki = 0;
18798   stack[stacki] = 0;
18799   stack[++stacki] = 0;
18800
18801   while (i < size)
18802     {
18803       op = data[i++];
18804       switch (op)
18805         {
18806         case DW_OP_lit0:
18807         case DW_OP_lit1:
18808         case DW_OP_lit2:
18809         case DW_OP_lit3:
18810         case DW_OP_lit4:
18811         case DW_OP_lit5:
18812         case DW_OP_lit6:
18813         case DW_OP_lit7:
18814         case DW_OP_lit8:
18815         case DW_OP_lit9:
18816         case DW_OP_lit10:
18817         case DW_OP_lit11:
18818         case DW_OP_lit12:
18819         case DW_OP_lit13:
18820         case DW_OP_lit14:
18821         case DW_OP_lit15:
18822         case DW_OP_lit16:
18823         case DW_OP_lit17:
18824         case DW_OP_lit18:
18825         case DW_OP_lit19:
18826         case DW_OP_lit20:
18827         case DW_OP_lit21:
18828         case DW_OP_lit22:
18829         case DW_OP_lit23:
18830         case DW_OP_lit24:
18831         case DW_OP_lit25:
18832         case DW_OP_lit26:
18833         case DW_OP_lit27:
18834         case DW_OP_lit28:
18835         case DW_OP_lit29:
18836         case DW_OP_lit30:
18837         case DW_OP_lit31:
18838           stack[++stacki] = op - DW_OP_lit0;
18839           break;
18840
18841         case DW_OP_reg0:
18842         case DW_OP_reg1:
18843         case DW_OP_reg2:
18844         case DW_OP_reg3:
18845         case DW_OP_reg4:
18846         case DW_OP_reg5:
18847         case DW_OP_reg6:
18848         case DW_OP_reg7:
18849         case DW_OP_reg8:
18850         case DW_OP_reg9:
18851         case DW_OP_reg10:
18852         case DW_OP_reg11:
18853         case DW_OP_reg12:
18854         case DW_OP_reg13:
18855         case DW_OP_reg14:
18856         case DW_OP_reg15:
18857         case DW_OP_reg16:
18858         case DW_OP_reg17:
18859         case DW_OP_reg18:
18860         case DW_OP_reg19:
18861         case DW_OP_reg20:
18862         case DW_OP_reg21:
18863         case DW_OP_reg22:
18864         case DW_OP_reg23:
18865         case DW_OP_reg24:
18866         case DW_OP_reg25:
18867         case DW_OP_reg26:
18868         case DW_OP_reg27:
18869         case DW_OP_reg28:
18870         case DW_OP_reg29:
18871         case DW_OP_reg30:
18872         case DW_OP_reg31:
18873           stack[++stacki] = op - DW_OP_reg0;
18874           if (i < size)
18875             dwarf2_complex_location_expr_complaint ();
18876           break;
18877
18878         case DW_OP_regx:
18879           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18880           i += bytes_read;
18881           stack[++stacki] = unsnd;
18882           if (i < size)
18883             dwarf2_complex_location_expr_complaint ();
18884           break;
18885
18886         case DW_OP_addr:
18887           stack[++stacki] = read_address (objfile->obfd, &data[i],
18888                                           cu, &bytes_read);
18889           i += bytes_read;
18890           break;
18891
18892         case DW_OP_const1u:
18893           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18894           i += 1;
18895           break;
18896
18897         case DW_OP_const1s:
18898           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18899           i += 1;
18900           break;
18901
18902         case DW_OP_const2u:
18903           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18904           i += 2;
18905           break;
18906
18907         case DW_OP_const2s:
18908           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18909           i += 2;
18910           break;
18911
18912         case DW_OP_const4u:
18913           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18914           i += 4;
18915           break;
18916
18917         case DW_OP_const4s:
18918           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18919           i += 4;
18920           break;
18921
18922         case DW_OP_const8u:
18923           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18924           i += 8;
18925           break;
18926
18927         case DW_OP_constu:
18928           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18929                                                   &bytes_read);
18930           i += bytes_read;
18931           break;
18932
18933         case DW_OP_consts:
18934           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18935           i += bytes_read;
18936           break;
18937
18938         case DW_OP_dup:
18939           stack[stacki + 1] = stack[stacki];
18940           stacki++;
18941           break;
18942
18943         case DW_OP_plus:
18944           stack[stacki - 1] += stack[stacki];
18945           stacki--;
18946           break;
18947
18948         case DW_OP_plus_uconst:
18949           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18950                                                  &bytes_read);
18951           i += bytes_read;
18952           break;
18953
18954         case DW_OP_minus:
18955           stack[stacki - 1] -= stack[stacki];
18956           stacki--;
18957           break;
18958
18959         case DW_OP_deref:
18960           /* If we're not the last op, then we definitely can't encode
18961              this using GDB's address_class enum.  This is valid for partial
18962              global symbols, although the variable's address will be bogus
18963              in the psymtab.  */
18964           if (i < size)
18965             dwarf2_complex_location_expr_complaint ();
18966           break;
18967
18968         case DW_OP_GNU_push_tls_address:
18969           /* The top of the stack has the offset from the beginning
18970              of the thread control block at which the variable is located.  */
18971           /* Nothing should follow this operator, so the top of stack would
18972              be returned.  */
18973           /* This is valid for partial global symbols, but the variable's
18974              address will be bogus in the psymtab.  Make it always at least
18975              non-zero to not look as a variable garbage collected by linker
18976              which have DW_OP_addr 0.  */
18977           if (i < size)
18978             dwarf2_complex_location_expr_complaint ();
18979           stack[stacki]++;
18980           break;
18981
18982         case DW_OP_GNU_uninit:
18983           break;
18984
18985         case DW_OP_GNU_addr_index:
18986         case DW_OP_GNU_const_index:
18987           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18988                                                          &bytes_read);
18989           i += bytes_read;
18990           break;
18991
18992         default:
18993           {
18994             const char *name = get_DW_OP_name (op);
18995
18996             if (name)
18997               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18998                          name);
18999             else
19000               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
19001                          op);
19002           }
19003
19004           return (stack[stacki]);
19005         }
19006
19007       /* Enforce maximum stack depth of SIZE-1 to avoid writing
19008          outside of the allocated space.  Also enforce minimum>0.  */
19009       if (stacki >= ARRAY_SIZE (stack) - 1)
19010         {
19011           complaint (&symfile_complaints,
19012                      _("location description stack overflow"));
19013           return 0;
19014         }
19015
19016       if (stacki <= 0)
19017         {
19018           complaint (&symfile_complaints,
19019                      _("location description stack underflow"));
19020           return 0;
19021         }
19022     }
19023   return (stack[stacki]);
19024 }
19025
19026 /* memory allocation interface */
19027
19028 static struct dwarf_block *
19029 dwarf_alloc_block (struct dwarf2_cu *cu)
19030 {
19031   struct dwarf_block *blk;
19032
19033   blk = (struct dwarf_block *)
19034     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
19035   return (blk);
19036 }
19037
19038 static struct die_info *
19039 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
19040 {
19041   struct die_info *die;
19042   size_t size = sizeof (struct die_info);
19043
19044   if (num_attrs > 1)
19045     size += (num_attrs - 1) * sizeof (struct attribute);
19046
19047   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
19048   memset (die, 0, sizeof (struct die_info));
19049   return (die);
19050 }
19051
19052 \f
19053 /* Macro support.  */
19054
19055 /* Return file name relative to the compilation directory of file number I in
19056    *LH's file name table.  The result is allocated using xmalloc; the caller is
19057    responsible for freeing it.  */
19058
19059 static char *
19060 file_file_name (int file, struct line_header *lh)
19061 {
19062   /* Is the file number a valid index into the line header's file name
19063      table?  Remember that file numbers start with one, not zero.  */
19064   if (1 <= file && file <= lh->num_file_names)
19065     {
19066       struct file_entry *fe = &lh->file_names[file - 1];
19067
19068       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
19069         return xstrdup (fe->name);
19070       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
19071                      fe->name, NULL);
19072     }
19073   else
19074     {
19075       /* The compiler produced a bogus file number.  We can at least
19076          record the macro definitions made in the file, even if we
19077          won't be able to find the file by name.  */
19078       char fake_name[80];
19079
19080       xsnprintf (fake_name, sizeof (fake_name),
19081                  "<bad macro file number %d>", file);
19082
19083       complaint (&symfile_complaints,
19084                  _("bad file number in macro information (%d)"),
19085                  file);
19086
19087       return xstrdup (fake_name);
19088     }
19089 }
19090
19091 /* Return the full name of file number I in *LH's file name table.
19092    Use COMP_DIR as the name of the current directory of the
19093    compilation.  The result is allocated using xmalloc; the caller is
19094    responsible for freeing it.  */
19095 static char *
19096 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19097 {
19098   /* Is the file number a valid index into the line header's file name
19099      table?  Remember that file numbers start with one, not zero.  */
19100   if (1 <= file && file <= lh->num_file_names)
19101     {
19102       char *relative = file_file_name (file, lh);
19103
19104       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19105         return relative;
19106       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19107     }
19108   else
19109     return file_file_name (file, lh);
19110 }
19111
19112
19113 static struct macro_source_file *
19114 macro_start_file (int file, int line,
19115                   struct macro_source_file *current_file,
19116                   const char *comp_dir,
19117                   struct line_header *lh, struct objfile *objfile)
19118 {
19119   /* File name relative to the compilation directory of this source file.  */
19120   char *file_name = file_file_name (file, lh);
19121
19122   if (! current_file)
19123     {
19124       /* Note: We don't create a macro table for this compilation unit
19125          at all until we actually get a filename.  */
19126       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19127
19128       /* If we have no current file, then this must be the start_file
19129          directive for the compilation unit's main source file.  */
19130       current_file = macro_set_main (macro_table, file_name);
19131       macro_define_special (macro_table);
19132     }
19133   else
19134     current_file = macro_include (current_file, line, file_name);
19135
19136   xfree (file_name);
19137
19138   return current_file;
19139 }
19140
19141
19142 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19143    followed by a null byte.  */
19144 static char *
19145 copy_string (const char *buf, int len)
19146 {
19147   char *s = xmalloc (len + 1);
19148
19149   memcpy (s, buf, len);
19150   s[len] = '\0';
19151   return s;
19152 }
19153
19154
19155 static const char *
19156 consume_improper_spaces (const char *p, const char *body)
19157 {
19158   if (*p == ' ')
19159     {
19160       complaint (&symfile_complaints,
19161                  _("macro definition contains spaces "
19162                    "in formal argument list:\n`%s'"),
19163                  body);
19164
19165       while (*p == ' ')
19166         p++;
19167     }
19168
19169   return p;
19170 }
19171
19172
19173 static void
19174 parse_macro_definition (struct macro_source_file *file, int line,
19175                         const char *body)
19176 {
19177   const char *p;
19178
19179   /* The body string takes one of two forms.  For object-like macro
19180      definitions, it should be:
19181
19182         <macro name> " " <definition>
19183
19184      For function-like macro definitions, it should be:
19185
19186         <macro name> "() " <definition>
19187      or
19188         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19189
19190      Spaces may appear only where explicitly indicated, and in the
19191      <definition>.
19192
19193      The Dwarf 2 spec says that an object-like macro's name is always
19194      followed by a space, but versions of GCC around March 2002 omit
19195      the space when the macro's definition is the empty string.
19196
19197      The Dwarf 2 spec says that there should be no spaces between the
19198      formal arguments in a function-like macro's formal argument list,
19199      but versions of GCC around March 2002 include spaces after the
19200      commas.  */
19201
19202
19203   /* Find the extent of the macro name.  The macro name is terminated
19204      by either a space or null character (for an object-like macro) or
19205      an opening paren (for a function-like macro).  */
19206   for (p = body; *p; p++)
19207     if (*p == ' ' || *p == '(')
19208       break;
19209
19210   if (*p == ' ' || *p == '\0')
19211     {
19212       /* It's an object-like macro.  */
19213       int name_len = p - body;
19214       char *name = copy_string (body, name_len);
19215       const char *replacement;
19216
19217       if (*p == ' ')
19218         replacement = body + name_len + 1;
19219       else
19220         {
19221           dwarf2_macro_malformed_definition_complaint (body);
19222           replacement = body + name_len;
19223         }
19224
19225       macro_define_object (file, line, name, replacement);
19226
19227       xfree (name);
19228     }
19229   else if (*p == '(')
19230     {
19231       /* It's a function-like macro.  */
19232       char *name = copy_string (body, p - body);
19233       int argc = 0;
19234       int argv_size = 1;
19235       char **argv = xmalloc (argv_size * sizeof (*argv));
19236
19237       p++;
19238
19239       p = consume_improper_spaces (p, body);
19240
19241       /* Parse the formal argument list.  */
19242       while (*p && *p != ')')
19243         {
19244           /* Find the extent of the current argument name.  */
19245           const char *arg_start = p;
19246
19247           while (*p && *p != ',' && *p != ')' && *p != ' ')
19248             p++;
19249
19250           if (! *p || p == arg_start)
19251             dwarf2_macro_malformed_definition_complaint (body);
19252           else
19253             {
19254               /* Make sure argv has room for the new argument.  */
19255               if (argc >= argv_size)
19256                 {
19257                   argv_size *= 2;
19258                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19259                 }
19260
19261               argv[argc++] = copy_string (arg_start, p - arg_start);
19262             }
19263
19264           p = consume_improper_spaces (p, body);
19265
19266           /* Consume the comma, if present.  */
19267           if (*p == ',')
19268             {
19269               p++;
19270
19271               p = consume_improper_spaces (p, body);
19272             }
19273         }
19274
19275       if (*p == ')')
19276         {
19277           p++;
19278
19279           if (*p == ' ')
19280             /* Perfectly formed definition, no complaints.  */
19281             macro_define_function (file, line, name,
19282                                    argc, (const char **) argv,
19283                                    p + 1);
19284           else if (*p == '\0')
19285             {
19286               /* Complain, but do define it.  */
19287               dwarf2_macro_malformed_definition_complaint (body);
19288               macro_define_function (file, line, name,
19289                                      argc, (const char **) argv,
19290                                      p);
19291             }
19292           else
19293             /* Just complain.  */
19294             dwarf2_macro_malformed_definition_complaint (body);
19295         }
19296       else
19297         /* Just complain.  */
19298         dwarf2_macro_malformed_definition_complaint (body);
19299
19300       xfree (name);
19301       {
19302         int i;
19303
19304         for (i = 0; i < argc; i++)
19305           xfree (argv[i]);
19306       }
19307       xfree (argv);
19308     }
19309   else
19310     dwarf2_macro_malformed_definition_complaint (body);
19311 }
19312
19313 /* Skip some bytes from BYTES according to the form given in FORM.
19314    Returns the new pointer.  */
19315
19316 static const gdb_byte *
19317 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19318                  enum dwarf_form form,
19319                  unsigned int offset_size,
19320                  struct dwarf2_section_info *section)
19321 {
19322   unsigned int bytes_read;
19323
19324   switch (form)
19325     {
19326     case DW_FORM_data1:
19327     case DW_FORM_flag:
19328       ++bytes;
19329       break;
19330
19331     case DW_FORM_data2:
19332       bytes += 2;
19333       break;
19334
19335     case DW_FORM_data4:
19336       bytes += 4;
19337       break;
19338
19339     case DW_FORM_data8:
19340       bytes += 8;
19341       break;
19342
19343     case DW_FORM_string:
19344       read_direct_string (abfd, bytes, &bytes_read);
19345       bytes += bytes_read;
19346       break;
19347
19348     case DW_FORM_sec_offset:
19349     case DW_FORM_strp:
19350     case DW_FORM_GNU_strp_alt:
19351       bytes += offset_size;
19352       break;
19353
19354     case DW_FORM_block:
19355       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19356       bytes += bytes_read;
19357       break;
19358
19359     case DW_FORM_block1:
19360       bytes += 1 + read_1_byte (abfd, bytes);
19361       break;
19362     case DW_FORM_block2:
19363       bytes += 2 + read_2_bytes (abfd, bytes);
19364       break;
19365     case DW_FORM_block4:
19366       bytes += 4 + read_4_bytes (abfd, bytes);
19367       break;
19368
19369     case DW_FORM_sdata:
19370     case DW_FORM_udata:
19371     case DW_FORM_GNU_addr_index:
19372     case DW_FORM_GNU_str_index:
19373       bytes = gdb_skip_leb128 (bytes, buffer_end);
19374       if (bytes == NULL)
19375         {
19376           dwarf2_section_buffer_overflow_complaint (section);
19377           return NULL;
19378         }
19379       break;
19380
19381     default:
19382       {
19383       complain:
19384         complaint (&symfile_complaints,
19385                    _("invalid form 0x%x in `%s'"),
19386                    form, get_section_name (section));
19387         return NULL;
19388       }
19389     }
19390
19391   return bytes;
19392 }
19393
19394 /* A helper for dwarf_decode_macros that handles skipping an unknown
19395    opcode.  Returns an updated pointer to the macro data buffer; or,
19396    on error, issues a complaint and returns NULL.  */
19397
19398 static const gdb_byte *
19399 skip_unknown_opcode (unsigned int opcode,
19400                      const gdb_byte **opcode_definitions,
19401                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19402                      bfd *abfd,
19403                      unsigned int offset_size,
19404                      struct dwarf2_section_info *section)
19405 {
19406   unsigned int bytes_read, i;
19407   unsigned long arg;
19408   const gdb_byte *defn;
19409
19410   if (opcode_definitions[opcode] == NULL)
19411     {
19412       complaint (&symfile_complaints,
19413                  _("unrecognized DW_MACFINO opcode 0x%x"),
19414                  opcode);
19415       return NULL;
19416     }
19417
19418   defn = opcode_definitions[opcode];
19419   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19420   defn += bytes_read;
19421
19422   for (i = 0; i < arg; ++i)
19423     {
19424       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19425                                  section);
19426       if (mac_ptr == NULL)
19427         {
19428           /* skip_form_bytes already issued the complaint.  */
19429           return NULL;
19430         }
19431     }
19432
19433   return mac_ptr;
19434 }
19435
19436 /* A helper function which parses the header of a macro section.
19437    If the macro section is the extended (for now called "GNU") type,
19438    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19439    the header, or issues a complaint and returns NULL on error.  */
19440
19441 static const gdb_byte *
19442 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19443                           bfd *abfd,
19444                           const gdb_byte *mac_ptr,
19445                           unsigned int *offset_size,
19446                           int section_is_gnu)
19447 {
19448   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19449
19450   if (section_is_gnu)
19451     {
19452       unsigned int version, flags;
19453
19454       version = read_2_bytes (abfd, mac_ptr);
19455       if (version != 4)
19456         {
19457           complaint (&symfile_complaints,
19458                      _("unrecognized version `%d' in .debug_macro section"),
19459                      version);
19460           return NULL;
19461         }
19462       mac_ptr += 2;
19463
19464       flags = read_1_byte (abfd, mac_ptr);
19465       ++mac_ptr;
19466       *offset_size = (flags & 1) ? 8 : 4;
19467
19468       if ((flags & 2) != 0)
19469         /* We don't need the line table offset.  */
19470         mac_ptr += *offset_size;
19471
19472       /* Vendor opcode descriptions.  */
19473       if ((flags & 4) != 0)
19474         {
19475           unsigned int i, count;
19476
19477           count = read_1_byte (abfd, mac_ptr);
19478           ++mac_ptr;
19479           for (i = 0; i < count; ++i)
19480             {
19481               unsigned int opcode, bytes_read;
19482               unsigned long arg;
19483
19484               opcode = read_1_byte (abfd, mac_ptr);
19485               ++mac_ptr;
19486               opcode_definitions[opcode] = mac_ptr;
19487               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19488               mac_ptr += bytes_read;
19489               mac_ptr += arg;
19490             }
19491         }
19492     }
19493
19494   return mac_ptr;
19495 }
19496
19497 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19498    including DW_MACRO_GNU_transparent_include.  */
19499
19500 static void
19501 dwarf_decode_macro_bytes (bfd *abfd,
19502                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19503                           struct macro_source_file *current_file,
19504                           struct line_header *lh, const char *comp_dir,
19505                           struct dwarf2_section_info *section,
19506                           int section_is_gnu, int section_is_dwz,
19507                           unsigned int offset_size,
19508                           struct objfile *objfile,
19509                           htab_t include_hash)
19510 {
19511   enum dwarf_macro_record_type macinfo_type;
19512   int at_commandline;
19513   const gdb_byte *opcode_definitions[256];
19514
19515   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19516                                       &offset_size, section_is_gnu);
19517   if (mac_ptr == NULL)
19518     {
19519       /* We already issued a complaint.  */
19520       return;
19521     }
19522
19523   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19524      GDB is still reading the definitions from command line.  First
19525      DW_MACINFO_start_file will need to be ignored as it was already executed
19526      to create CURRENT_FILE for the main source holding also the command line
19527      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19528      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19529
19530   at_commandline = 1;
19531
19532   do
19533     {
19534       /* Do we at least have room for a macinfo type byte?  */
19535       if (mac_ptr >= mac_end)
19536         {
19537           dwarf2_section_buffer_overflow_complaint (section);
19538           break;
19539         }
19540
19541       macinfo_type = read_1_byte (abfd, mac_ptr);
19542       mac_ptr++;
19543
19544       /* Note that we rely on the fact that the corresponding GNU and
19545          DWARF constants are the same.  */
19546       switch (macinfo_type)
19547         {
19548           /* A zero macinfo type indicates the end of the macro
19549              information.  */
19550         case 0:
19551           break;
19552
19553         case DW_MACRO_GNU_define:
19554         case DW_MACRO_GNU_undef:
19555         case DW_MACRO_GNU_define_indirect:
19556         case DW_MACRO_GNU_undef_indirect:
19557         case DW_MACRO_GNU_define_indirect_alt:
19558         case DW_MACRO_GNU_undef_indirect_alt:
19559           {
19560             unsigned int bytes_read;
19561             int line;
19562             const char *body;
19563             int is_define;
19564
19565             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19566             mac_ptr += bytes_read;
19567
19568             if (macinfo_type == DW_MACRO_GNU_define
19569                 || macinfo_type == DW_MACRO_GNU_undef)
19570               {
19571                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19572                 mac_ptr += bytes_read;
19573               }
19574             else
19575               {
19576                 LONGEST str_offset;
19577
19578                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19579                 mac_ptr += offset_size;
19580
19581                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19582                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19583                     || section_is_dwz)
19584                   {
19585                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19586
19587                     body = read_indirect_string_from_dwz (dwz, str_offset);
19588                   }
19589                 else
19590                   body = read_indirect_string_at_offset (abfd, str_offset);
19591               }
19592
19593             is_define = (macinfo_type == DW_MACRO_GNU_define
19594                          || macinfo_type == DW_MACRO_GNU_define_indirect
19595                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19596             if (! current_file)
19597               {
19598                 /* DWARF violation as no main source is present.  */
19599                 complaint (&symfile_complaints,
19600                            _("debug info with no main source gives macro %s "
19601                              "on line %d: %s"),
19602                            is_define ? _("definition") : _("undefinition"),
19603                            line, body);
19604                 break;
19605               }
19606             if ((line == 0 && !at_commandline)
19607                 || (line != 0 && at_commandline))
19608               complaint (&symfile_complaints,
19609                          _("debug info gives %s macro %s with %s line %d: %s"),
19610                          at_commandline ? _("command-line") : _("in-file"),
19611                          is_define ? _("definition") : _("undefinition"),
19612                          line == 0 ? _("zero") : _("non-zero"), line, body);
19613
19614             if (is_define)
19615               parse_macro_definition (current_file, line, body);
19616             else
19617               {
19618                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19619                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19620                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19621                 macro_undef (current_file, line, body);
19622               }
19623           }
19624           break;
19625
19626         case DW_MACRO_GNU_start_file:
19627           {
19628             unsigned int bytes_read;
19629             int line, file;
19630
19631             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19632             mac_ptr += bytes_read;
19633             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19634             mac_ptr += bytes_read;
19635
19636             if ((line == 0 && !at_commandline)
19637                 || (line != 0 && at_commandline))
19638               complaint (&symfile_complaints,
19639                          _("debug info gives source %d included "
19640                            "from %s at %s line %d"),
19641                          file, at_commandline ? _("command-line") : _("file"),
19642                          line == 0 ? _("zero") : _("non-zero"), line);
19643
19644             if (at_commandline)
19645               {
19646                 /* This DW_MACRO_GNU_start_file was executed in the
19647                    pass one.  */
19648                 at_commandline = 0;
19649               }
19650             else
19651               current_file = macro_start_file (file, line,
19652                                                current_file, comp_dir,
19653                                                lh, objfile);
19654           }
19655           break;
19656
19657         case DW_MACRO_GNU_end_file:
19658           if (! current_file)
19659             complaint (&symfile_complaints,
19660                        _("macro debug info has an unmatched "
19661                          "`close_file' directive"));
19662           else
19663             {
19664               current_file = current_file->included_by;
19665               if (! current_file)
19666                 {
19667                   enum dwarf_macro_record_type next_type;
19668
19669                   /* GCC circa March 2002 doesn't produce the zero
19670                      type byte marking the end of the compilation
19671                      unit.  Complain if it's not there, but exit no
19672                      matter what.  */
19673
19674                   /* Do we at least have room for a macinfo type byte?  */
19675                   if (mac_ptr >= mac_end)
19676                     {
19677                       dwarf2_section_buffer_overflow_complaint (section);
19678                       return;
19679                     }
19680
19681                   /* We don't increment mac_ptr here, so this is just
19682                      a look-ahead.  */
19683                   next_type = read_1_byte (abfd, mac_ptr);
19684                   if (next_type != 0)
19685                     complaint (&symfile_complaints,
19686                                _("no terminating 0-type entry for "
19687                                  "macros in `.debug_macinfo' section"));
19688
19689                   return;
19690                 }
19691             }
19692           break;
19693
19694         case DW_MACRO_GNU_transparent_include:
19695         case DW_MACRO_GNU_transparent_include_alt:
19696           {
19697             LONGEST offset;
19698             void **slot;
19699             bfd *include_bfd = abfd;
19700             struct dwarf2_section_info *include_section = section;
19701             struct dwarf2_section_info alt_section;
19702             const gdb_byte *include_mac_end = mac_end;
19703             int is_dwz = section_is_dwz;
19704             const gdb_byte *new_mac_ptr;
19705
19706             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19707             mac_ptr += offset_size;
19708
19709             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19710               {
19711                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19712
19713                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19714                                      &dwz->macro);
19715
19716                 include_section = &dwz->macro;
19717                 include_bfd = get_section_bfd_owner (include_section);
19718                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19719                 is_dwz = 1;
19720               }
19721
19722             new_mac_ptr = include_section->buffer + offset;
19723             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19724
19725             if (*slot != NULL)
19726               {
19727                 /* This has actually happened; see
19728                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19729                 complaint (&symfile_complaints,
19730                            _("recursive DW_MACRO_GNU_transparent_include in "
19731                              ".debug_macro section"));
19732               }
19733             else
19734               {
19735                 *slot = (void *) new_mac_ptr;
19736
19737                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19738                                           include_mac_end, current_file,
19739                                           lh, comp_dir,
19740                                           section, section_is_gnu, is_dwz,
19741                                           offset_size, objfile, include_hash);
19742
19743                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19744               }
19745           }
19746           break;
19747
19748         case DW_MACINFO_vendor_ext:
19749           if (!section_is_gnu)
19750             {
19751               unsigned int bytes_read;
19752               int constant;
19753
19754               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19755               mac_ptr += bytes_read;
19756               read_direct_string (abfd, mac_ptr, &bytes_read);
19757               mac_ptr += bytes_read;
19758
19759               /* We don't recognize any vendor extensions.  */
19760               break;
19761             }
19762           /* FALLTHROUGH */
19763
19764         default:
19765           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19766                                          mac_ptr, mac_end, abfd, offset_size,
19767                                          section);
19768           if (mac_ptr == NULL)
19769             return;
19770           break;
19771         }
19772     } while (macinfo_type != 0);
19773 }
19774
19775 static void
19776 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19777                      const char *comp_dir, int section_is_gnu)
19778 {
19779   struct objfile *objfile = dwarf2_per_objfile->objfile;
19780   struct line_header *lh = cu->line_header;
19781   bfd *abfd;
19782   const gdb_byte *mac_ptr, *mac_end;
19783   struct macro_source_file *current_file = 0;
19784   enum dwarf_macro_record_type macinfo_type;
19785   unsigned int offset_size = cu->header.offset_size;
19786   const gdb_byte *opcode_definitions[256];
19787   struct cleanup *cleanup;
19788   htab_t include_hash;
19789   void **slot;
19790   struct dwarf2_section_info *section;
19791   const char *section_name;
19792
19793   if (cu->dwo_unit != NULL)
19794     {
19795       if (section_is_gnu)
19796         {
19797           section = &cu->dwo_unit->dwo_file->sections.macro;
19798           section_name = ".debug_macro.dwo";
19799         }
19800       else
19801         {
19802           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19803           section_name = ".debug_macinfo.dwo";
19804         }
19805     }
19806   else
19807     {
19808       if (section_is_gnu)
19809         {
19810           section = &dwarf2_per_objfile->macro;
19811           section_name = ".debug_macro";
19812         }
19813       else
19814         {
19815           section = &dwarf2_per_objfile->macinfo;
19816           section_name = ".debug_macinfo";
19817         }
19818     }
19819
19820   dwarf2_read_section (objfile, section);
19821   if (section->buffer == NULL)
19822     {
19823       complaint (&symfile_complaints, _("missing %s section"), section_name);
19824       return;
19825     }
19826   abfd = get_section_bfd_owner (section);
19827
19828   /* First pass: Find the name of the base filename.
19829      This filename is needed in order to process all macros whose definition
19830      (or undefinition) comes from the command line.  These macros are defined
19831      before the first DW_MACINFO_start_file entry, and yet still need to be
19832      associated to the base file.
19833
19834      To determine the base file name, we scan the macro definitions until we
19835      reach the first DW_MACINFO_start_file entry.  We then initialize
19836      CURRENT_FILE accordingly so that any macro definition found before the
19837      first DW_MACINFO_start_file can still be associated to the base file.  */
19838
19839   mac_ptr = section->buffer + offset;
19840   mac_end = section->buffer + section->size;
19841
19842   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19843                                       &offset_size, section_is_gnu);
19844   if (mac_ptr == NULL)
19845     {
19846       /* We already issued a complaint.  */
19847       return;
19848     }
19849
19850   do
19851     {
19852       /* Do we at least have room for a macinfo type byte?  */
19853       if (mac_ptr >= mac_end)
19854         {
19855           /* Complaint is printed during the second pass as GDB will probably
19856              stop the first pass earlier upon finding
19857              DW_MACINFO_start_file.  */
19858           break;
19859         }
19860
19861       macinfo_type = read_1_byte (abfd, mac_ptr);
19862       mac_ptr++;
19863
19864       /* Note that we rely on the fact that the corresponding GNU and
19865          DWARF constants are the same.  */
19866       switch (macinfo_type)
19867         {
19868           /* A zero macinfo type indicates the end of the macro
19869              information.  */
19870         case 0:
19871           break;
19872
19873         case DW_MACRO_GNU_define:
19874         case DW_MACRO_GNU_undef:
19875           /* Only skip the data by MAC_PTR.  */
19876           {
19877             unsigned int bytes_read;
19878
19879             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19880             mac_ptr += bytes_read;
19881             read_direct_string (abfd, mac_ptr, &bytes_read);
19882             mac_ptr += bytes_read;
19883           }
19884           break;
19885
19886         case DW_MACRO_GNU_start_file:
19887           {
19888             unsigned int bytes_read;
19889             int line, file;
19890
19891             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19892             mac_ptr += bytes_read;
19893             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19894             mac_ptr += bytes_read;
19895
19896             current_file = macro_start_file (file, line, current_file,
19897                                              comp_dir, lh, objfile);
19898           }
19899           break;
19900
19901         case DW_MACRO_GNU_end_file:
19902           /* No data to skip by MAC_PTR.  */
19903           break;
19904
19905         case DW_MACRO_GNU_define_indirect:
19906         case DW_MACRO_GNU_undef_indirect:
19907         case DW_MACRO_GNU_define_indirect_alt:
19908         case DW_MACRO_GNU_undef_indirect_alt:
19909           {
19910             unsigned int bytes_read;
19911
19912             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19913             mac_ptr += bytes_read;
19914             mac_ptr += offset_size;
19915           }
19916           break;
19917
19918         case DW_MACRO_GNU_transparent_include:
19919         case DW_MACRO_GNU_transparent_include_alt:
19920           /* Note that, according to the spec, a transparent include
19921              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19922              skip this opcode.  */
19923           mac_ptr += offset_size;
19924           break;
19925
19926         case DW_MACINFO_vendor_ext:
19927           /* Only skip the data by MAC_PTR.  */
19928           if (!section_is_gnu)
19929             {
19930               unsigned int bytes_read;
19931
19932               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19933               mac_ptr += bytes_read;
19934               read_direct_string (abfd, mac_ptr, &bytes_read);
19935               mac_ptr += bytes_read;
19936             }
19937           /* FALLTHROUGH */
19938
19939         default:
19940           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19941                                          mac_ptr, mac_end, abfd, offset_size,
19942                                          section);
19943           if (mac_ptr == NULL)
19944             return;
19945           break;
19946         }
19947     } while (macinfo_type != 0 && current_file == NULL);
19948
19949   /* Second pass: Process all entries.
19950
19951      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19952      command-line macro definitions/undefinitions.  This flag is unset when we
19953      reach the first DW_MACINFO_start_file entry.  */
19954
19955   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19956                                     NULL, xcalloc, xfree);
19957   cleanup = make_cleanup_htab_delete (include_hash);
19958   mac_ptr = section->buffer + offset;
19959   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19960   *slot = (void *) mac_ptr;
19961   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19962                             current_file, lh, comp_dir, section,
19963                             section_is_gnu, 0,
19964                             offset_size, objfile, include_hash);
19965   do_cleanups (cleanup);
19966 }
19967
19968 /* Check if the attribute's form is a DW_FORM_block*
19969    if so return true else false.  */
19970
19971 static int
19972 attr_form_is_block (const struct attribute *attr)
19973 {
19974   return (attr == NULL ? 0 :
19975       attr->form == DW_FORM_block1
19976       || attr->form == DW_FORM_block2
19977       || attr->form == DW_FORM_block4
19978       || attr->form == DW_FORM_block
19979       || attr->form == DW_FORM_exprloc);
19980 }
19981
19982 /* Return non-zero if ATTR's value is a section offset --- classes
19983    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19984    You may use DW_UNSND (attr) to retrieve such offsets.
19985
19986    Section 7.5.4, "Attribute Encodings", explains that no attribute
19987    may have a value that belongs to more than one of these classes; it
19988    would be ambiguous if we did, because we use the same forms for all
19989    of them.  */
19990
19991 static int
19992 attr_form_is_section_offset (const struct attribute *attr)
19993 {
19994   return (attr->form == DW_FORM_data4
19995           || attr->form == DW_FORM_data8
19996           || attr->form == DW_FORM_sec_offset);
19997 }
19998
19999 /* Return non-zero if ATTR's value falls in the 'constant' class, or
20000    zero otherwise.  When this function returns true, you can apply
20001    dwarf2_get_attr_constant_value to it.
20002
20003    However, note that for some attributes you must check
20004    attr_form_is_section_offset before using this test.  DW_FORM_data4
20005    and DW_FORM_data8 are members of both the constant class, and of
20006    the classes that contain offsets into other debug sections
20007    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
20008    that, if an attribute's can be either a constant or one of the
20009    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
20010    taken as section offsets, not constants.  */
20011
20012 static int
20013 attr_form_is_constant (const struct attribute *attr)
20014 {
20015   switch (attr->form)
20016     {
20017     case DW_FORM_sdata:
20018     case DW_FORM_udata:
20019     case DW_FORM_data1:
20020     case DW_FORM_data2:
20021     case DW_FORM_data4:
20022     case DW_FORM_data8:
20023       return 1;
20024     default:
20025       return 0;
20026     }
20027 }
20028
20029
20030 /* DW_ADDR is always stored already as sect_offset; despite for the forms
20031    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
20032
20033 static int
20034 attr_form_is_ref (const struct attribute *attr)
20035 {
20036   switch (attr->form)
20037     {
20038     case DW_FORM_ref_addr:
20039     case DW_FORM_ref1:
20040     case DW_FORM_ref2:
20041     case DW_FORM_ref4:
20042     case DW_FORM_ref8:
20043     case DW_FORM_ref_udata:
20044     case DW_FORM_GNU_ref_alt:
20045       return 1;
20046     default:
20047       return 0;
20048     }
20049 }
20050
20051 /* Return the .debug_loc section to use for CU.
20052    For DWO files use .debug_loc.dwo.  */
20053
20054 static struct dwarf2_section_info *
20055 cu_debug_loc_section (struct dwarf2_cu *cu)
20056 {
20057   if (cu->dwo_unit)
20058     return &cu->dwo_unit->dwo_file->sections.loc;
20059   return &dwarf2_per_objfile->loc;
20060 }
20061
20062 /* A helper function that fills in a dwarf2_loclist_baton.  */
20063
20064 static void
20065 fill_in_loclist_baton (struct dwarf2_cu *cu,
20066                        struct dwarf2_loclist_baton *baton,
20067                        const struct attribute *attr)
20068 {
20069   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20070
20071   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20072
20073   baton->per_cu = cu->per_cu;
20074   gdb_assert (baton->per_cu);
20075   /* We don't know how long the location list is, but make sure we
20076      don't run off the edge of the section.  */
20077   baton->size = section->size - DW_UNSND (attr);
20078   baton->data = section->buffer + DW_UNSND (attr);
20079   baton->base_address = cu->base_address;
20080   baton->from_dwo = cu->dwo_unit != NULL;
20081 }
20082
20083 static void
20084 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
20085                              struct dwarf2_cu *cu, int is_block)
20086 {
20087   struct objfile *objfile = dwarf2_per_objfile->objfile;
20088   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20089
20090   if (attr_form_is_section_offset (attr)
20091       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
20092          the section.  If so, fall through to the complaint in the
20093          other branch.  */
20094       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
20095     {
20096       struct dwarf2_loclist_baton *baton;
20097
20098       baton = obstack_alloc (&objfile->objfile_obstack,
20099                              sizeof (struct dwarf2_loclist_baton));
20100
20101       fill_in_loclist_baton (cu, baton, attr);
20102
20103       if (cu->base_known == 0)
20104         complaint (&symfile_complaints,
20105                    _("Location list used without "
20106                      "specifying the CU base address."));
20107
20108       SYMBOL_ACLASS_INDEX (sym) = (is_block
20109                                    ? dwarf2_loclist_block_index
20110                                    : dwarf2_loclist_index);
20111       SYMBOL_LOCATION_BATON (sym) = baton;
20112     }
20113   else
20114     {
20115       struct dwarf2_locexpr_baton *baton;
20116
20117       baton = obstack_alloc (&objfile->objfile_obstack,
20118                              sizeof (struct dwarf2_locexpr_baton));
20119       baton->per_cu = cu->per_cu;
20120       gdb_assert (baton->per_cu);
20121
20122       if (attr_form_is_block (attr))
20123         {
20124           /* Note that we're just copying the block's data pointer
20125              here, not the actual data.  We're still pointing into the
20126              info_buffer for SYM's objfile; right now we never release
20127              that buffer, but when we do clean up properly this may
20128              need to change.  */
20129           baton->size = DW_BLOCK (attr)->size;
20130           baton->data = DW_BLOCK (attr)->data;
20131         }
20132       else
20133         {
20134           dwarf2_invalid_attrib_class_complaint ("location description",
20135                                                  SYMBOL_NATURAL_NAME (sym));
20136           baton->size = 0;
20137         }
20138
20139       SYMBOL_ACLASS_INDEX (sym) = (is_block
20140                                    ? dwarf2_locexpr_block_index
20141                                    : dwarf2_locexpr_index);
20142       SYMBOL_LOCATION_BATON (sym) = baton;
20143     }
20144 }
20145
20146 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20147    came from a separate debuginfo file, then the master objfile is
20148    returned.  */
20149
20150 struct objfile *
20151 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20152 {
20153   struct objfile *objfile = per_cu->objfile;
20154
20155   /* Return the master objfile, so that we can report and look up the
20156      correct file containing this variable.  */
20157   if (objfile->separate_debug_objfile_backlink)
20158     objfile = objfile->separate_debug_objfile_backlink;
20159
20160   return objfile;
20161 }
20162
20163 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20164    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20165    CU_HEADERP first.  */
20166
20167 static const struct comp_unit_head *
20168 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20169                        struct dwarf2_per_cu_data *per_cu)
20170 {
20171   const gdb_byte *info_ptr;
20172
20173   if (per_cu->cu)
20174     return &per_cu->cu->header;
20175
20176   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20177
20178   memset (cu_headerp, 0, sizeof (*cu_headerp));
20179   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20180
20181   return cu_headerp;
20182 }
20183
20184 /* Return the address size given in the compilation unit header for CU.  */
20185
20186 int
20187 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20188 {
20189   struct comp_unit_head cu_header_local;
20190   const struct comp_unit_head *cu_headerp;
20191
20192   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20193
20194   return cu_headerp->addr_size;
20195 }
20196
20197 /* Return the offset size given in the compilation unit header for CU.  */
20198
20199 int
20200 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20201 {
20202   struct comp_unit_head cu_header_local;
20203   const struct comp_unit_head *cu_headerp;
20204
20205   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20206
20207   return cu_headerp->offset_size;
20208 }
20209
20210 /* See its dwarf2loc.h declaration.  */
20211
20212 int
20213 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20214 {
20215   struct comp_unit_head cu_header_local;
20216   const struct comp_unit_head *cu_headerp;
20217
20218   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20219
20220   if (cu_headerp->version == 2)
20221     return cu_headerp->addr_size;
20222   else
20223     return cu_headerp->offset_size;
20224 }
20225
20226 /* Return the text offset of the CU.  The returned offset comes from
20227    this CU's objfile.  If this objfile came from a separate debuginfo
20228    file, then the offset may be different from the corresponding
20229    offset in the parent objfile.  */
20230
20231 CORE_ADDR
20232 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20233 {
20234   struct objfile *objfile = per_cu->objfile;
20235
20236   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20237 }
20238
20239 /* Locate the .debug_info compilation unit from CU's objfile which contains
20240    the DIE at OFFSET.  Raises an error on failure.  */
20241
20242 static struct dwarf2_per_cu_data *
20243 dwarf2_find_containing_comp_unit (sect_offset offset,
20244                                   unsigned int offset_in_dwz,
20245                                   struct objfile *objfile)
20246 {
20247   struct dwarf2_per_cu_data *this_cu;
20248   int low, high;
20249   const sect_offset *cu_off;
20250
20251   low = 0;
20252   high = dwarf2_per_objfile->n_comp_units - 1;
20253   while (high > low)
20254     {
20255       struct dwarf2_per_cu_data *mid_cu;
20256       int mid = low + (high - low) / 2;
20257
20258       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20259       cu_off = &mid_cu->offset;
20260       if (mid_cu->is_dwz > offset_in_dwz
20261           || (mid_cu->is_dwz == offset_in_dwz
20262               && cu_off->sect_off >= offset.sect_off))
20263         high = mid;
20264       else
20265         low = mid + 1;
20266     }
20267   gdb_assert (low == high);
20268   this_cu = dwarf2_per_objfile->all_comp_units[low];
20269   cu_off = &this_cu->offset;
20270   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20271     {
20272       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20273         error (_("Dwarf Error: could not find partial DIE containing "
20274                "offset 0x%lx [in module %s]"),
20275                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20276
20277       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20278                   <= offset.sect_off);
20279       return dwarf2_per_objfile->all_comp_units[low-1];
20280     }
20281   else
20282     {
20283       this_cu = dwarf2_per_objfile->all_comp_units[low];
20284       if (low == dwarf2_per_objfile->n_comp_units - 1
20285           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20286         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20287       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20288       return this_cu;
20289     }
20290 }
20291
20292 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20293
20294 static void
20295 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20296 {
20297   memset (cu, 0, sizeof (*cu));
20298   per_cu->cu = cu;
20299   cu->per_cu = per_cu;
20300   cu->objfile = per_cu->objfile;
20301   obstack_init (&cu->comp_unit_obstack);
20302 }
20303
20304 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20305
20306 static void
20307 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20308                        enum language pretend_language)
20309 {
20310   struct attribute *attr;
20311
20312   /* Set the language we're debugging.  */
20313   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20314   if (attr)
20315     set_cu_language (DW_UNSND (attr), cu);
20316   else
20317     {
20318       cu->language = pretend_language;
20319       cu->language_defn = language_def (cu->language);
20320     }
20321
20322   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20323   if (attr)
20324     cu->producer = DW_STRING (attr);
20325 }
20326
20327 /* Release one cached compilation unit, CU.  We unlink it from the tree
20328    of compilation units, but we don't remove it from the read_in_chain;
20329    the caller is responsible for that.
20330    NOTE: DATA is a void * because this function is also used as a
20331    cleanup routine.  */
20332
20333 static void
20334 free_heap_comp_unit (void *data)
20335 {
20336   struct dwarf2_cu *cu = data;
20337
20338   gdb_assert (cu->per_cu != NULL);
20339   cu->per_cu->cu = NULL;
20340   cu->per_cu = NULL;
20341
20342   obstack_free (&cu->comp_unit_obstack, NULL);
20343
20344   xfree (cu);
20345 }
20346
20347 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20348    when we're finished with it.  We can't free the pointer itself, but be
20349    sure to unlink it from the cache.  Also release any associated storage.  */
20350
20351 static void
20352 free_stack_comp_unit (void *data)
20353 {
20354   struct dwarf2_cu *cu = data;
20355
20356   gdb_assert (cu->per_cu != NULL);
20357   cu->per_cu->cu = NULL;
20358   cu->per_cu = NULL;
20359
20360   obstack_free (&cu->comp_unit_obstack, NULL);
20361   cu->partial_dies = NULL;
20362 }
20363
20364 /* Free all cached compilation units.  */
20365
20366 static void
20367 free_cached_comp_units (void *data)
20368 {
20369   struct dwarf2_per_cu_data *per_cu, **last_chain;
20370
20371   per_cu = dwarf2_per_objfile->read_in_chain;
20372   last_chain = &dwarf2_per_objfile->read_in_chain;
20373   while (per_cu != NULL)
20374     {
20375       struct dwarf2_per_cu_data *next_cu;
20376
20377       next_cu = per_cu->cu->read_in_chain;
20378
20379       free_heap_comp_unit (per_cu->cu);
20380       *last_chain = next_cu;
20381
20382       per_cu = next_cu;
20383     }
20384 }
20385
20386 /* Increase the age counter on each cached compilation unit, and free
20387    any that are too old.  */
20388
20389 static void
20390 age_cached_comp_units (void)
20391 {
20392   struct dwarf2_per_cu_data *per_cu, **last_chain;
20393
20394   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20395   per_cu = dwarf2_per_objfile->read_in_chain;
20396   while (per_cu != NULL)
20397     {
20398       per_cu->cu->last_used ++;
20399       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20400         dwarf2_mark (per_cu->cu);
20401       per_cu = per_cu->cu->read_in_chain;
20402     }
20403
20404   per_cu = dwarf2_per_objfile->read_in_chain;
20405   last_chain = &dwarf2_per_objfile->read_in_chain;
20406   while (per_cu != NULL)
20407     {
20408       struct dwarf2_per_cu_data *next_cu;
20409
20410       next_cu = per_cu->cu->read_in_chain;
20411
20412       if (!per_cu->cu->mark)
20413         {
20414           free_heap_comp_unit (per_cu->cu);
20415           *last_chain = next_cu;
20416         }
20417       else
20418         last_chain = &per_cu->cu->read_in_chain;
20419
20420       per_cu = next_cu;
20421     }
20422 }
20423
20424 /* Remove a single compilation unit from the cache.  */
20425
20426 static void
20427 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20428 {
20429   struct dwarf2_per_cu_data *per_cu, **last_chain;
20430
20431   per_cu = dwarf2_per_objfile->read_in_chain;
20432   last_chain = &dwarf2_per_objfile->read_in_chain;
20433   while (per_cu != NULL)
20434     {
20435       struct dwarf2_per_cu_data *next_cu;
20436
20437       next_cu = per_cu->cu->read_in_chain;
20438
20439       if (per_cu == target_per_cu)
20440         {
20441           free_heap_comp_unit (per_cu->cu);
20442           per_cu->cu = NULL;
20443           *last_chain = next_cu;
20444           break;
20445         }
20446       else
20447         last_chain = &per_cu->cu->read_in_chain;
20448
20449       per_cu = next_cu;
20450     }
20451 }
20452
20453 /* Release all extra memory associated with OBJFILE.  */
20454
20455 void
20456 dwarf2_free_objfile (struct objfile *objfile)
20457 {
20458   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20459
20460   if (dwarf2_per_objfile == NULL)
20461     return;
20462
20463   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20464   free_cached_comp_units (NULL);
20465
20466   if (dwarf2_per_objfile->quick_file_names_table)
20467     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20468
20469   /* Everything else should be on the objfile obstack.  */
20470 }
20471
20472 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20473    We store these in a hash table separate from the DIEs, and preserve them
20474    when the DIEs are flushed out of cache.
20475
20476    The CU "per_cu" pointer is needed because offset alone is not enough to
20477    uniquely identify the type.  A file may have multiple .debug_types sections,
20478    or the type may come from a DWO file.  Furthermore, while it's more logical
20479    to use per_cu->section+offset, with Fission the section with the data is in
20480    the DWO file but we don't know that section at the point we need it.
20481    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20482    because we can enter the lookup routine, get_die_type_at_offset, from
20483    outside this file, and thus won't necessarily have PER_CU->cu.
20484    Fortunately, PER_CU is stable for the life of the objfile.  */
20485
20486 struct dwarf2_per_cu_offset_and_type
20487 {
20488   const struct dwarf2_per_cu_data *per_cu;
20489   sect_offset offset;
20490   struct type *type;
20491 };
20492
20493 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20494
20495 static hashval_t
20496 per_cu_offset_and_type_hash (const void *item)
20497 {
20498   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20499
20500   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20501 }
20502
20503 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20504
20505 static int
20506 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20507 {
20508   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20509   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20510
20511   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20512           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20513 }
20514
20515 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20516    table if necessary.  For convenience, return TYPE.
20517
20518    The DIEs reading must have careful ordering to:
20519     * Not cause infite loops trying to read in DIEs as a prerequisite for
20520       reading current DIE.
20521     * Not trying to dereference contents of still incompletely read in types
20522       while reading in other DIEs.
20523     * Enable referencing still incompletely read in types just by a pointer to
20524       the type without accessing its fields.
20525
20526    Therefore caller should follow these rules:
20527      * Try to fetch any prerequisite types we may need to build this DIE type
20528        before building the type and calling set_die_type.
20529      * After building type call set_die_type for current DIE as soon as
20530        possible before fetching more types to complete the current type.
20531      * Make the type as complete as possible before fetching more types.  */
20532
20533 static struct type *
20534 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20535 {
20536   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20537   struct objfile *objfile = cu->objfile;
20538
20539   /* For Ada types, make sure that the gnat-specific data is always
20540      initialized (if not already set).  There are a few types where
20541      we should not be doing so, because the type-specific area is
20542      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20543      where the type-specific area is used to store the floatformat).
20544      But this is not a problem, because the gnat-specific information
20545      is actually not needed for these types.  */
20546   if (need_gnat_info (cu)
20547       && TYPE_CODE (type) != TYPE_CODE_FUNC
20548       && TYPE_CODE (type) != TYPE_CODE_FLT
20549       && !HAVE_GNAT_AUX_INFO (type))
20550     INIT_GNAT_SPECIFIC (type);
20551
20552   if (dwarf2_per_objfile->die_type_hash == NULL)
20553     {
20554       dwarf2_per_objfile->die_type_hash =
20555         htab_create_alloc_ex (127,
20556                               per_cu_offset_and_type_hash,
20557                               per_cu_offset_and_type_eq,
20558                               NULL,
20559                               &objfile->objfile_obstack,
20560                               hashtab_obstack_allocate,
20561                               dummy_obstack_deallocate);
20562     }
20563
20564   ofs.per_cu = cu->per_cu;
20565   ofs.offset = die->offset;
20566   ofs.type = type;
20567   slot = (struct dwarf2_per_cu_offset_and_type **)
20568     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20569   if (*slot)
20570     complaint (&symfile_complaints,
20571                _("A problem internal to GDB: DIE 0x%x has type already set"),
20572                die->offset.sect_off);
20573   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20574   **slot = ofs;
20575   return type;
20576 }
20577
20578 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20579    or return NULL if the die does not have a saved type.  */
20580
20581 static struct type *
20582 get_die_type_at_offset (sect_offset offset,
20583                         struct dwarf2_per_cu_data *per_cu)
20584 {
20585   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20586
20587   if (dwarf2_per_objfile->die_type_hash == NULL)
20588     return NULL;
20589
20590   ofs.per_cu = per_cu;
20591   ofs.offset = offset;
20592   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20593   if (slot)
20594     return slot->type;
20595   else
20596     return NULL;
20597 }
20598
20599 /* Look up the type for DIE in CU in die_type_hash,
20600    or return NULL if DIE does not have a saved type.  */
20601
20602 static struct type *
20603 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20604 {
20605   return get_die_type_at_offset (die->offset, cu->per_cu);
20606 }
20607
20608 /* Add a dependence relationship from CU to REF_PER_CU.  */
20609
20610 static void
20611 dwarf2_add_dependence (struct dwarf2_cu *cu,
20612                        struct dwarf2_per_cu_data *ref_per_cu)
20613 {
20614   void **slot;
20615
20616   if (cu->dependencies == NULL)
20617     cu->dependencies
20618       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20619                               NULL, &cu->comp_unit_obstack,
20620                               hashtab_obstack_allocate,
20621                               dummy_obstack_deallocate);
20622
20623   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20624   if (*slot == NULL)
20625     *slot = ref_per_cu;
20626 }
20627
20628 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20629    Set the mark field in every compilation unit in the
20630    cache that we must keep because we are keeping CU.  */
20631
20632 static int
20633 dwarf2_mark_helper (void **slot, void *data)
20634 {
20635   struct dwarf2_per_cu_data *per_cu;
20636
20637   per_cu = (struct dwarf2_per_cu_data *) *slot;
20638
20639   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20640      reading of the chain.  As such dependencies remain valid it is not much
20641      useful to track and undo them during QUIT cleanups.  */
20642   if (per_cu->cu == NULL)
20643     return 1;
20644
20645   if (per_cu->cu->mark)
20646     return 1;
20647   per_cu->cu->mark = 1;
20648
20649   if (per_cu->cu->dependencies != NULL)
20650     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20651
20652   return 1;
20653 }
20654
20655 /* Set the mark field in CU and in every other compilation unit in the
20656    cache that we must keep because we are keeping CU.  */
20657
20658 static void
20659 dwarf2_mark (struct dwarf2_cu *cu)
20660 {
20661   if (cu->mark)
20662     return;
20663   cu->mark = 1;
20664   if (cu->dependencies != NULL)
20665     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20666 }
20667
20668 static void
20669 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20670 {
20671   while (per_cu)
20672     {
20673       per_cu->cu->mark = 0;
20674       per_cu = per_cu->cu->read_in_chain;
20675     }
20676 }
20677
20678 /* Trivial hash function for partial_die_info: the hash value of a DIE
20679    is its offset in .debug_info for this objfile.  */
20680
20681 static hashval_t
20682 partial_die_hash (const void *item)
20683 {
20684   const struct partial_die_info *part_die = item;
20685
20686   return part_die->offset.sect_off;
20687 }
20688
20689 /* Trivial comparison function for partial_die_info structures: two DIEs
20690    are equal if they have the same offset.  */
20691
20692 static int
20693 partial_die_eq (const void *item_lhs, const void *item_rhs)
20694 {
20695   const struct partial_die_info *part_die_lhs = item_lhs;
20696   const struct partial_die_info *part_die_rhs = item_rhs;
20697
20698   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20699 }
20700
20701 static struct cmd_list_element *set_dwarf2_cmdlist;
20702 static struct cmd_list_element *show_dwarf2_cmdlist;
20703
20704 static void
20705 set_dwarf2_cmd (char *args, int from_tty)
20706 {
20707   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20708 }
20709
20710 static void
20711 show_dwarf2_cmd (char *args, int from_tty)
20712 {
20713   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20714 }
20715
20716 /* Free data associated with OBJFILE, if necessary.  */
20717
20718 static void
20719 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20720 {
20721   struct dwarf2_per_objfile *data = d;
20722   int ix;
20723
20724   /* Make sure we don't accidentally use dwarf2_per_objfile while
20725      cleaning up.  */
20726   dwarf2_per_objfile = NULL;
20727
20728   for (ix = 0; ix < data->n_comp_units; ++ix)
20729    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20730
20731   for (ix = 0; ix < data->n_type_units; ++ix)
20732     VEC_free (dwarf2_per_cu_ptr,
20733               data->all_type_units[ix]->per_cu.imported_symtabs);
20734   xfree (data->all_type_units);
20735
20736   VEC_free (dwarf2_section_info_def, data->types);
20737
20738   if (data->dwo_files)
20739     free_dwo_files (data->dwo_files, objfile);
20740   if (data->dwp_file)
20741     gdb_bfd_unref (data->dwp_file->dbfd);
20742
20743   if (data->dwz_file && data->dwz_file->dwz_bfd)
20744     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20745 }
20746
20747 \f
20748 /* The "save gdb-index" command.  */
20749
20750 /* The contents of the hash table we create when building the string
20751    table.  */
20752 struct strtab_entry
20753 {
20754   offset_type offset;
20755   const char *str;
20756 };
20757
20758 /* Hash function for a strtab_entry.
20759
20760    Function is used only during write_hash_table so no index format backward
20761    compatibility is needed.  */
20762
20763 static hashval_t
20764 hash_strtab_entry (const void *e)
20765 {
20766   const struct strtab_entry *entry = e;
20767   return mapped_index_string_hash (INT_MAX, entry->str);
20768 }
20769
20770 /* Equality function for a strtab_entry.  */
20771
20772 static int
20773 eq_strtab_entry (const void *a, const void *b)
20774 {
20775   const struct strtab_entry *ea = a;
20776   const struct strtab_entry *eb = b;
20777   return !strcmp (ea->str, eb->str);
20778 }
20779
20780 /* Create a strtab_entry hash table.  */
20781
20782 static htab_t
20783 create_strtab (void)
20784 {
20785   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20786                             xfree, xcalloc, xfree);
20787 }
20788
20789 /* Add a string to the constant pool.  Return the string's offset in
20790    host order.  */
20791
20792 static offset_type
20793 add_string (htab_t table, struct obstack *cpool, const char *str)
20794 {
20795   void **slot;
20796   struct strtab_entry entry;
20797   struct strtab_entry *result;
20798
20799   entry.str = str;
20800   slot = htab_find_slot (table, &entry, INSERT);
20801   if (*slot)
20802     result = *slot;
20803   else
20804     {
20805       result = XNEW (struct strtab_entry);
20806       result->offset = obstack_object_size (cpool);
20807       result->str = str;
20808       obstack_grow_str0 (cpool, str);
20809       *slot = result;
20810     }
20811   return result->offset;
20812 }
20813
20814 /* An entry in the symbol table.  */
20815 struct symtab_index_entry
20816 {
20817   /* The name of the symbol.  */
20818   const char *name;
20819   /* The offset of the name in the constant pool.  */
20820   offset_type index_offset;
20821   /* A sorted vector of the indices of all the CUs that hold an object
20822      of this name.  */
20823   VEC (offset_type) *cu_indices;
20824 };
20825
20826 /* The symbol table.  This is a power-of-2-sized hash table.  */
20827 struct mapped_symtab
20828 {
20829   offset_type n_elements;
20830   offset_type size;
20831   struct symtab_index_entry **data;
20832 };
20833
20834 /* Hash function for a symtab_index_entry.  */
20835
20836 static hashval_t
20837 hash_symtab_entry (const void *e)
20838 {
20839   const struct symtab_index_entry *entry = e;
20840   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20841                          sizeof (offset_type) * VEC_length (offset_type,
20842                                                             entry->cu_indices),
20843                          0);
20844 }
20845
20846 /* Equality function for a symtab_index_entry.  */
20847
20848 static int
20849 eq_symtab_entry (const void *a, const void *b)
20850 {
20851   const struct symtab_index_entry *ea = a;
20852   const struct symtab_index_entry *eb = b;
20853   int len = VEC_length (offset_type, ea->cu_indices);
20854   if (len != VEC_length (offset_type, eb->cu_indices))
20855     return 0;
20856   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20857                   VEC_address (offset_type, eb->cu_indices),
20858                   sizeof (offset_type) * len);
20859 }
20860
20861 /* Destroy a symtab_index_entry.  */
20862
20863 static void
20864 delete_symtab_entry (void *p)
20865 {
20866   struct symtab_index_entry *entry = p;
20867   VEC_free (offset_type, entry->cu_indices);
20868   xfree (entry);
20869 }
20870
20871 /* Create a hash table holding symtab_index_entry objects.  */
20872
20873 static htab_t
20874 create_symbol_hash_table (void)
20875 {
20876   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20877                             delete_symtab_entry, xcalloc, xfree);
20878 }
20879
20880 /* Create a new mapped symtab object.  */
20881
20882 static struct mapped_symtab *
20883 create_mapped_symtab (void)
20884 {
20885   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20886   symtab->n_elements = 0;
20887   symtab->size = 1024;
20888   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20889   return symtab;
20890 }
20891
20892 /* Destroy a mapped_symtab.  */
20893
20894 static void
20895 cleanup_mapped_symtab (void *p)
20896 {
20897   struct mapped_symtab *symtab = p;
20898   /* The contents of the array are freed when the other hash table is
20899      destroyed.  */
20900   xfree (symtab->data);
20901   xfree (symtab);
20902 }
20903
20904 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20905    the slot.
20906    
20907    Function is used only during write_hash_table so no index format backward
20908    compatibility is needed.  */
20909
20910 static struct symtab_index_entry **
20911 find_slot (struct mapped_symtab *symtab, const char *name)
20912 {
20913   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20914
20915   index = hash & (symtab->size - 1);
20916   step = ((hash * 17) & (symtab->size - 1)) | 1;
20917
20918   for (;;)
20919     {
20920       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20921         return &symtab->data[index];
20922       index = (index + step) & (symtab->size - 1);
20923     }
20924 }
20925
20926 /* Expand SYMTAB's hash table.  */
20927
20928 static void
20929 hash_expand (struct mapped_symtab *symtab)
20930 {
20931   offset_type old_size = symtab->size;
20932   offset_type i;
20933   struct symtab_index_entry **old_entries = symtab->data;
20934
20935   symtab->size *= 2;
20936   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20937
20938   for (i = 0; i < old_size; ++i)
20939     {
20940       if (old_entries[i])
20941         {
20942           struct symtab_index_entry **slot = find_slot (symtab,
20943                                                         old_entries[i]->name);
20944           *slot = old_entries[i];
20945         }
20946     }
20947
20948   xfree (old_entries);
20949 }
20950
20951 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20952    CU_INDEX is the index of the CU in which the symbol appears.
20953    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20954
20955 static void
20956 add_index_entry (struct mapped_symtab *symtab, const char *name,
20957                  int is_static, gdb_index_symbol_kind kind,
20958                  offset_type cu_index)
20959 {
20960   struct symtab_index_entry **slot;
20961   offset_type cu_index_and_attrs;
20962
20963   ++symtab->n_elements;
20964   if (4 * symtab->n_elements / 3 >= symtab->size)
20965     hash_expand (symtab);
20966
20967   slot = find_slot (symtab, name);
20968   if (!*slot)
20969     {
20970       *slot = XNEW (struct symtab_index_entry);
20971       (*slot)->name = name;
20972       /* index_offset is set later.  */
20973       (*slot)->cu_indices = NULL;
20974     }
20975
20976   cu_index_and_attrs = 0;
20977   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20978   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20979   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20980
20981   /* We don't want to record an index value twice as we want to avoid the
20982      duplication.
20983      We process all global symbols and then all static symbols
20984      (which would allow us to avoid the duplication by only having to check
20985      the last entry pushed), but a symbol could have multiple kinds in one CU.
20986      To keep things simple we don't worry about the duplication here and
20987      sort and uniqufy the list after we've processed all symbols.  */
20988   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20989 }
20990
20991 /* qsort helper routine for uniquify_cu_indices.  */
20992
20993 static int
20994 offset_type_compare (const void *ap, const void *bp)
20995 {
20996   offset_type a = *(offset_type *) ap;
20997   offset_type b = *(offset_type *) bp;
20998
20999   return (a > b) - (b > a);
21000 }
21001
21002 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
21003
21004 static void
21005 uniquify_cu_indices (struct mapped_symtab *symtab)
21006 {
21007   int i;
21008
21009   for (i = 0; i < symtab->size; ++i)
21010     {
21011       struct symtab_index_entry *entry = symtab->data[i];
21012
21013       if (entry
21014           && entry->cu_indices != NULL)
21015         {
21016           unsigned int next_to_insert, next_to_check;
21017           offset_type last_value;
21018
21019           qsort (VEC_address (offset_type, entry->cu_indices),
21020                  VEC_length (offset_type, entry->cu_indices),
21021                  sizeof (offset_type), offset_type_compare);
21022
21023           last_value = VEC_index (offset_type, entry->cu_indices, 0);
21024           next_to_insert = 1;
21025           for (next_to_check = 1;
21026                next_to_check < VEC_length (offset_type, entry->cu_indices);
21027                ++next_to_check)
21028             {
21029               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
21030                   != last_value)
21031                 {
21032                   last_value = VEC_index (offset_type, entry->cu_indices,
21033                                           next_to_check);
21034                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
21035                                last_value);
21036                   ++next_to_insert;
21037                 }
21038             }
21039           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
21040         }
21041     }
21042 }
21043
21044 /* Add a vector of indices to the constant pool.  */
21045
21046 static offset_type
21047 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
21048                       struct symtab_index_entry *entry)
21049 {
21050   void **slot;
21051
21052   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
21053   if (!*slot)
21054     {
21055       offset_type len = VEC_length (offset_type, entry->cu_indices);
21056       offset_type val = MAYBE_SWAP (len);
21057       offset_type iter;
21058       int i;
21059
21060       *slot = entry;
21061       entry->index_offset = obstack_object_size (cpool);
21062
21063       obstack_grow (cpool, &val, sizeof (val));
21064       for (i = 0;
21065            VEC_iterate (offset_type, entry->cu_indices, i, iter);
21066            ++i)
21067         {
21068           val = MAYBE_SWAP (iter);
21069           obstack_grow (cpool, &val, sizeof (val));
21070         }
21071     }
21072   else
21073     {
21074       struct symtab_index_entry *old_entry = *slot;
21075       entry->index_offset = old_entry->index_offset;
21076       entry = old_entry;
21077     }
21078   return entry->index_offset;
21079 }
21080
21081 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
21082    constant pool entries going into the obstack CPOOL.  */
21083
21084 static void
21085 write_hash_table (struct mapped_symtab *symtab,
21086                   struct obstack *output, struct obstack *cpool)
21087 {
21088   offset_type i;
21089   htab_t symbol_hash_table;
21090   htab_t str_table;
21091
21092   symbol_hash_table = create_symbol_hash_table ();
21093   str_table = create_strtab ();
21094
21095   /* We add all the index vectors to the constant pool first, to
21096      ensure alignment is ok.  */
21097   for (i = 0; i < symtab->size; ++i)
21098     {
21099       if (symtab->data[i])
21100         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21101     }
21102
21103   /* Now write out the hash table.  */
21104   for (i = 0; i < symtab->size; ++i)
21105     {
21106       offset_type str_off, vec_off;
21107
21108       if (symtab->data[i])
21109         {
21110           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21111           vec_off = symtab->data[i]->index_offset;
21112         }
21113       else
21114         {
21115           /* While 0 is a valid constant pool index, it is not valid
21116              to have 0 for both offsets.  */
21117           str_off = 0;
21118           vec_off = 0;
21119         }
21120
21121       str_off = MAYBE_SWAP (str_off);
21122       vec_off = MAYBE_SWAP (vec_off);
21123
21124       obstack_grow (output, &str_off, sizeof (str_off));
21125       obstack_grow (output, &vec_off, sizeof (vec_off));
21126     }
21127
21128   htab_delete (str_table);
21129   htab_delete (symbol_hash_table);
21130 }
21131
21132 /* Struct to map psymtab to CU index in the index file.  */
21133 struct psymtab_cu_index_map
21134 {
21135   struct partial_symtab *psymtab;
21136   unsigned int cu_index;
21137 };
21138
21139 static hashval_t
21140 hash_psymtab_cu_index (const void *item)
21141 {
21142   const struct psymtab_cu_index_map *map = item;
21143
21144   return htab_hash_pointer (map->psymtab);
21145 }
21146
21147 static int
21148 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21149 {
21150   const struct psymtab_cu_index_map *lhs = item_lhs;
21151   const struct psymtab_cu_index_map *rhs = item_rhs;
21152
21153   return lhs->psymtab == rhs->psymtab;
21154 }
21155
21156 /* Helper struct for building the address table.  */
21157 struct addrmap_index_data
21158 {
21159   struct objfile *objfile;
21160   struct obstack *addr_obstack;
21161   htab_t cu_index_htab;
21162
21163   /* Non-zero if the previous_* fields are valid.
21164      We can't write an entry until we see the next entry (since it is only then
21165      that we know the end of the entry).  */
21166   int previous_valid;
21167   /* Index of the CU in the table of all CUs in the index file.  */
21168   unsigned int previous_cu_index;
21169   /* Start address of the CU.  */
21170   CORE_ADDR previous_cu_start;
21171 };
21172
21173 /* Write an address entry to OBSTACK.  */
21174
21175 static void
21176 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21177                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21178 {
21179   offset_type cu_index_to_write;
21180   gdb_byte addr[8];
21181   CORE_ADDR baseaddr;
21182
21183   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21184
21185   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21186   obstack_grow (obstack, addr, 8);
21187   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21188   obstack_grow (obstack, addr, 8);
21189   cu_index_to_write = MAYBE_SWAP (cu_index);
21190   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21191 }
21192
21193 /* Worker function for traversing an addrmap to build the address table.  */
21194
21195 static int
21196 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21197 {
21198   struct addrmap_index_data *data = datap;
21199   struct partial_symtab *pst = obj;
21200
21201   if (data->previous_valid)
21202     add_address_entry (data->objfile, data->addr_obstack,
21203                        data->previous_cu_start, start_addr,
21204                        data->previous_cu_index);
21205
21206   data->previous_cu_start = start_addr;
21207   if (pst != NULL)
21208     {
21209       struct psymtab_cu_index_map find_map, *map;
21210       find_map.psymtab = pst;
21211       map = htab_find (data->cu_index_htab, &find_map);
21212       gdb_assert (map != NULL);
21213       data->previous_cu_index = map->cu_index;
21214       data->previous_valid = 1;
21215     }
21216   else
21217       data->previous_valid = 0;
21218
21219   return 0;
21220 }
21221
21222 /* Write OBJFILE's address map to OBSTACK.
21223    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21224    in the index file.  */
21225
21226 static void
21227 write_address_map (struct objfile *objfile, struct obstack *obstack,
21228                    htab_t cu_index_htab)
21229 {
21230   struct addrmap_index_data addrmap_index_data;
21231
21232   /* When writing the address table, we have to cope with the fact that
21233      the addrmap iterator only provides the start of a region; we have to
21234      wait until the next invocation to get the start of the next region.  */
21235
21236   addrmap_index_data.objfile = objfile;
21237   addrmap_index_data.addr_obstack = obstack;
21238   addrmap_index_data.cu_index_htab = cu_index_htab;
21239   addrmap_index_data.previous_valid = 0;
21240
21241   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21242                    &addrmap_index_data);
21243
21244   /* It's highly unlikely the last entry (end address = 0xff...ff)
21245      is valid, but we should still handle it.
21246      The end address is recorded as the start of the next region, but that
21247      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21248      anyway.  */
21249   if (addrmap_index_data.previous_valid)
21250     add_address_entry (objfile, obstack,
21251                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21252                        addrmap_index_data.previous_cu_index);
21253 }
21254
21255 /* Return the symbol kind of PSYM.  */
21256
21257 static gdb_index_symbol_kind
21258 symbol_kind (struct partial_symbol *psym)
21259 {
21260   domain_enum domain = PSYMBOL_DOMAIN (psym);
21261   enum address_class aclass = PSYMBOL_CLASS (psym);
21262
21263   switch (domain)
21264     {
21265     case VAR_DOMAIN:
21266       switch (aclass)
21267         {
21268         case LOC_BLOCK:
21269           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21270         case LOC_TYPEDEF:
21271           return GDB_INDEX_SYMBOL_KIND_TYPE;
21272         case LOC_COMPUTED:
21273         case LOC_CONST_BYTES:
21274         case LOC_OPTIMIZED_OUT:
21275         case LOC_STATIC:
21276           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21277         case LOC_CONST:
21278           /* Note: It's currently impossible to recognize psyms as enum values
21279              short of reading the type info.  For now punt.  */
21280           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21281         default:
21282           /* There are other LOC_FOO values that one might want to classify
21283              as variables, but dwarf2read.c doesn't currently use them.  */
21284           return GDB_INDEX_SYMBOL_KIND_OTHER;
21285         }
21286     case STRUCT_DOMAIN:
21287       return GDB_INDEX_SYMBOL_KIND_TYPE;
21288     default:
21289       return GDB_INDEX_SYMBOL_KIND_OTHER;
21290     }
21291 }
21292
21293 /* Add a list of partial symbols to SYMTAB.  */
21294
21295 static void
21296 write_psymbols (struct mapped_symtab *symtab,
21297                 htab_t psyms_seen,
21298                 struct partial_symbol **psymp,
21299                 int count,
21300                 offset_type cu_index,
21301                 int is_static)
21302 {
21303   for (; count-- > 0; ++psymp)
21304     {
21305       struct partial_symbol *psym = *psymp;
21306       void **slot;
21307
21308       if (SYMBOL_LANGUAGE (psym) == language_ada)
21309         error (_("Ada is not currently supported by the index"));
21310
21311       /* Only add a given psymbol once.  */
21312       slot = htab_find_slot (psyms_seen, psym, INSERT);
21313       if (!*slot)
21314         {
21315           gdb_index_symbol_kind kind = symbol_kind (psym);
21316
21317           *slot = psym;
21318           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21319                            is_static, kind, cu_index);
21320         }
21321     }
21322 }
21323
21324 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21325    exception if there is an error.  */
21326
21327 static void
21328 write_obstack (FILE *file, struct obstack *obstack)
21329 {
21330   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21331               file)
21332       != obstack_object_size (obstack))
21333     error (_("couldn't data write to file"));
21334 }
21335
21336 /* Unlink a file if the argument is not NULL.  */
21337
21338 static void
21339 unlink_if_set (void *p)
21340 {
21341   char **filename = p;
21342   if (*filename)
21343     unlink (*filename);
21344 }
21345
21346 /* A helper struct used when iterating over debug_types.  */
21347 struct signatured_type_index_data
21348 {
21349   struct objfile *objfile;
21350   struct mapped_symtab *symtab;
21351   struct obstack *types_list;
21352   htab_t psyms_seen;
21353   int cu_index;
21354 };
21355
21356 /* A helper function that writes a single signatured_type to an
21357    obstack.  */
21358
21359 static int
21360 write_one_signatured_type (void **slot, void *d)
21361 {
21362   struct signatured_type_index_data *info = d;
21363   struct signatured_type *entry = (struct signatured_type *) *slot;
21364   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21365   gdb_byte val[8];
21366
21367   write_psymbols (info->symtab,
21368                   info->psyms_seen,
21369                   info->objfile->global_psymbols.list
21370                   + psymtab->globals_offset,
21371                   psymtab->n_global_syms, info->cu_index,
21372                   0);
21373   write_psymbols (info->symtab,
21374                   info->psyms_seen,
21375                   info->objfile->static_psymbols.list
21376                   + psymtab->statics_offset,
21377                   psymtab->n_static_syms, info->cu_index,
21378                   1);
21379
21380   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21381                           entry->per_cu.offset.sect_off);
21382   obstack_grow (info->types_list, val, 8);
21383   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21384                           entry->type_offset_in_tu.cu_off);
21385   obstack_grow (info->types_list, val, 8);
21386   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21387   obstack_grow (info->types_list, val, 8);
21388
21389   ++info->cu_index;
21390
21391   return 1;
21392 }
21393
21394 /* Recurse into all "included" dependencies and write their symbols as
21395    if they appeared in this psymtab.  */
21396
21397 static void
21398 recursively_write_psymbols (struct objfile *objfile,
21399                             struct partial_symtab *psymtab,
21400                             struct mapped_symtab *symtab,
21401                             htab_t psyms_seen,
21402                             offset_type cu_index)
21403 {
21404   int i;
21405
21406   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21407     if (psymtab->dependencies[i]->user != NULL)
21408       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21409                                   symtab, psyms_seen, cu_index);
21410
21411   write_psymbols (symtab,
21412                   psyms_seen,
21413                   objfile->global_psymbols.list + psymtab->globals_offset,
21414                   psymtab->n_global_syms, cu_index,
21415                   0);
21416   write_psymbols (symtab,
21417                   psyms_seen,
21418                   objfile->static_psymbols.list + psymtab->statics_offset,
21419                   psymtab->n_static_syms, cu_index,
21420                   1);
21421 }
21422
21423 /* Create an index file for OBJFILE in the directory DIR.  */
21424
21425 static void
21426 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21427 {
21428   struct cleanup *cleanup;
21429   char *filename, *cleanup_filename;
21430   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21431   struct obstack cu_list, types_cu_list;
21432   int i;
21433   FILE *out_file;
21434   struct mapped_symtab *symtab;
21435   offset_type val, size_of_contents, total_len;
21436   struct stat st;
21437   htab_t psyms_seen;
21438   htab_t cu_index_htab;
21439   struct psymtab_cu_index_map *psymtab_cu_index_map;
21440
21441   if (dwarf2_per_objfile->using_index)
21442     error (_("Cannot use an index to create the index"));
21443
21444   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21445     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21446
21447   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21448     return;
21449
21450   if (stat (objfile_name (objfile), &st) < 0)
21451     perror_with_name (objfile_name (objfile));
21452
21453   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
21454                      INDEX_SUFFIX, (char *) NULL);
21455   cleanup = make_cleanup (xfree, filename);
21456
21457   out_file = gdb_fopen_cloexec (filename, "wb");
21458   if (!out_file)
21459     error (_("Can't open `%s' for writing"), filename);
21460
21461   cleanup_filename = filename;
21462   make_cleanup (unlink_if_set, &cleanup_filename);
21463
21464   symtab = create_mapped_symtab ();
21465   make_cleanup (cleanup_mapped_symtab, symtab);
21466
21467   obstack_init (&addr_obstack);
21468   make_cleanup_obstack_free (&addr_obstack);
21469
21470   obstack_init (&cu_list);
21471   make_cleanup_obstack_free (&cu_list);
21472
21473   obstack_init (&types_cu_list);
21474   make_cleanup_obstack_free (&types_cu_list);
21475
21476   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21477                                   NULL, xcalloc, xfree);
21478   make_cleanup_htab_delete (psyms_seen);
21479
21480   /* While we're scanning CU's create a table that maps a psymtab pointer
21481      (which is what addrmap records) to its index (which is what is recorded
21482      in the index file).  This will later be needed to write the address
21483      table.  */
21484   cu_index_htab = htab_create_alloc (100,
21485                                      hash_psymtab_cu_index,
21486                                      eq_psymtab_cu_index,
21487                                      NULL, xcalloc, xfree);
21488   make_cleanup_htab_delete (cu_index_htab);
21489   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21490     xmalloc (sizeof (struct psymtab_cu_index_map)
21491              * dwarf2_per_objfile->n_comp_units);
21492   make_cleanup (xfree, psymtab_cu_index_map);
21493
21494   /* The CU list is already sorted, so we don't need to do additional
21495      work here.  Also, the debug_types entries do not appear in
21496      all_comp_units, but only in their own hash table.  */
21497   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21498     {
21499       struct dwarf2_per_cu_data *per_cu
21500         = dwarf2_per_objfile->all_comp_units[i];
21501       struct partial_symtab *psymtab = per_cu->v.psymtab;
21502       gdb_byte val[8];
21503       struct psymtab_cu_index_map *map;
21504       void **slot;
21505
21506       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21507          It may be referenced from a local scope but in such case it does not
21508          need to be present in .gdb_index.  */
21509       if (psymtab == NULL)
21510         continue;
21511
21512       if (psymtab->user == NULL)
21513         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21514
21515       map = &psymtab_cu_index_map[i];
21516       map->psymtab = psymtab;
21517       map->cu_index = i;
21518       slot = htab_find_slot (cu_index_htab, map, INSERT);
21519       gdb_assert (slot != NULL);
21520       gdb_assert (*slot == NULL);
21521       *slot = map;
21522
21523       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21524                               per_cu->offset.sect_off);
21525       obstack_grow (&cu_list, val, 8);
21526       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21527       obstack_grow (&cu_list, val, 8);
21528     }
21529
21530   /* Dump the address map.  */
21531   write_address_map (objfile, &addr_obstack, cu_index_htab);
21532
21533   /* Write out the .debug_type entries, if any.  */
21534   if (dwarf2_per_objfile->signatured_types)
21535     {
21536       struct signatured_type_index_data sig_data;
21537
21538       sig_data.objfile = objfile;
21539       sig_data.symtab = symtab;
21540       sig_data.types_list = &types_cu_list;
21541       sig_data.psyms_seen = psyms_seen;
21542       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21543       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21544                               write_one_signatured_type, &sig_data);
21545     }
21546
21547   /* Now that we've processed all symbols we can shrink their cu_indices
21548      lists.  */
21549   uniquify_cu_indices (symtab);
21550
21551   obstack_init (&constant_pool);
21552   make_cleanup_obstack_free (&constant_pool);
21553   obstack_init (&symtab_obstack);
21554   make_cleanup_obstack_free (&symtab_obstack);
21555   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21556
21557   obstack_init (&contents);
21558   make_cleanup_obstack_free (&contents);
21559   size_of_contents = 6 * sizeof (offset_type);
21560   total_len = size_of_contents;
21561
21562   /* The version number.  */
21563   val = MAYBE_SWAP (8);
21564   obstack_grow (&contents, &val, sizeof (val));
21565
21566   /* The offset of the CU list from the start of the file.  */
21567   val = MAYBE_SWAP (total_len);
21568   obstack_grow (&contents, &val, sizeof (val));
21569   total_len += obstack_object_size (&cu_list);
21570
21571   /* The offset of the types CU list from the start of the file.  */
21572   val = MAYBE_SWAP (total_len);
21573   obstack_grow (&contents, &val, sizeof (val));
21574   total_len += obstack_object_size (&types_cu_list);
21575
21576   /* The offset of the address table from the start of the file.  */
21577   val = MAYBE_SWAP (total_len);
21578   obstack_grow (&contents, &val, sizeof (val));
21579   total_len += obstack_object_size (&addr_obstack);
21580
21581   /* The offset of the symbol table from the start of the file.  */
21582   val = MAYBE_SWAP (total_len);
21583   obstack_grow (&contents, &val, sizeof (val));
21584   total_len += obstack_object_size (&symtab_obstack);
21585
21586   /* The offset of the constant pool from the start of the file.  */
21587   val = MAYBE_SWAP (total_len);
21588   obstack_grow (&contents, &val, sizeof (val));
21589   total_len += obstack_object_size (&constant_pool);
21590
21591   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21592
21593   write_obstack (out_file, &contents);
21594   write_obstack (out_file, &cu_list);
21595   write_obstack (out_file, &types_cu_list);
21596   write_obstack (out_file, &addr_obstack);
21597   write_obstack (out_file, &symtab_obstack);
21598   write_obstack (out_file, &constant_pool);
21599
21600   fclose (out_file);
21601
21602   /* We want to keep the file, so we set cleanup_filename to NULL
21603      here.  See unlink_if_set.  */
21604   cleanup_filename = NULL;
21605
21606   do_cleanups (cleanup);
21607 }
21608
21609 /* Implementation of the `save gdb-index' command.
21610    
21611    Note that the file format used by this command is documented in the
21612    GDB manual.  Any changes here must be documented there.  */
21613
21614 static void
21615 save_gdb_index_command (char *arg, int from_tty)
21616 {
21617   struct objfile *objfile;
21618
21619   if (!arg || !*arg)
21620     error (_("usage: save gdb-index DIRECTORY"));
21621
21622   ALL_OBJFILES (objfile)
21623   {
21624     struct stat st;
21625
21626     /* If the objfile does not correspond to an actual file, skip it.  */
21627     if (stat (objfile_name (objfile), &st) < 0)
21628       continue;
21629
21630     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21631     if (dwarf2_per_objfile)
21632       {
21633         volatile struct gdb_exception except;
21634
21635         TRY_CATCH (except, RETURN_MASK_ERROR)
21636           {
21637             write_psymtabs_to_index (objfile, arg);
21638           }
21639         if (except.reason < 0)
21640           exception_fprintf (gdb_stderr, except,
21641                              _("Error while writing index for `%s': "),
21642                              objfile_name (objfile));
21643       }
21644   }
21645 }
21646
21647 \f
21648
21649 int dwarf2_always_disassemble;
21650
21651 static void
21652 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21653                                 struct cmd_list_element *c, const char *value)
21654 {
21655   fprintf_filtered (file,
21656                     _("Whether to always disassemble "
21657                       "DWARF expressions is %s.\n"),
21658                     value);
21659 }
21660
21661 static void
21662 show_check_physname (struct ui_file *file, int from_tty,
21663                      struct cmd_list_element *c, const char *value)
21664 {
21665   fprintf_filtered (file,
21666                     _("Whether to check \"physname\" is %s.\n"),
21667                     value);
21668 }
21669
21670 void _initialize_dwarf2_read (void);
21671
21672 void
21673 _initialize_dwarf2_read (void)
21674 {
21675   struct cmd_list_element *c;
21676
21677   dwarf2_objfile_data_key
21678     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21679
21680   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21681 Set DWARF 2 specific variables.\n\
21682 Configure DWARF 2 variables such as the cache size"),
21683                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21684                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21685
21686   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21687 Show DWARF 2 specific variables\n\
21688 Show DWARF 2 variables such as the cache size"),
21689                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21690                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21691
21692   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21693                             &dwarf2_max_cache_age, _("\
21694 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21695 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21696 A higher limit means that cached compilation units will be stored\n\
21697 in memory longer, and more total memory will be used.  Zero disables\n\
21698 caching, which can slow down startup."),
21699                             NULL,
21700                             show_dwarf2_max_cache_age,
21701                             &set_dwarf2_cmdlist,
21702                             &show_dwarf2_cmdlist);
21703
21704   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21705                            &dwarf2_always_disassemble, _("\
21706 Set whether `info address' always disassembles DWARF expressions."), _("\
21707 Show whether `info address' always disassembles DWARF expressions."), _("\
21708 When enabled, DWARF expressions are always printed in an assembly-like\n\
21709 syntax.  When disabled, expressions will be printed in a more\n\
21710 conversational style, when possible."),
21711                            NULL,
21712                            show_dwarf2_always_disassemble,
21713                            &set_dwarf2_cmdlist,
21714                            &show_dwarf2_cmdlist);
21715
21716   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21717 Set debugging of the dwarf2 reader."), _("\
21718 Show debugging of the dwarf2 reader."), _("\
21719 When enabled, debugging messages are printed during dwarf2 reading\n\
21720 and symtab expansion."),
21721                             NULL,
21722                             NULL,
21723                             &setdebuglist, &showdebuglist);
21724
21725   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21726 Set debugging of the dwarf2 DIE reader."), _("\
21727 Show debugging of the dwarf2 DIE reader."), _("\
21728 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21729 The value is the maximum depth to print."),
21730                              NULL,
21731                              NULL,
21732                              &setdebuglist, &showdebuglist);
21733
21734   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21735 Set cross-checking of \"physname\" code against demangler."), _("\
21736 Show cross-checking of \"physname\" code against demangler."), _("\
21737 When enabled, GDB's internal \"physname\" code is checked against\n\
21738 the demangler."),
21739                            NULL, show_check_physname,
21740                            &setdebuglist, &showdebuglist);
21741
21742   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21743                            no_class, &use_deprecated_index_sections, _("\
21744 Set whether to use deprecated gdb_index sections."), _("\
21745 Show whether to use deprecated gdb_index sections."), _("\
21746 When enabled, deprecated .gdb_index sections are used anyway.\n\
21747 Normally they are ignored either because of a missing feature or\n\
21748 performance issue.\n\
21749 Warning: This option must be enabled before gdb reads the file."),
21750                            NULL,
21751                            NULL,
21752                            &setlist, &showlist);
21753
21754   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21755                _("\
21756 Save a gdb-index file.\n\
21757 Usage: save gdb-index DIRECTORY"),
21758                &save_cmdlist);
21759   set_cmd_completer (c, filename_completer);
21760
21761   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21762                                                         &dwarf2_locexpr_funcs);
21763   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21764                                                         &dwarf2_loclist_funcs);
21765
21766   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21767                                         &dwarf2_block_frame_base_locexpr_funcs);
21768   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21769                                         &dwarf2_block_frame_base_loclist_funcs);
21770 }